Exemplo n.º 1
0
 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()
Exemplo n.º 2
0
 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()
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
 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)
Exemplo n.º 5
0
 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)])
Exemplo n.º 6
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))
Exemplo n.º 7
0
 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]))
Exemplo n.º 8
0
 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)
Exemplo n.º 9
0
 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())
Exemplo n.º 10
0
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
Exemplo n.º 11
0
 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)])
Exemplo n.º 12
0
 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()
Exemplo n.º 13
0
 def test_process(self):
     game = Game(1, 2)
     self.assertEqual(game.turn, Cell.RED)
     game.process()
     self.assertEqual(game.turn, Cell.BLUE)
     game.make_step(0, 0)
     game.process()
     self.assertEqual(game.turn, Cell.RED)
     game.make_step(0, 1)
     game.process()
     self.assertEqual(game.get_winner(), Cell.EMPTY)
Exemplo n.º 14
0
    def test_different_situation(self):
        game = Game(10, 10)
        self.assertEqual(game.turn, Cell.RED)
        game.make_step(2, 3)
        game.make_step(1, 4)
        game.change_turn_player()
        self.assertEqual(game.turn, Cell.BLUE)
        game.make_step(1, 3)
        game.make_step(2, 2)
        game.change_turn_player()
        self.assertEqual(game.turn, Cell.RED)
        game.make_step(0, 3)
        game.make_step(1, 2)
        self.assertEqual(game.lines,
                         [(([(1, 2), (0, 3), (1, 4), (2, 3),
                             (1, 2)], Cell.RED, [((1, 3), Cell.BLUE)], 2.0))])
        game.make_step(3, 2)
        game.make_step(4, 3)
        game.make_step(2, 1)
        self.assertEqual(game.lines,
                         [(([(1, 2), (0, 3), (1, 4), (2, 3),
                             (1, 2)], Cell.RED, [((1, 3), Cell.BLUE)], 2.0)),
                          (([(2, 1), (1, 2), (2, 3), (3, 2),
                             (2, 1)], Cell.RED, [((2, 2), Cell.BLUE)], 2.0))])

        game.change_turn_player()
        self.assertEqual(game.turn, Cell.BLUE)
        game.make_step(9, 9)
        game.make_step(9, 8)
        game.change_turn_player()
        self.assertEqual(game.turn, Cell.RED)
        game.make_step(8, 9)
        game.make_step(8, 8)
        game.make_step(7, 8)
        game.change_turn_player()
        self.assertEqual(game.turn, Cell.BLUE)
        game.make_step(7, 7)
        game.make_step(8, 7)
        game.make_step(7, 9)
        game.make_step(6, 8)
        game.make_step(8, 0)
        self.assertEqual(game.lines,
                         [(([(1, 2), (0, 3), (1, 4), (2, 3),
                             (1, 2)], Cell.RED, [((1, 3), Cell.BLUE)], 2.0)),
                          (([(2, 1), (1, 2), (2, 3), (3, 2),
                             (2, 1)], Cell.RED, [((2, 2), Cell.BLUE)], 2.0)),
                          (([(8, 0), (7, 9), (6, 8), (7, 7), (8, 7), (9, 8),
                             (9, 9),
                             (8, 0)], Cell.BLUE, [((7, 8), Cell.RED),
                                                  ((8, 8), Cell.RED),
                                                  ((8, 9), Cell.RED)], 5.5))])
        self.assertEqual(game.score_red, 4.0)
        self.assertEqual(game.score_blue, 5.5)
        self.assertEqual(game.get_winner(), Cell.BLUE)
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
 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)))
Exemplo n.º 17
0
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')
Exemplo n.º 18
0
 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)
Exemplo n.º 19
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
Exemplo n.º 20
0
 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)
Exemplo n.º 21
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'
Exemplo n.º 22
0
    def test_neighboring_points_vertical_border(self):
        game = Game(5, 5)
        game.field[0][2] = Cell.BLUE
        game.field[4][2] = Cell.BLUE
        game.field[0][1] = Cell.RED
        game.field[1][2] = Cell.RED
        game.field[3][2] = Cell.RED
        game.field[0][3] = Cell.RED
        game.field[4][3] = Cell.RED
        game.field[4][1] = Cell.RED

        best_path_and_squre = game.check_neighboring_points(
            4, 1, 4, 1, [((4, 1))], [], 0, time.time())
        self.assertEqual(best_path_and_squre,
                         (([(4, 1), (3, 2), (4, 3), (5, 3), (6, 2),
                            (5, 1)], 4.0)))

        best_path_and_squre = game.check_neighboring_points(
            0, 3, 0, 3, [((0, 3))], [], 0, time.time())
        self.assertEqual(best_path_and_squre, (([(0, 3), (-1, 3), (-2, 2),
                                                 (-1, 1), (0, 1),
                                                 (1, 2)], 4.0)))
Exemplo n.º 23
0
    def test_neighboring_points_horiz_border(self):
        game = Game(5, 5)
        game.field[1][0] = Cell.BLUE
        game.field[1][4] = Cell.BLUE
        game.field[1][1] = Cell.RED
        game.field[0][4] = Cell.RED
        game.field[1][3] = Cell.RED
        game.field[0][0] = Cell.RED
        game.field[2][0] = Cell.RED
        game.field[2][4] = Cell.RED

        best_path_and_squre = game.check_neighboring_points(
            2, 4, 2, 4, [((2, 4))], [], 0, time.time())
        self.assertEqual(best_path_and_squre,
                         (([(2, 4), (1, 3), (0, 4), (0, 5), (1, 6),
                            (2, 5)], 4.0)))

        best_path_and_squre = game.check_neighboring_points(
            0, 0, 0, 0, [((0, 0))], [], 0, time.time())
        self.assertEqual(best_path_and_squre, (([(0, 0), (1, 1),
                                                 (2, 0), (2, -1), (1, -2),
                                                 (0, -1)], 4.0)))
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
def test_normal_game_play() -> None:
    game = Game(Round)
    game.start_round()
    game.play(Selection.PAPER)
    game.play(Selection.PAPER, game.cpu)
    finished_round = game.finish_round()
    assert finished_round.winner is None
    assert finished_round.draw is True
    game.start_round()
    game.play(Selection.PAPER)
    game.play(Selection.ROCK, game.cpu)
    finished_round = game.finish_round()
    assert finished_round.winner == game.player
    game.start_round()
    with pytest.raises(PlayerError):
        game.finish_round()
    game.play(Selection.SCISSORS)
    game.play(Selection.ROCK, game.cpu)
    finished_round = game.finish_round()
    assert finished_round.winner == game.cpu
    assert game.get_player_result() == Result.DRAW
    with pytest.raises(GameError):
        game.start_round()
Exemplo n.º 26
0
    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))])
Exemplo n.º 27
0
 def test_undo_redo(self):
     game = Game(2, 3)
     game.make_step(0, 0)
     game.change_turn_player()
     game.make_step(1, 1)
     game.change_turn_player()
     game.make_step(0, 1)
     game.change_turn_player()
     game.make_step(1, 0)
     game.change_turn_player()
     game.make_step(0, 2)
     game.change_turn_player()
     game.make_step(1, 2)
     enemy = Rival.AInormal
     for _i in range(4):
         with contextlib.suppress(IndexError):
             game.undo(enemy)
             try:
                 game.undo(enemy)
             except IndexError:
                 game.redo(enemy)
     for i in range(game.width):
         for j in range(game.height):
             if i != 0 or j != 0:
                 self.assertEqual(game.field[i][j], Cell.EMPTY)
     for _i in range(4):
         with contextlib.suppress(IndexError):
             game.redo(enemy)
             game.redo(enemy)
     for i in range(game.width):
         for j in range(game.height):
             if (i, j) in [(0, 0), (0, 1), (0, 2)]:
                 self.assertEqual(game.field[i][j], Cell.RED)
             elif (i, j) in [(1, 1), (1, 0), (1, 2)]:
                 self.assertEqual(game.field[i][j], Cell.BLUE)
             else:
                 self.assertEqual(game.field[i][j], Cell.EMPTY)
Exemplo n.º 28
0
def test_timer_game_play() -> None:
    game = Game(TimerRound)
    game.set_options(rounds=4)
    game.start_round()
    game.play(Selection.PAPER)
    game.play(Selection.ROCK, game.cpu)
    finished_round = game.finish_round()
    assert finished_round.winner is game.player
    game.start_round()
    game.play(Selection.PAPER)
    # to satisfy mypy
    assert isinstance(game.current_round, TimerRound)
    game.current_round.timings[game.player] = time() + 999999
    game.play(Selection.ROCK, game.cpu)
    finished_round = game.finish_round()
    assert finished_round.winner is game.cpu
    assert game.is_running()
    game.start_round()
    game.current_round.timings[game.player] = time() + 999999
    game.current_round.timings[
        game.cpu] = time() + 999999  # normally impossible
    finished_round = game.finish_round()
    assert finished_round.winner is game.cpu
    assert finished_round.draw is False
Exemplo n.º 29
0
def createGame(players):
    global game

    game = Game.Game(players)
Exemplo n.º 30
0
import pygame, sys
import numpy as np
from logic import Game, GameOverError

pygame.init()

size = (5, 5)

game = Game(size=size,
            difficulty=1,
            seed=0,
            fixed_goal=True,
            visualize=True,
            max_screen_size=500,
            turn_penalty=0)

move_dict = {
    pygame.K_LEFT: "left",
    pygame.K_RIGHT: "right",
    pygame.K_UP: "up",
    pygame.K_DOWN: "down",
}

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                sys.exit()