def getValidCategories(state, roll): local_time = time.time() * 10000.0 cats_to_probe = [] mroll = Roll(roll) if isJoker(mroll, state): if not (C_MASKS[mroll.sample_dice() - 1] & state ): # if one of the Yahtzee-making dice is not a used category cats_to_probe.append(C_MASKS[mroll.sample_dice() - 1]) # must use that upper category elif (not (C_FH & state) or not (C_SS & state) or not (C_LS & state) or not (C_3K & state) or not (C_4K & state) or not (C_C & state) ): # if upper category filled and lower categories open... for cat in C_MASKS[6:12]: # add all of the available lower cats if not (cat & state): cats_to_probe.append(cat) else: for cat in C_MASKS[ 0:6]: # otherwise, score a zero in one of the upper cats if not (cat & state): cats_to_probe.append(cat) else: # if not a joker, just add all available cats for cat in C_MASKS: if not (cat & state): cats_to_probe.append(cat) return cats_to_probe
def generateNNTrainingData(policy, state_potentials, new_training_title, n_trials): labelout = open("training/" + new_training_title, "a") sys.stdout.write('Generating training data') sys.stdout.flush() for x in range(0, n_trials): sheet, roll, n_rerolls = sample_gamespace(policy.choose_dice, policy.choose_category) opt_move = optimal_strategy.queryMove(state_potentials, sheet.as_bitmask(), roll.as_list(), n_rerolls) labeled_one_hot = None labelout.write(sheet.as_csv() + "," + roll.as_string() + "," + str(n_rerolls) + ",") try: best_category = YahtzeeScoresheet.categories[opt_move] labelout.write(best_category + ",") labeled_one_hot = label.build_one_hot(opt_move, 13) except (ValueError, TypeError) as e: kept_dice = Roll(opt_move) labelout.write("[" + kept_dice.as_string() + "],") labeled_one_hot = label.find_macro(kept_dice, roll, sheet, n_rerolls) labelout.write(labeled_one_hot + "\n") if x % 1000 == 0: sys.stdout.write('.') sys.stdout.flush() labelout.close()
def __find_child(self, mum): # find all children under a mum assert isinstance(mum, Tree) for item in mum.node: if item[0]: l = mum.row[item[1]] else: l = mum.col[item[1]] m = Roll(item[2], item[3], l) # print(item) # print(l) m.move() if item[0]: table = mum.row.copy() table[item[1]] = m.result # print(table) table_t = self.__transpose(table, self.n_col) # print(table_t) node_t = snap(table, table_t) else: table = mum.col.copy() table[item[1]] = m.result # print(table) table_t = self.__transpose(table, self.n_row) node_t = snap(table_t, table) if len(node_t) != 0: self.n += 1 if item[0]: child = Tree(node_t, self.n, table, table_t, item) else: child = Tree(node_t, self.n, table_t, table, item) mum.add_child(child)
async def _process_roll_character(self, message): c = self.kv.get(self._char_key(message)) if not c: await message.channel.send('You have not uploaded your character.') return tokens = message.content.strip().lower().split()[1:] skill = tokens[0] modifying_ability = SKILLS.get(skill, None) if not modifying_ability: await message.channel.send('{} is not supported.'.format(skill)) return ability = c['abilities'][modifying_ability] ability_modifier = (ability - 10) // 2 proficiency = c['proficiencies'][skill] level = c['level'] base_modifier = ability_modifier + proficiency + level extra_mods = [Modifier(m) for m in map(int, tokens[1:])] rolls = [DiceRoll(1, 20), Modifier(base_modifier)] rolls.extend(extra_mods) r = Roll(rolls) results, total = r.get() msg = "{} rolled `{}` for a total of `{}`".format( message.author.nick, ' + '.join(map(str, results)), total) msg += ": {}".format(skill) await message.channel.send(msg)
def generate_extra_info(self, char, print_extra_info): char.generate_info("build", Roll.a_dice("3d6")) char.generate_info("age", Roll.a_dice("3d6")) char.generate_info("appearence", Roll.a_dice("3d6")) if print_extra_info: print("Age: " + char.char_age) print("Appearence: " + char.char_appearence) print("Build: " + char.char_build)
def generate_extra_info(self, char, print_extra_info): char.generate_info("build", Roll.a_dice("3d6")) char.generate_info("odd_habit", Roll.a_dice("1d20")) char.generate_info("age", Roll.a_dice("3d6")) char.generate_info("appearence", Roll.a_dice("1d20")) if print_extra_info: print("Age: " + char.char_age) print("Distinctive Appearence: " + char.char_appearence) print("Build: " + char.char_build) print("Odd Habit: " + char.char_odd_habit)
def get_player_roll(): valid_choice = False while not valid_choice: choice = input("Choose Rock, Paper, or Scissors: ").lower() if choice == 'rock': return Roll('rock') elif choice == 'paper': return Roll('paper') elif choice == 'scissors': return Roll('scissors')
def getNewState(state, roll, c, marginal_upper_total): new_state = state new_state += marginal_upper_total new_state += c mroll = Roll(roll) if c == C_Y and mroll.is_n_kind(5) and not ( new_state & YSCORED ): # if scoring in Y and roll is Y, activate possibility for Yahtzee bonus new_state += YSCORED return new_state
def generate_extra_info(self, char, print_extra_info): char.generate_info("form", Roll.a_dice("3d6")) char.generate_info("appearence", Roll.a_dice("3d6")) char.generate_info("purpose", Roll.a_dice("1d20")) char.generate_info("age", Roll.a_dice("3d6")) if print_extra_info: print("Form: " + char.char_form) print("Appearence: " + char.char_appearence) print("Purpose: " + char.char_purpose) print("Age: " + char.char_age)
def test_complex_roll_output(self): d1 = Dice(1, 20) d2 = Dice(2, 4) d3 = Dice(4, 8) roll = Roll([d1, d2, d3], [], Roll.ADVANTAGE) result = roll.roll() expected_output = ('Total: 39\n' '1d20: 13\n' '2d4: 3 | 2, 1\n' '4d8: 23 | 8, 1, 7, 7\n' 'Other roll: 35') self.assertEqual(str(result), expected_output)
def get_input(): questions = [ { 'type': 'list', 'name': 'system', 'message': 'What system are you using?', 'choices': ['5e', 'Pathfinder'] }, { 'type': 'input', 'name': 'ac', 'message': 'What AC are you attacking against?\n >', 'validate': lambda val: is_num(val) }, { 'type': 'input', 'name': 'attack', 'message': "What's your to-hit bonus?\n >", 'validate': lambda val: is_num(str(val).replace('+', '')) }, { 'type': 'input', 'name': 'base_damage', 'message': "What's your regular damage?\n >" }, { 'type': 'input', 'name': 'crit_damage', 'message': "What's your critical hit damage?\n >" }, { 'type': 'list', 'name': 'crit_range', 'message': "What's your critical hit chance?", 'choices': ['5%', '10%', '15%', '20%', '25%', '30%'], 'when': lambda answers: answers['system'] == 'Pathfinder' } ] answers = prompt(questions) for key in ('ac', 'attack'): if key in answers.keys(): answers[key] = float(answers[key]) if 'crit_range' in answers.keys(): if answers['crit_range'][-1] == '%': answers['crit_range'] = answers['crit_range'][:-1] answers['crit_range'] = int(answers['crit_range']) / 100. for key in ('base_damage', 'crit_damage'): if key in answers.keys(): damage_roll = Roll(answers[key]) answers[key] = damage_roll.average() return answers
def __find_child(self, mum, pointy_mum): # find all children under a mum assert isinstance(mum, Tree) for item in mum.node: if item[0]: l = mum.row[item[1]] else: l = mum.col[item[1]] m = Roll(item[2], item[3], l) # print(item) # print(l) m.move() if item[0]: table = mum.row.copy() table[item[1]] = m.result # print(table) table_t = self.__transpose(table, self.n_col) # print(table_t) node_t = snap(table, table_t) else: table = mum.col.copy() table[item[1]] = m.result # print(table) table_t = self.__transpose(table, self.n_row) node_t = snap(table_t, table) if len(node_t) != 0: self.n += 1 if item[0]: child = Tree(node_t, self.n, table, table_t, item) else: child = Tree(node_t, self.n, table_t, table, item) n_row = 0 n_col = 0 for i in mum.row.keys(): if len(mum.row[i]) > 0: # not empty n_row += 1 for i in mum.col.keys(): if len(mum.col[i]) > 0: n_col += 1 if n_row == 1 or n_col == 1: # solution found solution = True else: solution = False pointy_child = PointyTree(self.n, pointy_mum.mum, solution, children=None) pointy_child.add_point(child) mum.add_child(child) pointy_mum.add_child(pointy_child)
def startGame(self): self.roll = Roll() self.score = Score() self.score.clearScore() self.currentPlayer = 1 self.currentTurn = 1 self.clearDisplay(0) self.clearDisplay(1) self.remainRoll.setText('3') self.roll.clearRollCount() self.rollButton.setEnabled(True) self.buttonSetting() self.currentPlayer = 0 self.colorSetting(0) self.scoreTypeClear()
def scoreRoll(state, dice, c): roll = Roll(dice) score = index_to_function[cat_to_index[c]](roll, state) marginal_upper_total = ( score % 100 ) if c >= C_SIXES else 0 # if 1s, 2s, ... 6s, marginal upper total cannot include bonuses return score, marginal_upper_total
def _advance_to_nearest_utility(player, state): electric_company = INDEX[ELECTRIC_COMPANY] water_works = INDEX[WATER_WORKS] nearest_utility = Card._nearest_to(player.position, [electric_company, water_works]) roll = Roll().value return Card._advance_to_square(player, nearest_utility, roll, state)
def evaluate_blank(args: list, i: int) -> str: while blank in args[i]: if i + 1 == len(args): raise util.ParseException( "Failure: missing value for _ in '{}'".format(args[i])) if blank in args[i + 1]: # parse that blank first evaluate_blank(args, i + 1) # replace blanks with next value after executed if args[i + 1] == left_sep: # if the next arg is the beginning of a group, parse and execute the group depth = 0 j = i + 1 while depth >= 0: j += 1 depth += 1 if args[j] == left_sep else ( -1 if args[j] == right_sep else 0) nextvalue = str(Group(args[i + 2:j]).execute(print_rolls=False)) del args[i + 1:j + 1] elif expression.is_expression(args[i + 1]): # if the arg is an expression, evaluate it nextvalue = str(int(expression.parse_math(args[i + 1]))) del args[i + 1] elif table.is_table(args[i + 1]): nextvalue = table.Table(args[i + 1]).execute() del args[i + 1] else: # try to parse next arg as a roll nextvalue = str(Roll(args[i + 1]).execute(print_output=False)) del args[i + 1] # replace blank with resulting value args[i] = args[i].replace(blank, nextvalue, 1)
def sample_gamespace(choose_dice, choose_category): ''' Returns the score earned in one game played with the policy defined by the two given functions. Each position is logged with the given function. choose_dice -- a function that takes a scoresheet, roll, and number of rerolls, returns a subroll of the roll choose_category -- a function that takes a non-filled scoresheet and a roll and returns the index of an unused category on that scoresheet log -- a function that takes a scoresheet, roll, and number of rerolls ''' # start with empty scoresheet sheet = YahtzeeScoresheet() rand = random.randint(0, 38) it = 0 while not sheet.game_over(): # do the initial roll roll = Roll() roll.reroll() # reroll twice for i in [2, 1]: if it == rand: return (sheet, roll, i) it += 1 # choose dice to keep keep = choose_dice(sheet, roll, i) if not keep.subroll(roll): raise ValueError("dice to keep %s not a subset of roll %s" % (keep.as_list(), roll.as_list())) keep.reroll() roll = keep if it == rand: return (sheet, roll, 0) it += 1 # choose category to use and mark it cat = choose_category(sheet, roll) sheet.mark(cat, roll) return (None, None, None)
def run(self): num_players = len(self._state.players) idx = random.randint(0, num_players - 1) while not self._completed(): # cash = [player.cash for player in self._state.players] # print cash player = self._state.players[idx] idx = (idx + 1) % len(self._state.players) roll = Roll() print '%s rolled a %d%s' % (player.name, roll.value, ' (doubles)' if roll.is_doubles else '') if player.jail_moves > 0 and roll.is_doubles: self._state.apply( GroupOfChanges( changes=[GameStateChange.leave_jail(player)])) elif player.jail_moves >= 2: self._state.apply( GroupOfChanges( changes=[GameStateChange.decrement_jail_moves(player) ])) self._wait() continue elif player.jail_moves == 1: # TODO: Allow player to choose to use a "Get out of jail free" card pay_changes = player.pay(self._state.bank, 50, self._state) leave_changes = GroupOfChanges( changes=[GameStateChange.leave_jail(player)]) self._state.apply( GroupOfChanges.combine([pay_changes, leave_changes])) self._take_turn(player, roll.value) num_rolls = 0 max_rolls = 2 while roll.is_doubles: roll = Roll() print '%s rolled a %d%s' % (player.name, roll.value, ' (doubles)' if roll.is_doubles else '') num_rolls += 1 if num_rolls > max_rolls: self._state.apply( GroupOfChanges( changes=[GameStateChange.send_to_jail(player)])) break self._take_turn(player, roll.value)
def generate_extra_info(self, char, print_extra_info): char.generate_info("apparent_ancestry", Roll.a_dice("3d6")) char.generate_info("apparent_gender", Roll.a_dice("1d6")) char.generate_info("true_age", Roll.a_dice("3d6")) char.generate_info("quirk", Roll.a_dice("1d20")) print("Apparent Ancestry: " + char.char_apparent_ancestry) print("Apparent Gender: " + char.char_apparent_gender) print("True Age: " + char.char_true_age) print("Quirk: " + char.char_quirk) if "human" in char.char_apparent_ancestry: apparent_Ancestry = Human() elif "dwarf" in char.char_apparent_ancestry: apparent_Ancestry = Dwarf() elif "goblin" in char.char_apparent_ancestry: apparent_Ancestry = Goblin() elif "orc" in char.char_apparent_ancestry: apparent_Ancestry = Orc() apparent_Ancestry.generate_extra_info(apparent_Ancestry, False) print("Apparent Age: " + apparent_Ancestry.char_age) print("Apparent Build: " + apparent_Ancestry.char_build) print("Apparent Appearence: " + apparent_Ancestry.char_appearence)
def roll(self, count=1, goal=None): """Appends a roll to the dice's rolls list. """ self.check_vars() result = None if goal == None and self.__goal != None: goal = self.__goal for _ in range(count): value = randint(self.offset + 1, self.max_roll + self.offset + 1) if self.__func != None: result = self.__func(value) self.__rolls.insert(0, Roll(self, value, goal=goal, result=result))
def create_char(): character = random.choice( [Human(), Changeling(), Clockwork(), Dwarf(), Goblin(), Orc()]) character.generate_name() character.char_level = 0 character.generate_info("background", Roll.a_dice("1d20")) character.generate_info("personality", Roll.a_dice("3d6")) character.generate_profession(Roll.a_dice("1d20")) character.generate_personality(Roll.a_dice("1d20"), Roll.a_dice("1d20"), Roll.a_dice("1d20")) character.generate_interesting_things(Roll.a_dice("1d6"), Roll.a_dice("1d20")) character.generate_wealth(Roll.a_dice("3d6")) Printer.print_common_info(character) character.generate_extra_info(character, True) return render_template('index.html', character=character)
def generate_training_data(self, n_trials, all_data): for x in range(0, n_trials): current_line = "" sheet, roll, n_rerolls = sample_gamespace(self.choose_dice, self.choose_category) opt_move = optimal_strategy.queryMove(self.state_potentials, sheet.as_bitmask(), roll.as_list(), n_rerolls) labeled_one_hot = None current_line = sheet.as_csv() + "," + roll.as_string() + "," + str( n_rerolls) + "," try: # assume in this situation you choose a category to score in best_category = YahtzeeScoresheet.categories[opt_move] current_line += best_category + "," labeled_one_hot = label.build_one_hot(lookup_macro[opt_move], 10) except (ValueError, TypeError) as e: kept_dice = Roll(opt_move) current_line += "[" + kept_dice.as_string() + "]," labeled_one_hot = label.find_macro(kept_dice, roll, sheet, n_rerolls) current_line += labeled_one_hot + "\n" all_data.append(current_line)
def play_solitaire(choose_dice, choose_category, log=null_log): ''' Returns the score earned in one game played with the policy defined by the two given functions. Each position is logged with the given function. choose_dice -- a function that takes a scoresheet, roll, and number of rerolls, returns a subroll of the roll choose_category -- a function that takes a non-filled scoresheet and a roll and returns the index of an unused category on that scoresheet log -- a function that takes a scoresheet, roll, and number of rerolls ''' # start with empty scoresheet sheet = YahtzeeScoresheet() while not sheet.game_over(): # do the initial roll roll = Roll() roll.reroll() # reroll twice for i in [2, 1]: # choose dice to keep keep = choose_dice(sheet, roll, i) if not keep.subroll(roll): raise ValueError("dice to keep %s not a subset of roll %s" % (keep.as_list(), roll.as_list())) keep.reroll() roll = keep # choose category to use and mark it cat = choose_category(sheet, roll) sheet.mark(cat, roll) # print("=========GAME OVER==========") return sheet.grand_total()
def submit_dice(self, d1, d2): roll_number = self.game.get_roll_num() game_number = self.session.get_game_num() # Check if radio buttons were selected (0 if unselected) if (d1 > 0 and d2 > 0): roll = Roll(d1, d2) self.session.process_roll(roll) self.game.add_roll(roll) self.console_out("Gm " + str(game_number + 1) + "- Rd " + str(roll_number + 1) + ": " + str(d1) + " " + str(d2)) self.make_game_decision(roll) self.update_statistics() else: self.console_out("Select dice values before submitting")
def choose_dice_interactive(sheet, roll, rerolls): if rerolls == 2: print_scoresheet(sheet) print(roll) keep = None while keep is None: response = input("Select dice to keep (or 'all'):") if response == 'all': keep = roll else: try: keep = Roll.parse(response) if not keep.subroll(roll): keep = None print("select only dice in the current roll") except ValueError: keep = None print("select only dice in the current roll") return keep
def get_roll_response(self, message): """Creates rolls response text""" # Remove !roll from content reason = None split_command = [x.strip() for x in message.content[5:].split('!', 1)] if len(split_command) > 1: reason = split_command[1] print(split_command) roll = Roll.from_expr(split_command[0]) if not roll: return "Did not conform to spec: Check the docs, which there are none of." results, total = roll.get() msg = "{} rolled `{}` for a total of `{}`".format( message.author.nick, ' + '.join(map(str, results)), total) if reason: msg += ": {}".format(reason) return msg
import random from roll import Roll DRAW = 0 WIN = 1 LOSE = -1 roll = Roll() truth_table = roll.truth_table attack_options = roll.rolls class Player: def __init__(self, name): self.name = name self.score = 0 def attack(self): while True: print(f"{self.name}, select an attack:") roll.print_attack_options() attack = input("------->") try: attack_id = int(attack) attack = attack_options[attack_id] print(f"{self.name} chose to attack with {attack}") return attack except ValueError: raise except KeyError: raise
elif args[j] == left_sep: depth += 1 self.append(Group(args[i + 1:j], self.depth + 1)) i = j # check if it is an expression elif expression.is_expression(arg): self.append(expression.Expression(arg)) # check if it is a table elif table.is_table(arg): self.append(table.Table(arg)) # assume it is a normal roll else: self.append(Roll(arg)) # last line of code in the loop i += 1 if not self.all_tags[tags.YIELD]: self.__set_yield(firstStatFound or tags.TOTAL) self.__apply_supertags(self.all_tags) def __set_yield(self, stat: str): """Determines what the group returns upon execution""" self.all_tags[tags.YIELD] = tags.Tag(tags.YIELD, contents=stat) self.all_tags[stat] = tags.get_tag(stat, []) def __apply_supertags(self, _tags: list):
def test_from_str(self): r1 = Roll([Dice(1, 20), Dice(4, 6)], [5, -2], False) r2 = Roll.from_str('1d20+4d6+5-2', False) self.assertEqual(r1, r2)
def test_simple_roll_output_with_disadvantage(self): roll = Roll([Dice(1, 20)], [], Roll.DISADVANTAGE) result = roll.roll() expected_output = ('1d20: 5\n' 'Other roll: 19') self.assertEqual(str(result), expected_output)
__author__ = "Mikron" __version__ = "0.0-dev" from roll import Roll dice = [ 6, 6, 20 ] if __name__ == "__main__": rolls = Roll(dice) roll_results = rolls.get_rolls() for roll in roll_results: print("Roll: "+str(roll)+"\n")
def app(): app_ = Roll() traceback(app_) return app_
def make_choice(self): if self.kind == 'computer': return Roll.random_choice() else: return Roll(input('Select rock, paper or scissors. '))
import asyncio import os import uvloop from aiofile import AIOFile, Reader from roll import Roll from roll.extensions import cors, igniter, logger, simple_server, traceback asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = Roll() cors(app) logger(app) traceback(app) @app.route("/fullasync", methods=["POST"], lazy_body=True) async def fullasync(request, response): response.body = (chunk async for chunk in request) if __name__ == "__main__": simple_server(app)
def test_simple_roll_output(self): roll = Roll([Dice(1, 20)], []) result = roll.roll() expected_output = '1d20: 5' self.assertEqual(str(result), expected_output)