Refactor board_randomizer

- Make file read separate and return "dice" or a list of strings from
  dice handling functions for use in downstream programs
This commit is contained in:
2022-09-26 11:40:36 -04:00
parent f18c30cb60
commit 21aab46b96
+10 -10
View File
@@ -4,9 +4,9 @@ from random import randint, shuffle
from math import sqrt
from os import path
def read_dice_file(path):
def read_dice_file(dice_path: str):
'''Return list of die strings from file ignoring all comments (#)'''
with open(path, 'r+', encoding="utf-8") as file:
with open(path.abspath(dice_path), 'r+', encoding="utf-8") as file:
return [line.rstrip().split(',') for line in file.readlines() if line[0] != "#"]
def roll_die(die: str):
@@ -17,20 +17,19 @@ def roll_dice(dice: list[str]):
'''Return a random roll for each die'''
return [ roll_die(die) for die in dice ]
def get_random_board(dice_path):
dice_strings = read_dice_file(dice_path)
shuffle(dice_strings)
rolls = roll_dice(dice_strings)
def get_random_board(dice: list[str]):
shuffle(dice)
rolls = roll_dice(dice)
# Format dice rolls for boards file
board_size = int(sqrt(len(rolls)))
board = []
for i in range(0, len(dice_strings), board_size):
for i in range(0, len(dice), board_size):
board.append(rolls[i:i+board_size])
return board
def get_random_board_csv(dice_path):
board = get_random_board(dice_path)
def get_random_board_csv(dice: list[str]):
board = get_random_board(dice)
board = [",".join(row) for row in board]
return board
@@ -39,7 +38,8 @@ if __name__ == '__main__':
print('Usage: python3 board_randomizer.py <dice_file>')
else:
try:
board = get_random_board_csv(path.abspath(argv[1]))
dice = read_dice_file(path.abspath(argv[1]))
board = get_random_board_csv(dice)
for row in board:
print(row)
except Exception as e: