def goResult(self, rps): self.game = Game() self.balance.deductPrice() if self.game.determineWinOrLose(rps) == "win": self.resultWindow.setPlaceholderText("win") self.balance.winPrice() elif self.game.determineWinOrLose(rps) == "lose": self.resultWindow.setPlaceholderText("lose") self.balance.losePrice() elif self.game.determineWinOrLose(rps) == "draw": self.resultWindow.setPlaceholderText("draw") self.balance.drawPrice() self.balanceWindow.setPlaceholderText( str(self.balance.currentBalance())) # 현재 금액 띄우기 if self.balance.currentBalance() >= 1000: self.checkResultButton.setEnabled(True) self.rockButton.setEnabled(False) self.paperButton.setEnabled(False) self.scissorsButton.setEnabled(False) elif self.balance.currentBalance() <= 0: self.checkResultButton.setEnabled(True) self.rockButton.setEnabled(False) self.paperButton.setEnabled(False) self.scissorsButton.setEnabled(False)
def start_game(self, event): if self.player1name.get() == "Already Chosen!" or self.player2name.get() == "Already Chosen!": return self.game = Game(self.player1, self.player2) for i, space in enumerate(self.game.board): self.game.board[i] = [0, 0, 0, 0, 0, 0, 0] self.update() self.enable()
def play_finding_multiple(): # TODO: make this pass # input("Starting: play_finding_multiple") S.reset() S.set_rack("ERDE") play_erde = D.Play("ERDE", "G8", "X") L.execute_play(play_erde) S.increase_turn() S.set_rack("DEN") area_den = D.Area("K6", "K8") subturn_den = Game.SubTurn(area_den) # highest scoring play should be DEN, K6, Y with ERDEN as bonus. print("highest scoring play for Area of K6 to K8:") print(subturn_den.highest_scoring_play) # play_den = D.Play("DEN", "K6", "Y") L.execute_play(subturn_den.highest_scoring_play) # L.execute_play(play_den) S.increase_turn() S.set_rack("URNE") Display.print_board() parallel_area = D.Area("I9", "L9") affected_parallel_plays = parallel_area.contested_plays print("affected_parallel plays:") pprint.pprint(affected_parallel_plays) parallel_subturn = Game.SubTurn(parallel_area) print("highest scoring play:") # expected: Still URNE on I9, X # bonus, DU, ER, DENN pprint.pprint(parallel_subturn.highest_scoring_play) print("Plays possible on I9 to L9:") pprint.pprint(parallel_subturn.possible_plays)
def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.snake = Player(3) self.apple = Apple(5, 5)
def test_put_point(self): game = Game(3, 3) game.field[1][2] = Cell.RED for i in range(game.width): for j in range(game.height): if i == 1 and j == 2: self.assertEqual(game.field[i][j], Cell.RED) else: self.assertEqual(game.field[i][j], Cell.EMPTY)
def __init__(self): super().__init__() self.game = Game() self.painter = QPainter() self.move_timer = QTimer() self.item_size = QSize(50, 50) self.width = self.game.board_size * 50 self.height = self.width + 60 self.state_panel = StatePanel(self, self.game, self.width) self.init_ui()
def test_check_intersection_lines(self): game = Game(4, 4) list_points = [(0, 0), (1, 0), (2, 1), (1, 1), (2, 0), (3, 0)] change = game.check_intersection_lines(list_points) self.assertListEqual(change, [(0, 0), (1, 0), (1, 1), (2, 1), (2, 0), (3, 0)]) list_points = [(0, 0), (1, 0), (2, 1), (2, 0), (1, 1), (0, 1)] change = game.check_intersection_lines(list_points) self.assertListEqual(change, [(0, 0), (1, 0), (2, 0), (2, 1), (1, 1), (0, 1)])
def test_empty_cell(self): game = Game(2, 2) self.assertTrue(game.is_empty_cell_on_field()) game.field[0][0] = Cell.RED game.field[1][0] = Cell.RED self.assertTrue(game.is_empty_cell_on_field()) game.field[0][1] = Cell.RED game.field[1][1] = Cell.RED self.assertFalse(game.is_empty_cell_on_field())
def run(): print_commands() replay = True while replay: game = Game() while not game.has_finished(): print_game(game) try: game.move(take_input()) except Exception as e: print("Error:", e) print_game(game) replay = print_win_and_get_replay(game.moves)
def main(): # initialize the pygame module pygame.init() # load and set the logo logo = pygame.image.load("assets/snek.png") pygame.display.set_icon(logo) pygame.display.set_caption("snake") # load images for later head_image = pygame.image.load("assets/head.png") body_image = pygame.image.load("assets/body.png") apple_image = pygame.image.load("assets/apple.png") assets = (apple_image, head_image, body_image) # create a surface on screen that has the size of 240 x 180 screen = pygame.display.set_mode((width * 100, height * 100)) num_episodes = 300 for i_episode in range(num_episodes): game = Game(width, height) last_screen = get_screen(game) current_screen = get_screen(game) for t in count(): render_board(game.getBoard(), screen, assets) pygame.display.flip() # Select and perform an action action = select_action(current_screen) reward = game.getScore() done = game.getState != 0 reward = torch.tensor([reward], device=device) # Observe new state last_screen = current_screen current_screen = get_screen(game) # Store the transition in memory memory.push(last_screen, action, current_screen, reward) # Perform one step of the optimization (on the target network) optimize_model() if done: print(f"score: {game.getScore()}") break # Update the target network, copying all weights and biases in DQN if i_episode % TARGET_UPDATE == 0: target_net.load_state_dict(policy_net.state_dict()) print('Complete')
def __init__(self): super().__init__() self.game = Game() arg_parsing(self.game) self.game_field = GameField(self, self.game) self.statistics_panel = StatisticsPanel(self, self.game) self.init_ui()
def __init__(self, game: Game) -> None: self.selection = '' self.game = game self.options = game.options self.previous_round = game.start_round() self.player_images = {game.cpu: art.ROBOT, game.player: art.PLAYER} self.last_action_time = .0
def change_rival_field_game(game, field): size = tuple(map(int, field.name_win['size'].split('x'))) game = Game(size[0], size[1]) rival = (field.name_win.get('first', None), field.name_win.get('second', None)) if rival == (None, None): color = field.saving_for_online["color"] ip = field.saving_for_online["ip"] size = field.saving_for_online["size"] rival = (Rival.ONLINE, Rival.ONLINE) high_scores = Start.get_high_scores(game) field = Field(game, high_scores, rival) if rival == (Rival.ONLINE, Rival.ONLINE): field.saving_for_online = {"color": color, "ip": ip, "size": size} game.possible_steps = game.get_possible_step() return game, field, rival
def test_neighboring_points_simple(self): game = Game(6, 6) game.field[3][2] = Cell.RED best_path_and_squre = game.check_neighboring_points( 3, 2, 3, 2, [((3, 2))], [], 0, time.time()) self.assertEqual(best_path_and_squre, (([], 0))) game.field[3][4] = Cell.RED game.field[2][3] = Cell.RED game.field[3][3] = Cell.BLUE game.field[4][3] = Cell.RED best_path_and_squre = game.check_neighboring_points( 4, 3, 4, 3, [((4, 3))], [], 0, time.time()) self.assertEqual(best_path_and_squre, (([(4, 3), (3, 2), (2, 3), (3, 4)], 2.0)))
def test_can_round(self): game = Game(4, 4) path = [(1, 0), (2, 1), (2, 2), (1, 3), (0, 2), (0, 1)] for e in path: game.field[e[0]][e[1]] = Cell.RED game.field[1][1] = Cell.BLUE self.assertFalse(game.can_round(path)) game.field[1][2] = Cell.BLUE self.assertTrue(game.can_round(path))
def test_in_border(self): game = Game(3, 4) list_points = [(0, 0), (-1, 2), (2, 2), (1, -1), (7, 1), (1, 7)] self.assertTrue(game.in_border(*list_points[0])) self.assertFalse(game.in_border(*list_points[1])) self.assertTrue(game.in_border(*list_points[2])) self.assertFalse(game.in_border(*list_points[3])) self.assertFalse(game.in_border(*list_points[4])) self.assertFalse(game.in_border(*list_points[5]))
def log_searching(): S.reset() # finding the plays. S.set_rack("ERNSTLÜ") play_lustern = D.Play("LÜSTERN", "G8", "X") L.execute_play(play_lustern) S.increase_turn() # Display.print_board() # Set BORSTE S.set_rack("BORTE") play_borste = D.Play("BORSTE", "I5", "Y") L.execute_play(play_borste) S.increase_turn() # Display.print_board() # Set ERBE S.set_rack("ERE") play_erbe = D.Play("ERBE", "G5", "X") L.execute_play(play_erbe) S.increase_turn() # Display.print_board() # found_play = WL.find_active_play_by_position("G8") # print(found_play) # Find BEDARF, # Extends ERBE to DERBE # Extends LÜSTERN to FLÜSTERN # mark both extended-plays as "active" in the WordLog. # mark ERBE and LÜSTERN S.set_rack("BEDARF") test_area_bedarf = D.Area("F3", "F8") bedarf_turn = Game.SubTurn(test_area_bedarf.position_list) L.execute_play(bedarf_turn.highest_scoring_play) S.increase_turn() Display.print_board() print("All Plays:") all_plays = WL.read_log() pprint.pprint(all_plays) print("Length of all plays:", len(all_plays)) print("updating to only active plays") WL.deactivate_extended_plays() print("Only the active plays:") active_plays = WL.get_active_plays() pprint.pprint(active_plays) print("Length of active plays:", len(active_plays)) # test passes if the active plays are: # FLÜSTERN, DERBE, BORSTE and BEDARF print("PASSED.")
async def game_handler(request): if len(request.app["players"]) >= GAME_PLAYERS_COUNT: participating_players = random.sample(request.app["players"], GAME_PLAYERS_COUNT) game = Game(players=participating_players) request.app["games"].append(game) request.app["players"] = list( set(request.app["players"]) - set(participating_players)) for player in participating_players: await player.ws.send_json({ "action": "game_start", "message": "Game started" }) await GameHelper(game).start_game(request.app) for player in game.players: await player.ws.send_json({ "action": "game_result", "message": str(game.get_player_result(player).name), }) request.app["players"].append(player)
def test_possible_step_for_ai(self): game = Game(3, 2) game.possible_steps = game.get_possible_step() self.assertEqual(game.possible_steps, [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]) game.make_step(0, 1) self.assertEqual(game.possible_steps, [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)])
def level_1(): g = Game() g.add_player( Player(position=Vector2(0.2, 0.5), movement=Vector2(0, 0.002 * random()))) g.add_player( Player(position=Vector2(0.8, 0.5), movement=Vector2(0, 0.002 * random()))) return g
def test_count_score_and_black_points(self): game = Game(4, 4) path = [(1, 0), (2, 1), (2, 2), (1, 3), (0, 2), (0, 1)] for e in path: game.field[e[0]][e[1]] = Cell.RED game.field[1][1] = Cell.BLUE game.make_black_some_points(path) for i in range(game.width): for j in range(game.height): if (i, j) in [(1, 1), (1, 2)]: self.assertTrue(game.field[i][j] == Cell.BLACK) else: self.assertTrue(game.field[i][j] == Cell.EMPTY or game.field[i][j] == Cell.RED) game.count_score(path, 4.0) self.assertEqual(game.score_red, 4.0) self.assertEqual(game.score_blue, 0.0)
def area_find_occupied_neighbors(): S.reset() S.set_rack("STRUDELN") first_play = D.Play("STRUDELN", "F8", "x") L.execute_play(first_play) S.increase_turn() S.set_rack("FARBE") second_play = D.Play("FARBEN", "M3", "y") L.execute_play(second_play) S.increase_turn() S.set_rack("BEDARF") Display.print_board() subturn_area = D.Area("L2", "L14") subturn_to_solve = Game.SubTurn(subturn_area) pprint.pprint(subturn_to_solve.possible_plays)
def entire_turn(number_of_turns: int = 5): # TODO: DEBUG A WHOLE LOT # BUG: # considers FARBEN a proper play on M2, y # only FARBE gets planted. # if there's no letter on the rack, it's still trying to find a valid play. # TODO: Add checks to ensure at least one Rack-letter must be used. # BUG: "FABEL" on L4-L8 is considered the best play on Turn 3 in this setup. # The available Area is F8 to F14... # Also doesn't check for bonus-plays # which would need to be: FA, AR, BB, and EE # tested in debugger: # expected # [STRUDELN F8-M8:x score:20(20+0) , # FARBEN M3-M8:y score:24(24+0) , # BEDARF K7-K12:y score:22(22+0) , # RAFFE H12-L12:x score:24(24+0) , # BEDARF I5-N5:x score:22(22+0) ] S.reset() # S.fill_rack() turn_number = S.GAME_SETTINGS['turn'] all_turns = [] while turn_number < number_of_turns: # TODO: finally make Game_settings a proper Object turn_number = S.GAME_SETTINGS['turn'] if C.is_first_turn() is True: S.set_rack("ERNSTLU?") else: S.set_rack("BEDARF") print(f" Turn No.: {turn_number} ".center(80, "-")) Display.print_board() turn = Game.Turn(None, S.get_rack()) all_turns.append(turn) # input("Press Enter to execute the highest scoring play from this turn...") L.execute_play(turn.highest_scoring_play) print(" End of turn. ".center(80, "-")) # S.fill_rack() S.increase_turn() Display.print_board() pprint.pprint(WL.get_active_plays()) print("PASSED.")
def first_turn(): S.reset() S.set_rack("ERNSTLU?") filled_positions = [] usable_positions = WS.find_usable_positions("H8", "x") print("Usable positions:") first_area = D.Area(position_list=usable_positions) starting_positions = WS.find_starting_position("STRUDELN", first_area) print("starting positions for STRUDELN:") print(starting_positions) Display.print_board() print("Subturn in Turn 1:") first_subturn = Game.SubTurn(first_area) highest_play = first_subturn.highest_scoring_play L.execute_play(highest_play) Display.print_board()
class ViewModel: def __init__(self, root): self.game = Game() self.cell_as_text = tkinter.StringVar(root) self.next_cell() def cmd_miss(self): self.game.miss(self.cell) self.next_cell() def cmd_wound(self): self.game.wound(self.cell) self.next_cell() def cmd_died(self): self.game.died(self.cell) self.next_cell() def next_cell(self): self.cell = self.game.choise_shot() x = 'абвгдежзик'[self.cell[0]] y = self.cell[1] + 1 self.cell_as_text.set('%s %s' % (x, y)) def cmd_reset(self): self.game = Game() self.next_cell() def cmd_show(self): stat = self.game.show_field() for y in range(self.game.ys): for x in range(self.game.xs): cell = stat[x, y] if cell['state'] == CellState.miss: ch = '.' elif cell['state'] == CellState.dead: ch = 'X' else: ch = str(cell['count']) print('%3s' % ch, end=' ') print() print()
def area_finding(): S.set_rack("ERNSTL?") test_play_open = D.Play("LÜSTERN", "G8", "X") L.execute_play(test_play_open) S.increase_turn() Display.print_board() # Goal: make this consider FLÜSTERN by Building BEDARF on F3, along Y. S.set_rack("BEDARF") rack = S.get_rack() area_list = Scratch.find_all_areas_per_play(test_play_open, "y", rack) possible_plays = [] for current_area in area_list: neighbors = current_area.get_area_neighbors() sub_turn = Game.SubTurn(current_area.position_list) possible_plays.append(sub_turn.highest_scoring_play) print(possible_plays) print("PASSED.")
def test_intersection(self): game = Game(6, 6) first = [(1, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 3), (3, 2), (3, 1), (2, 1)] second = [(2, 3), (2, 4), (3, 4), (4, 5), (5, 4), (5, 3), (4, 2), (3, 3)] self.assertEqual(Geometry.get_intersection(first, second, second), [(2, 3), (2, 4), (3, 4), (3, 3)]) for e in first: game.field[e[0]][e[1]] = Cell.RED for e in second: game.field[e[0]][e[1]] = Cell.RED game.lines.append((first, Cell.RED)) self.assertEqual(game.count_square_wihtout_intersections(first), 0) self.assertEqual(game.count_square_wihtout_intersections(second), 4.0)
def play_finding_parallel(): input("Starting: play_finding_parallel") S.reset() S.set_rack("ERDE") play_erde = D.Play("ERDE", "G8", "X") L.execute_play(play_erde) S.increase_turn() S.set_rack("URNE") Display.print_board() parallel_area = D.Area("I9", "L9") affected_parallel_plays = parallel_area.contested_plays print("affected_parallel plays:") pprint.pprint(affected_parallel_plays) parallel_subturn = Game.SubTurn(parallel_area) print("highest scoring play:") pprint.pprint(parallel_subturn.highest_scoring_play) print("Plays possible on I9 to L9:") pprint.pprint(parallel_subturn.possible_plays) print("PASSED.")
def test_make_step(self): game = Game(6, 6) game.field[2][2] = Cell.BLUE self.assertEqual(game.field[2][2], Cell.BLUE) game.make_step(3, 2) game.make_step(2, 1) game.make_step(1, 2) game.make_step(2, 3) for i in range(game.width): for j in range(game.height): if (i, j) in [(3, 2), (2, 1), (1, 2), (2, 3)]: self.assertEqual(game.field[i][j], Cell.RED) elif i == 2 and j == 2: self.assertEqual(game.field[i][j], Cell.BLACK) else: self.assertEqual(game.field[i][j], Cell.EMPTY) self.assertTrue(game.score_blue == 0.0) self.assertTrue(game.score_red == 2.0) self.assertListEqual( game.lines, [(([(2, 3), (1, 2), (2, 1), (3, 2), (2, 3)], Cell.RED, [((2, 2), Cell.BLUE)], 2.0))])
def test_normal_game() -> None: game = Game(Round) c = FakeConsoleGame(game) c.flush_output() c.show_stats() assert c.get_output() == 'Round: 1 / 3|Wins: 0|Wins: 0' c.handle_selection(ord('p')) game.play(Selection.PAPER, game.cpu) assert game.player.selection == Selection.PAPER c.flush_output() c.show_hands() assert c.get_output() == "{}|{}".format(art.PAPER, art.PAPER) c.finalize_round() c.start_next_round() c.handle_selection(ord('s')) game.play(Selection.PAPER, game.cpu) c.last_action_time = .0 c.finalize_round() c.flush_output() c.show_stats() assert c.get_output() == 'Round: 2 / 3|Wins: 0|Wins: 1'
def new_game(request): """ Creates a new game with the player or computer first, makes the first move if the computer is first, and redirect to the board page. """ if request.method != 'POST': return HttpResponseRedirect(reverse(index)) f = forms.NewGameForm(request.POST) if not f.is_valid(): return HttpResponse('<h1>Error in form post.</h1> %s'%f) player_first = f.cleaned_data['player_first'] if player_first: game = Game(Board(), Player, Computer) game.player_id = 1 else: game = Game(Board(), Computer, Player) game.set_move() game.player_id = 2 request.session['game'] = game return HttpResponseRedirect(reverse(render_board))