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')
Esempio n. 2
0
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()
Esempio n. 3
0
 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)
Esempio n. 4
0
    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)
Esempio n. 5
0
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
Esempio n. 6
0
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
Esempio n. 7
0
 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)
Esempio n. 8
0
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)
Esempio n. 9
0
    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)
Esempio n. 10
0
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
Esempio n. 11
0
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
Esempio n. 12
0
    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))
Esempio n. 13
0
 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)
Esempio n. 14
0
 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()
Esempio n. 15
0
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)
Esempio n. 16
0
    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")
Esempio n. 17
0
def play_solitaire_test(choose_dice,
                        choose_category,
                        optimal_policy,
                        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)
        best_cat = optimal_policy.choose_category(sheet, roll)
        if not cat == best_cat:
            print(cat, best_cat, roll.as_list(), sheet.as_csv())
        sheet.mark(cat, roll)
    # print("=========GAME OVER==========")

    return sheet.grand_total()
Esempio n. 18
0
 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)
Esempio n. 19
0
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)
Esempio n. 20
0
keysBinds=[
    ["F1","F7","F13","F19"],
    ["F2","F8","F14","F20"],
    ["F3","F9","F15","F21"],
    ["F4","F10","F16","F22"],
    ["F5","F11","F17","F23"],
    ["F6","F12","F18","F24"],
]
set1= [4,17,27,22]
set2 = [10,9,11,7]
set3 = [15,18,23,24]
set4= [12,16,20,21]
set5= [6,13,19,26]
set6= [5,3,2,14]

choc=Roll(set1,"Choc",400)
led2=Roll(set2,"SX-MINI",100)
mx=Roll(set3,"Mx",400)
led1=Roll(set4,"SX6812-E",100)
diode=Roll(set5,"Diode",100)
led3=Roll(set6,"SX-50-50",100)


rolls=[
    led3,
    led1,
    led2,
    choc,
    mx,
   diode,
]
Esempio n. 21
0
def app():
    app_ = Roll()
    traceback(app_)
    return app_
Esempio n. 22
0
                    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_choose():
    roll = Roll()
    choice = roll.choose()
    assert choice == "Rock"
Esempio n. 24
0
        roll_number += 1

        print("\nRound ",
              round_number,
              " - Roll ",
              roll_number,
              " - Point ",
              point,
              sep='')

        # get user input for dice
        die1 = ask_roll(1)
        die2 = ask_roll(2)

        # create Roll object with each die
        roll = Roll(die1, die2)
        dice_total = roll.get_dice_total()

        # append every roll to a list
        roll_list.append(roll)
        print(dice_total)

        # if comeout roll
        if (roll_number == 1):
            # if craps -- don't pass win
            if (dice_total == 2 or dice_total == 3):
                round_over = 1
                print("Result: Craps")

            # if craps -- don't pass push
            elif (dice_total == 12):
Esempio n. 25
0
from roll import Roll
from admin import Admin
from profile import Profile
from information import Information
from wishlist import Wishlist
from trade import Trade
from images import Images

intents = discord.Intents.default()
intents.members = True

load_dotenv()
BOT_TOKEN = os.getenv('BOT_TOKEN')
bot = commands.Bot(command_prefix='*', intents=intents)

bot.add_cog(Roll(bot))
bot.add_cog(Admin(bot))
bot.add_cog(Profile(bot))
bot.add_cog(Information(bot))
bot.add_cog(Wishlist(bot))
bot.add_cog(Trade(bot))
bot.add_cog(Images(bot))

#### Bot commands ####


@bot.command()
async def ping(ctx):
    await ctx.message.delete()
    await ctx.send('Yup, I\'m awake.', delete_after=5)
Esempio n. 26
0
__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 build_the_three_rolls():
    rock = Roll('rock')
    paper = Roll('paper')
    scissors = Roll('scissors')
    rolls = [rock, paper, scissors]
    return rolls
Esempio n. 28
0
 def make_choice(self):
     if self.kind == 'computer':
         return Roll.random_choice()
     else:
         return Roll(input('Select rock, paper or scissors. '))
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
Esempio n. 30
0
 def choose_dice(self, sheet, roll, rolls_remaining):
     dice = optimal_strategy.queryMove(self.state_potentials,
                                       sheet.as_bitmask(), roll.as_list(),
                                       rolls_remaining)
     roll = Roll(dice)
     return roll