def __init__(self): self._dice = Dice(5, 6) self._scorecard = Scorecard() self._cur_rolls = 0 self._game_state = GS.NEED_ROLL self._state_action_map = { GS.NEED_ROLL: [GA.ROLL, GA.RESTART], GS.ROLLING: [GA.ROLL, GA.HOLD, GA.SCORE, GA.RESTART], GS.NO_MORE_ROLLS: [GA.SCORE, GA.HOLD, GA.RESTART], GS.GAME_OVER: [GA.RESTART] }
def __init__(self, ai_settings: Settings, stats: GameStats, **kwargs: game_items_types): """Initialize with default items unless specified in kwargs.""" # Default initializations for game items. # Initialize screen. flags = pygame.HWSURFACE | pygame.DOUBLEBUF # | pygame.FULLSCREEN self.screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height), flags) pygame.display.set_caption("Alien Invasion Game") # Initialize ship. self.ship = Ship(ai_settings, self.screen) # Initialize aliens group. self.aliens = Group() # Initialize bullets group. self.bullets = Group() # Initialize buttons. self.play_button = Button(self.screen, "Play!") # TODO implement Restart and Cancel buttons. # self.restart_button = Button(self.screen, "Restart") # self.cancel_button = Button(self.screen, "Cancel", (255, 0, 0, 80)) # self.set_button_pos() # Initialize scorecard. self.sb = Scorecard(ai_settings, stats, self.screen) # Set the game items for those default values are given. for game_item in kwargs: if game_item in self.acceptable_game_items: self.__setattr__(game_item, kwargs[game_item])
def __init__(self, name): """Take the player's name and create their scorecard. Parameters: name (str) = the player's name """ self._name = name self._scorecard = Scorecard()
def get_scorecard(self, request): """Returns the scorecard for a game.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') scorecard = Scorecard.query(Scorecard.game == game.key).get() if not scorecard: raise endpoints.NotFoundException('Scorecard not found!') return scorecard.to_form()
def __init__(self): self.scores = Scorecard() self.dice = Dice() self.is_done = False #there are 252 possible combinations of dice #there are three roll stats: one roll, two roll, and three roll #there are also a number 524,288 board states #there are 32 ways to roll dice including not rolling #there are 13 scoring actions #need to represent states by which scores are filled and what the total in the top section is #total states are #252*3*524,288 = 396,361,728 #total actions are #32+13 = 45 self.num_states = 396361728 self.num_actions = 45 #actions are broken down as follows #0-31 are rolling actions self.roll_actions = np.zeros((32, 5), dtype=int) dice_indices = [0, 1, 2, 3, 4] count = 0 for i in range(6): for j in itertools.combinations(dice_indices, i): self.roll_actions[count, j] = 1 count += 1 dice_nums = [1, 2, 3, 4, 5, 6] dice_combs = itertools.combinations_with_replacement(dice_nums, 5) self.dice_state_lookup = {} count = 0 for index, c in enumerate(dice_combs): key = ''.join([str(i) for i in c]) self.dice_state_lookup[key] = count count += 1
def blob_task(self): obj = ChainMeasurements( self.symbol, input=self.input, interval=self.kwargs.get('interval'), dummy=self.kwargs.get('dummy')) if self.task == 'options' else ( Historicals(self.symbol, **{ **self.kwargs, **{ 'input': self.input } }) if self.task == 'historicals' else (TimeSeriesArchive(self.symbol, self.input) if self.task == 'archive_timeseries' else (Scorecard(self.input, self.kwargs.get('interval'), **self. kwargs) if self.task == 'scorecard' else Artifacts( self.symbol, self.task, input=self.input)))) return obj.data
def __init__(self, course, players=[], *args, **kwargs): super(Round, self).__init__(*args, **kwargs) self._course = course self._players = players self._scorecard = Scorecard() self._current_hole = None
def reset(self): self.scores = Scorecard() self.dice.reset() self.is_done = False
RIGHT_LIMIT = 485 if __name__ == "__main__": screen = Screen() screen.title("PONG") screen.listen() game_on = True screen.setup(height=HEIGHT, width=WIDTH) screen.bgcolor("black") screen.tracer(0) left_paddle_obj = Paddle(LEFT_PADDLE_POS) right_paddle_obj = Paddle(RIGHT_PADDLE_POS) left_paddle = left_paddle_obj.paddle right_paddle = right_paddle_obj.paddle ball = Ball() score = Scorecard() screen.onkeypress(key="Up", fun=right_paddle_obj.move_up) screen.onkeypress(key="Down", fun=right_paddle_obj.move_down) screen.onkeypress(key="w", fun=left_paddle_obj.move_up) screen.onkeypress(key="s", fun=left_paddle_obj.move_down) screen.onkeypress(key="space", fun=screen.bye) while game_on: screen.update() time.sleep(0.005) ball.move_ball() if ball.pong_ball.ycor() >= UPPER_LIMIT or ball.pong_ball.ycor( ) <= BOTTOM_LIMIT: ball.change_direction_up_dn_collision()
def game(): scorecard = Scorecard() while "empty" in scorecard.values.values(): turn = Turn() turn.take_turn() scorecard.show_scorecard() while True: choice = raw_input("What would you like to take?") if choice == "quit": return if choice == "1s" and scorecard.values["1's"] != 'empty': print "You have already taken 1's" continue if choice == "1s": scorecard.take_1s(turn.dice_values) break if choice == "2s" and scorecard.values["2's"] != 'empty': print "You have already taken 2's" continue elif choice == "2s": scorecard.take_2s(turn.dice_values) break if choice == "3s" and scorecard.values["3's"] != 'empty': print "You have already taken 3's" continue elif choice == "3s": scorecard.take_3s(turn.dice_values) break if choice == "4s" and scorecard.values["4's"] != 'empty': print "You have already taken 4's" continue elif choice == "4s": scorecard.take_4s(turn.dice_values) break if choice == "5s" and scorecard.values["5's"] != 'empty': print "You have already taken 5's" continue elif choice == "5s": scorecard.take_5s(turn.dice_values) break if choice == "6s" and scorecard.values["6's"] != 'empty': print "You have already taken 6's" continue elif choice == "6s": scorecard.take_6s(turn.dice_values) break if choice == "3 of a kind" and scorecard.values[ "3 of a kind"] != 'empty': print "You have already taken 3 of a kind" continue elif choice == "3 of a kind": number = raw_input("Which number?") number = int(number) if turn.dice_values.count(number) < 3: print "You don't have 3 of that number" decision = raw_input( "Do you still want to take 3 of a kind, [y/n]?") if decision == "n": continue else: scorecard.no_three_of_a_kind() break else: scorecard.three_of_kind(turn.dice_values, number) break if choice == "4 of a kind" and scorecard.values[ "4 of a kind"] != 'empty': print "You have already taken 4 of a kind" continue elif choice == "4 of a kind": number = raw_input("Which number?") number = int(number) if turn.dice_values.count(number) < 4: print "You don't have 4 of that number" decision = raw_input( "Do you still want to take 4 of a kind, [y/n]?") if decision == "n": continue else: scorecard.no_four_of_a_kind() break else: scorecard.four_of_kind(turn.dice_values, number) break if choice == "low run" and scorecard.values["low run"] != 'empty': print "You have already taken low run" continue elif choice == "low run": scorecard.low_run(turn.dice_values) break if choice == "low run" and collections.Counter( turn.dice_values) == collections.Counter([1, 2, 4, 5, 3]): scorecard.low_run(turn.dice_values) break elif choice == "low run" and collections.Counter( turn.dice_values) != collections.Counter([2, 3, 4, 5, 1]): scorecard.no_low_run(turn.dice_values) break if choice == "high run" and scorecard.values["high run"] != 'empty': print "You have already taken high run" continue if choice == "high run" and collections.Counter( turn.dice_values) == collections.Counter([2, 3, 4, 5, 6]): scorecard.high_run(turn.dice_values) break elif choice == "high run" and collections.Counter( turn.dice_values) != collections.Counter([2, 3, 4, 5, 6]): scorecard.no_high_run(turn.dice_values) break if choice == "full house" and scorecard.values[ "full house"] != 'empty': print "You have already taken full house" continue if choice == "full house": countvalues = collections.Counter(turn.dice_values) if countvalues.values() == [2, 3] or countvalues.values() == [ 3, 2 ] or countvalues.values() == [5]: scorecard.full_house(turn.dice_values) break else: scorecard.no_full_house() break if choice == "sum" and scorecard.values["sum"] != 'empty': print "You have already taken sum" continue elif choice == "sum": scorecard.sum_of(turn.dice_values) break if choice == "yahtzee" and scorecard.values["yahtzee"] != 'empty': print "You have already taken yahtzee" continue elif choice == "yahtzee" and collections.Counter( turn.dice_values) == collections.Counter([6, 6, 6, 6, 6]): scorecard.yahtzee(turn.dice_values) break elif choice == "yahtzee" and collections.Counter( turn.dice_values) != collections.Counter([6, 6, 6, 6, 6]): scorecard.noyahtzee(turn.dice_values) break scorecard.show_scorecard() print "End of Game. Your final score is %s" % scorecard.total_score()
from turtle import Screen import time from snake import Snake from food import Food from scorecard import Scorecard screen = Screen() screen.bgcolor("Black") screen.title("Snake Game") screen.setup(width=600, height=600) screen.tracer(False, 1000) is_game_on = True food = Food() scorecard = Scorecard() snake = Snake() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.right, "Right") screen.onkey(snake.left, "Left") while is_game_on: screen.update() time.sleep(0.1) snake.move() if food.distance(snake.head) < 15: food.generate_food() snake.add_segment() scorecard.value += 1 scorecard.update() if snake.head.xcor() < -290 or snake.head.xcor() > 290 or snake.head.ycor() < -290 or snake.head.ycor() > 290:
def score_turn(self, request): """ Calculates the score for the Turn. Required Params: url safe key for the Turn and the scoring category. """ # Get the turn turn = get_by_urlsafe(request.urlsafe_turn_key, Turn) if not turn: raise endpoints.NotFoundException('Turn not found!') if turn.is_complete: message = ('Turn {} is already scored!').format( request.urlsafe_turn_key) raise endpoints.ConflictException(message) # Get the game game = turn.game.get() # Get the score card for this game. scorecard = Scorecard.query(Scorecard.game == game.key).get() # Check that the category_type is one of the expected types. category_type = request.category_type print 'category_type:', category_type print scorecard.category_scores.keys() if str(category_type) not in scorecard.category_scores.keys(): message = ('Category {} not found!').format(category_type) raise endpoints.ConflictException(message) # Check if there is already a score entered for the selected category. current_score = scorecard.category_scores[str(category_type)] """The YAHTZEE category is the only category which can be scored more than once. So check the category type and whether or not the category had already been scored. """ if category_type is not 'YAHZTEE' and current_score > -1: message = ('{} category already contains a score. Please select a different score category.').format( str(category_type)) raise endpoints.ConflictException(message) # Calculate the score for this turn based on the category selected. score = scorecard.calculate_score_for_category( turn.dice, category_type) # Update the game history. entry = (str(category_type), score) # Add the entry to the game history. game.history[turn.number].append(entry) # Update the scorecard with the calculated score. scorecard.category_scores[str(category_type)] = score # Turn is now complete game.has_incomplete_turn = False turn.is_complete = True turn.put() # Save the updated scorecard values. scorecard.put() # Check to see if the game is over. game_over = scorecard.check_full() print 'game_over = ', game_over # If the game is now over, calculate the final score. if game_over: final_score = scorecard.calculate_final_score() print 'final score:', final_score # End the game game.game_over(final_score) # Save the changes made to game game.put() return scorecard.to_form()
class Yahtzee(object): def __init__(self): self._dice = Dice(5, 6) self._scorecard = Scorecard() self._cur_rolls = 0 self._game_state = GS.NEED_ROLL self._state_action_map = { GS.NEED_ROLL: [GA.ROLL, GA.RESTART], GS.ROLLING: [GA.ROLL, GA.HOLD, GA.SCORE, GA.RESTART], GS.NO_MORE_ROLLS: [GA.SCORE, GA.HOLD, GA.RESTART], GS.GAME_OVER: [GA.RESTART] } ## Properties @property def dice(self): return self._dice @property def score(self): return self._scorecard.score @property def scorecard(self): return self._scorecard @property def cur_rolls(self): return self._cur_rolls @property def open_categories(self): return self._scorecard.get_open_categories() @property def available_actions(self): return self._state_action_map[self._game_state] ## Game actions @StateBoundAction(GA.RESTART) def restart(self): self._scorecard.reset() self._dice.release_all() self._cur_rolls = 0 self._game_state = GS.NEED_ROLL @StateBoundAction(GA.ROLL) def roll(self): self._dice.roll() self._cur_rolls += 1 if self._cur_rolls >= 3: self._game_state = GS.NO_MORE_ROLLS else: self._game_state = GS.ROLLING return self._dice @StateBoundAction(GA.HOLD) def toggle_hold(self, *idxs): for idx in idxs: self._dice.toggle_hold(idx) @StateBoundAction(GA.HOLD) def hold(self, *idxs): for idx in idxs: self._dice.hold(idx) @StateBoundAction(GA.HOLD) def release(self, *idxs): for idx in idxs: self._dice.release(idx) @StateBoundAction(GA.SCORE) def score_dice_as(self, category): if self._scorecard.is_category_open(category): score = self._scorecard.score_as(self._dice, category) o = self._scorecard.get_num_open_categories() if o == 0: self._game_state = GS.GAME_OVER else: self._cur_rolls = 0 self._dice.release_all() self._game_state = GS.NEED_ROLL return score else: raise IllegalAction('The "%s" category is already filled' % category) def get_potential_score_for(self, category): return self._scorecard.score_as(self._dice, category, False) ## public def is_game_over(self): return self._game_state == GS.GAME_OVER
def main(): golfers = create_golfers() course = generate_course() scorecard = Scorecard() scorecard = play_round(golfers, scorecard, course) tally_score(scorecard)
class Yahtzee_Game: def __init__(self): self.scores = Scorecard() self.dice = Dice() self.is_done = False #there are 252 possible combinations of dice #there are three roll stats: one roll, two roll, and three roll #there are also a number 524,288 board states #there are 32 ways to roll dice including not rolling #there are 13 scoring actions #need to represent states by which scores are filled and what the total in the top section is #total states are #252*3*524,288 = 396,361,728 #total actions are #32+13 = 45 self.num_states = 396361728 self.num_actions = 45 #actions are broken down as follows #0-31 are rolling actions self.roll_actions = np.zeros((32, 5), dtype=int) dice_indices = [0, 1, 2, 3, 4] count = 0 for i in range(6): for j in itertools.combinations(dice_indices, i): self.roll_actions[count, j] = 1 count += 1 dice_nums = [1, 2, 3, 4, 5, 6] dice_combs = itertools.combinations_with_replacement(dice_nums, 5) self.dice_state_lookup = {} count = 0 for index, c in enumerate(dice_combs): key = ''.join([str(i) for i in c]) self.dice_state_lookup[key] = count count += 1 #32-44 are scoring actions (starting with ones and going down to chance) def create_state_map(self): "this won't work because there are too many values to keep in memory" state_dict = {} roll_nums = [1, 2, 3] ones = [-1, 0] twos = [-1, 0] threes = [-1, 0] fours = [-1, 0] fives = [-1, 0] sixs = [-1] + [i for i in range(1, 64)] three_kind = [-1, 0] four_kind = [-1, 0] sm_straight = [-1, 0] lg_straight = [-1, 0] yahtzee = [-1, 0] chance = [-1, 0] dice_nums = [1, 2, 3, 4, 5, 6] count = 0 # make a big loop and set appropriate values in class to calculate state number # TODO find a better way to iterate over lists of varying lengths for roll_num in roll_nums: for one_val in ones: for two_val in twos: for three_val in threes: for four_val in fours: for five_val in fives: for six_val in sixs: for three_kind_val in three_kind: for four_kind_val in four_kind: for sm_straight_val in sm_straight: for lg_straight_val in lg_straight: for yahtzee_val in yahtzee: for chance_val in chance: for dice_comb in itertools.combinations_with_replacement( dice_nums, 5): key = ( roll_num, one_val, two_val, three_val, four_val, five_val, six_val, three_kind_val, four_kind_val, sm_straight_val, lg_straight_val, yahtzee_val, chance_val, dice_comb) state_dict[ key] = count count += 1 if count % 1000000 == 0: print( count) output = open('states.pkl', 'wb') pickle.dump(state_dict, output) output.close() def compute_state_number(self): roll_number = self.dice.roll_num dice_state = sorted(self.dice.dice_state) state_num = 0 division_level = self.num_states state_num += division_level / 3 * (roll_number - 1) division_level /= 3 top_state = 0 for entry in self.scores.scores.loc[0, 'ones':'sixs']: if entry > 0: top_state += entry if top_state > 63: top_state = 63 state_num += division_level / 64 * top_state division_level /= 64 ones = 0 if self.scores.scores.loc[0, 'ones'] == -1 else 1 state_num += division_level / 2 * ones division_level /= 2 twos = 0 if self.scores.scores.loc[0, 'twos'] == -1 else 1 state_num += division_level / 2 * twos division_level /= 2 threes = 0 if self.scores.scores.loc[0, 'threes'] == -1 else 1 state_num += division_level / 2 * threes division_level /= 2 fours = 0 if self.scores.scores.loc[0, 'fours'] == -1 else 1 state_num += division_level / 2 * fours division_level /= 2 fives = 0 if self.scores.scores.loc[0, 'fives'] == -1 else 1 state_num += division_level / 2 * fives division_level /= 2 sixs = 0 if self.scores.scores.loc[0, 'sixs'] == -1 else 1 state_num += division_level / 2 * sixs division_level /= 2 three_kind_state = 0 if self.scores.scores.loc[ 0, 'three_of_kind'] == -1 else 1 state_num += division_level / 2 * three_kind_state division_level /= 2 four_kind_state = 0 if self.scores.scores.loc[ 0, 'four_of_kind'] == -1 else 1 state_num += division_level / 2 * four_kind_state division_level /= 2 sm_straight = 0 if self.scores.scores.loc[ 0, 'small_straight'] == -1 else 1 state_num += division_level / 2 * sm_straight division_level /= 2 lg_straight = 0 if self.scores.scores.loc[ 0, 'large_straight'] == -1 else 1 state_num += division_level / 2 * lg_straight division_level /= 2 full_house = 0 if self.scores.scores.loc[0, 'full_house'] == -1 else 1 state_num += division_level / 2 * full_house division_level /= 2 yahtzee = 0 if self.scores.scores.loc[0, 'yahtzee'] == -1 else 1 state_num += division_level / 2 * yahtzee division_level /= 2 chance_state = 0 if self.scores.scores.loc[0, 'chance'] == -1 else 1 state_num += division_level / 2 * chance_state division_level /= 2 #handled all score states and roll number states #now need to handle dice states state_num += self.dice_state_lookup[''.join( [str(i) for i in dice_state])] return int(state_num) def roll(self, dice_to_roll): self.dice.roll(dice_to_roll) return self.dice.dice_state def get_possible_actions(self): #need to return valid action numbers as a list valid_actions = [] if self.dice.roll_num < 3: valid_actions += [i for i in range(32)] #now need to check which columns have been filled open_spots = self.scores.get_open_categories() + 32 valid_actions += list(open_spots) return valid_actions def get_valid_score(self, entry_num): #TODO figure out how to directly call appropriate logic without 12 if statements (list of funtions or something) counts = Counter(self.dice.dice_state) entry_num -= 32 assert (self.scores.scores_new[entry_num] == -1) if entry_num == 0: #ones category return counts[1] elif entry_num == 1: #twos category return counts[2] * 2 elif entry_num == 2: #threes category return counts[3] * 3 elif entry_num == 3: #fours category return counts[4] * 4 elif entry_num == 4: #fives category return counts[5] * 5 elif entry_num == 5: #sixs category return counts[6] * 6 elif entry_num == 6: #three of a kind if max(counts.values()) >= 3: return sum(self.dice.dice_state) else: return 0 elif entry_num == 7: #four of a kind if max(counts.values()) >= 4: return sum(self.dice.dice_state) else: return 0 elif entry_num == 8: #full house if max(counts.values()) == 3 and min(counts.values()) == 2: #default value for full house (25) return 25 else: return 0 elif entry_num == 9 or entry_num == 10: #small/large straight self.dice.dice_state.sort() lis_max = 0 cur_lis = 1 for index in range(1, 5): if self.dice.dice_state[index] == self.dice.dice_state[index - 1] + 1: cur_lis += 1 if cur_lis > lis_max: lis_max = cur_lis elif self.dice.dice_state[index] == self.dice.dice_state[index - 1]: continue else: cur_lis = 1 if entry_num == 9 and lis_max >= 4: return 30 else: return 0 if entry_num == 10 and lis_max >= 5: return 40 else: return 0 elif entry_num == 11: #yahtzee if max(counts.values() ) == 5 and self.dice.dice_state != [0, 0, 0, 0, 0]: return 50 else: return 0 elif entry_num == 12: return sum(self.dice.dice_state) def score(self, action): score = self.get_valid_score(action) self.scores.update_scorecard(action - 32, score) def take_action(self, action_number): if action_number < 32: self.dice.roll(self.roll_actions[action_number]) def step(self, action): # the action is either to enter a score in a column or roll a subset of dice # the actions is specified as an integer from 0-45 with 0-31 being rolling actions and # 32 - 45 being scoring actions #need to return new state and the reward achieved as well as allowed next actions #state is defined by the dice state and the roll number if action >= 32: #scoring action self.score(action) self.dice.reset() else: self.dice.roll(self.roll_actions[action]) #check if all scores are filled to see if the game is done if self.scores.is_full(): reward = self.scores.calculate_score() self.is_done = True else: reward = 0 new_state = self.compute_state_number() return new_state, reward def reset(self): self.scores = Scorecard() self.dice.reset() self.is_done = False
border.hideturtle() border.color("White") border.penup() border.goto(0, 300) border.setheading(270) screen.tracer(False) while border.ycor() != -300: border.pendown() border.fd(10) border.penup() border.fd(10) rpaddle = Paddle((475, 0)) lpaddle = Paddle((-480, 0)) ball = Ball() rscore = Scorecard((20, 330)) lscore = Scorecard((-20, 330)) screen.listen() screen.onkey(rpaddle.userup, "Up") screen.onkey(rpaddle.userdown, "Down") screen.onkey(lpaddle.userup, "w") screen.onkey(lpaddle.userdown, "s") game_on = True while game_on: screen.update() time.sleep(0.1) ball.hideturtle() if ball.ycor() > 340 or ball.ycor() < -340: ball.setheading(-ball.heading())
SCREEN_WIDTH = 600.0 SLEEP_TIME = 0.1 GAME_OVER_BOUNDARY_LIMIT = 285 if __name__ == "__main__": # Creating Screen Object and setting its properties screen = Screen() screen.listen() screen.bgcolor("black") screen.title("SNAKE GAME") screen.setup(height=SCREEN_HEIGHT, width=SCREEN_WIDTH) screen.tracer(0) # Creating objects of the involved classes snake_game = Snake() food = Food() scorecard = Scorecard() # Listening for direction changes screen.onkeypress(snake_game.up, key='Up') screen.onkeypress(snake_game.right, key='Right') screen.onkeypress(snake_game.down, key='Down') screen.onkeypress(snake_game.left, key='Left') # Game logic game_on = True while game_on: screen.update() time.sleep(SLEEP_TIME) snake_game.move() if snake_game.head.distance(food) < 15: food.position_food() scorecard.update_score()