Exemplo n.º 1
0
class Game:
    def __init__(self):
        self.board = Board()
        self.totems = [Totem("{0:04b}".format(i)) for i in range(16)]

    def put_totem(self, totem: Totem, i: int, j: int):
        assert i in range(4), "i out of range"
        assert j in range(4), "j out of range"
        try:
            if self.board.is_empty(i, j):
                self.board.grid[i][j] = totem
                self.totems.remove(totem)
                return self
        except Exception as e:
            print(e)

    def status(self):
        for i in range(4):
            if are_similar(self.board.get_row(i)):
                return 'match in row %d' % i
            if are_similar(self.board.get_col(i)):
                return 'match in column %d' % i
        if are_similar(self.board.get_diag()):
            return 'match in main diagonal'
        if are_similar(self.board.get_adiag()):
            return 'match in anti diagonal'

        if not self.totems:
            return 'tie'

        return 'N/A'

    def __repr__(self):
        return str(self.board.grid)
Exemplo n.º 2
0
    def __init__(self, configuration_of_ships):
        self.__num_of_shoots = 0
        self.__board = Board()
        self.__generator_of_ship = GeneratorOfShip(self.__board)

        self.__ships = list()
        for num_of_decks in configuration_of_ships:
            self.__ships.append(
                self.__generator_of_ship.create_ship(num_of_decks))
        db.creat_shema()
Exemplo n.º 3
0
    def __init__(self, screen):
        """
        Set up the game.
        Params: screen, root pygame surface.
        """
        # Create the main screen surface.
        self.__screen = screen
        self.__screen.fill((0, 0, 85))  # Fill the background with colour.

        # Initialize Board
        self.__board_surface = pygame.Surface(BOARD_SIZE)
        self.__board_rect = self.__board_surface.get_rect()
        self.__board_rect.x, self.__board_rect.y = BOARD_POS

        # Font filepath.
        topaz_filepath = pygame.font.match_font(FONTFAMILY)

        # Create the font for the title.
        self.__title_font = pygame.font.Font(topaz_filepath, 30)

        # Create the title and center it so that it displays above the board.
        self.__title = Title(self.__screen, self.__title_font, "", 300, 50,
                             True, True, red)

        # Creating the Buttons
        offset = 150
        x = SCREEN_W // 2
        y = SCREEN_H - 50

        # Font for the buttons.
        self.__button_font = pygame.font.Font(topaz_filepath, 15)

        # Restart button for restarting the game, but keeping the same gamemode.
        self.__restart_button = Button(self.__screen, self.__button_font,
                                       100, 30, x - offset, y,
                                       "RESTART", True, (light_red, red),
                                       (white, black))

        # Quit button for backing out into the main menu.
        self.__quit_button = Button(self.__screen, self.__button_font,
                                    100, 30, x + offset, y,
                                    "BACK", True, (light_red, red),
                                    (white, black))

        # Single player variables
        self.__computer_peice = None # The computer's peice.
        self.__player_peice = None # The player's peice.
        # State variables
        self.__wait = True # Display the screen before running the minimax algorithm.
        self.__finished = False
        self.__board = Board()  # Create an empty 3x3 board.
        self.__win = self.__is_draw = self.__game_over = self.__visible = False
        self.__current_peice = CROSS # The first peice to make a move.
Exemplo n.º 4
0
 def __restart(self):
     """
     Restart the game state with the previous settings, i.e. computer_peice, player_peice stay the same.
     """
     self.__screen.fill(black) # Fill screen black
     self.__board = Board() # Create new empty board.
     # Reset game state.
     self.__wait = True
     self.__winfo = self.__win = self.__is_draw = self.__game_over = False
     # Reset to the default starting peice: Nought.
     self.__current_peice = CROSS
     # Reset the button state.
     self.__restart_button.reset()
     self.__quit_button.reset()
Exemplo n.º 5
0
    def init_round(self):
        self.end_round()
        self.chips = create_chips_without_double(self.highest_double,
                                                 self.current_double)
        random.shuffle(self.chips)

        for player in self.players:
            chips = []
            for i in range(self.n_chips_per_player):
                chips.append(self.chips.pop())
            player.init_turn(chips)

        self.board = Board(len(self.players), self.current_double, self.chips)
        self.current_double -= 1
Exemplo n.º 6
0
 def __reset(self):
     """
     Completely reset the game state.
     """
     self.__screen.fill(black) # Fill the screen with black.
     self.__board = Board()  # Create an empty 3x3 board.
     self.__wait = True
     self.__win = self.__is_draw = self.__game_over = self.__visible = False
     # Reset variables used in singleplayer
     self.__computer_peice = self.__player_peice = None
     # Reset to the default starting peice: Nought.
     self.__current_peice = CROSS
     # Reset the button state.
     self.__restart_button.reset()
     self.__quit_button.reset()
Exemplo n.º 7
0
def main():
    not_quit = True
    while not_quit:
        menu_input = input()
        board = Board()
        board.display_table()

        if check_input(menu_input) == "exit":
            not_quit = False
        if check_input(menu_input) == "start":
            pX, pO = parse_input(menu_input)

            pX = build_player(pX, "X", board)
            pO = build_player(pO, "O", board)

            game = TicTacToeGame(board, pX, pO)
            game.play()

        else:
            print("Bad parameters!")
Exemplo n.º 8
0
def game():
    ships = []
    xdim, ydim = GUI.askforboardsize()
    board = Board(xdim, ydim)
    GUI.printboard(board)
    while True:
        size, xpos, ypos, allign = GUI.askforshiptoplace()
        ship = whichshiptocreate(int(size), allign)
        if board.oktoplaceship(int(ypos), int(xpos), ship):
            board.placeshipat(int(ypos), int(xpos), ship)
            ships.append(ship)
        next = input(
            "Would you like to continue providing ships yes/no = 1/0 respectively: "
        )
        if next.isdigit():
            if next == "0":
                break
            elif next == "1":
                continue
            else:
                print("Bad choose!")
                break
        else:
            print("Bad data. End of providing ships!")
    while len(ships) > 0:
        row, col = GUI.wheretoshot()
        _, text = board.shootat(row, col)
        print(text)
        GUI.printboard(board)
        if "sink" in text:
            ships.pop()
            print("Congratulations you sink all the ships! Game over! ")
Exemplo n.º 9
0
class CoreOfGame(object):
    def __init__(self, configuration_of_ships):
        self.__num_of_shoots = 0
        self.__board = Board()
        self.__generator_of_ship = GeneratorOfShip(self.__board)

        self.__ships = list()
        for num_of_decks in configuration_of_ships:
            self.__ships.append(
                self.__generator_of_ship.create_ship(num_of_decks))
        db.creat_shema()

    def get_board(self):
        return self.__board

    def make_shoot(self, name_cell_of_board):
        target_cell = self.__board.get_cell_of_board(name_cell_of_board)
        if not target_cell:
            return False
        is_damage = False
        for ship in self.__ships:
            if ship.make_damage(target_cell):
                is_damage = True
                break
        if not is_damage:
            target_cell.set_miss_shoot_status()
        self.__inc_num_of_shoots()
        return True

    def __inc_num_of_shoots(self):
        self.__num_of_shoots += 1
        if self.__num_of_shoots >= MAX_NUMBER_OF_SHOOTS:
            return True
        return False

    def __get_num_of_shoots(self):
        return self.__num_of_shoots

    def is_exhausted_all_attempts(self):
        if self.__num_of_shoots >= MAX_NUMBER_OF_SHOOTS:
            return True
        return False

    def is_dead_all_ships(self):
        is_alive_ships = False
        for ship in self.__ships:
            is_alive_ships = is_alive_ships or ship.is_alive()
        if is_alive_ships:
            return False
        return True
Exemplo n.º 10
0
 def setUp(self):
     self.board = Board(10, 10)
     self.horizontalShip = HorizontalShip(4)
     self.verticalShip = VerticalShip(3)
Exemplo n.º 11
0
class TestBoard(TestCase):
    def setUp(self):
        self.board = Board(10, 10)
        self.horizontalShip = HorizontalShip(4)
        self.verticalShip = VerticalShip(3)

    def test_get_xdim(self):
        self.assertEqual(self.board.getxdim(), 10)

    def test_get_ydim(self):
        self.assertEqual(self.board.getydim(), 10)

    def test_is_occupied(self):
        self.assertEqual(self.board.isoccupied(5, 5), False)

    def test_shoot_at_empty_sea(self):
        self.assertEqual(self.board.shootat(4, 4), (True, "You shoot in Sea!"))

    def test_shoot_at_horizontal_ship(self):
        self.board.placeshipat(0, 0, self.horizontalShip)
        self.assertEqual(self.board.shootat(0, 0), (True, "Hit!"))

    def test_shoot_at_vertical_ship(self):
        self.board.placeshipat(0, 0, self.verticalShip)
        self.assertEqual(self.board.shootat(0, 0), (True, "Hit!"))

    def test_ok_to_place_ship(self):
        self.assertEqual(self.board.oktoplaceship(5, 5, self.verticalShip), True)

    def test_place_ship_at(self):
        self.assertEqual(self.board.placeshipat(3, 3, self.horizontalShip), True)

    def test_get_ships(self):
        k = 0
        for row in range(len(self.board.getships())):
            for column in range(len(self.board.getships()[row])):
                if isinstance(self.board.getships()[row][column], EmptySea):
                    k += 1
        self.assertEqual(self.board.getydim()*self.board.getxdim(), k)
Exemplo n.º 12
0
 def __init__(self):
     self.board = Board()
     self.totems = [Totem("{0:04b}".format(i)) for i in range(16)]
Exemplo n.º 13
0
 def __init__(self):
     self.board = Board()
     self.turn = 1
     self.result = 0
Exemplo n.º 14
0
class Game:
    def __init__(self, screen):
        """
        Set up the game.
        Params: screen, root pygame surface.
        """
        # Create the main screen surface.
        self.__screen = screen
        self.__screen.fill((0, 0, 85))  # Fill the background with colour.

        # Initialize Board
        self.__board_surface = pygame.Surface(BOARD_SIZE)
        self.__board_rect = self.__board_surface.get_rect()
        self.__board_rect.x, self.__board_rect.y = BOARD_POS

        # Font filepath.
        topaz_filepath = pygame.font.match_font(FONTFAMILY)

        # Create the font for the title.
        self.__title_font = pygame.font.Font(topaz_filepath, 30)

        # Create the title and center it so that it displays above the board.
        self.__title = Title(self.__screen, self.__title_font, "", 300, 50,
                             True, True, red)

        # Creating the Buttons
        offset = 150
        x = SCREEN_W // 2
        y = SCREEN_H - 50

        # Font for the buttons.
        self.__button_font = pygame.font.Font(topaz_filepath, 15)

        # Restart button for restarting the game, but keeping the same gamemode.
        self.__restart_button = Button(self.__screen, self.__button_font,
                                       100, 30, x - offset, y,
                                       "RESTART", True, (light_red, red),
                                       (white, black))

        # Quit button for backing out into the main menu.
        self.__quit_button = Button(self.__screen, self.__button_font,
                                    100, 30, x + offset, y,
                                    "BACK", True, (light_red, red),
                                    (white, black))

        # Single player variables
        self.__computer_peice = None # The computer's peice.
        self.__player_peice = None # The player's peice.
        # State variables
        self.__wait = True # Display the screen before running the minimax algorithm.
        self.__finished = False
        self.__board = Board()  # Create an empty 3x3 board.
        self.__win = self.__is_draw = self.__game_over = self.__visible = False
        self.__current_peice = CROSS # The first peice to make a move.

    def board_pos(self, mouse_pos):
        """
        Description: Get a valid board position from mouse position.
        Usage: Get the board cell clicked by the user.
        Params: mouse_pos, (x, y), the position of the mouse when clicked.
        Returns: x, y coordinates relative to the game board.
        """
        # Check if the cursor position has collided with the board surface.
        if self.__board_rect.collidepoint(mouse_pos[0], mouse_pos[1]):
            # Now convert this mouse position into a valid position on the board.
            y = int((mouse_pos[1] - self.__board_rect.y) / (self.__board_rect.height // ROWS))
            x = int((mouse_pos[0] - self.__board_rect.x) / (self.__board_rect.width // COLUMNS))
            return x, y
        return False

    def __sp_setup(self, max_ai_depth, computer_first):
        """
        Setup the singleplayer gamemode so that either the computer or the
        user can play first.
        Params: max_ai_depth, int, The maximum recursion depth the minimax will go before stopping.
                computer_first, bool, Will the computer go first?
        """
        self.__max_ai_depth = max_ai_depth
        if computer_first:  # if computer starts first, then bost the computer and current peice are the same.
            self.__computer_peice = self.__current_peice = CROSS
            self.__player_peice = NOUGHT
        else:
            self.__computer_peice = NOUGHT
            self.__current_peice = self.__player_peice = CROSS # Player starts first.

    def __input(self):
        """
        Get input from the player.
        """
        # It's the computers turn when the current peice is equal to the
        # peice used by the computer.
        computers_turn = self.__current_peice == self.__computer_peice

        # wait if we have to.
        # When it's the computer's turn, make a move.
        if not self.__wait and computers_turn:
            # Run the minimax algorithm and retrieve it's best move.
            move = get_move(self.__board, self.__max_ai_depth, self.__computer_peice, self.__player_peice)
            # Then place it.
            self.__board.place_move(self.__current_peice, move)

        # Check for ESC key press.
        # Check for any mouse input on the board.
        for event in pygame.event.get():
            # Check if user has clicked.
            # Don't do this unless it's the players turn and the game is not over.
            if not computers_turn and not self.__game_over and event.type == MOUSEBUTTONUP and event.button == 1:
                # Get the cell chosen and place.
                coords = self.board_pos(event.pos)
                # Are these coords valid?
                if coords:
                    self.__board.place_move(self.__current_peice, coords)
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                self.__finished = True
            # Update the state of the buttons.
            self.__restart_button.update(event)
            self.__quit_button.update(event)

        if self.__wait:
            self.__wait = False

    def __update(self):
        """
        Update the state
        """
        # Change the state.
        self.__winfo = self.__board.win(self.__current_peice)
        self.__win = (self.__winfo != False)
        self.__is_draw = self.__board.draw()
        self.__game_over = self.__win or self.__is_draw

        # Switch to the next peice if the game has not already ended.
        if not self.__game_over:
            self.__current_peice = self.__board.active_player

    def __draw(self):
        """
        Draws the current state of the game.
        """
        # Clear the screen.
        self.__screen.fill(black)

        # Draw board and peices.
        draw_board(self.__board_surface, self.__board, white, (17, 0, 34))
        draw_peices(self.__board_surface, self.__board, red, blue)

        # Reset the title message.
        self.__title.text = ""
        self.__title.colours = (white, None)

        # Display a message to the user about the current state of the game,
        # i.e. when a player has won, who's turn it is, when a draw has occured.

        if self.__game_over:
            if self.__win:
                # Check if either a player or computer won.
                if self.__current_peice == self.__computer_peice:
                    self.__title.text = "Computer has won!"
                else:
                    self.__title.text = "Player {} has won!".format(self.__current_peice)
                # Set the colour based on the player.
                colour = red if self.__current_peice == NOUGHT else blue
                # change title colours (fg, bg)
                self.__title.colours = (colour, None)
                # Draw a line straight through the winning three peices.
                draw_win(self.__board_surface, self.__winfo, colour)
            elif self.__is_draw:
                self.__title.text = "Draw!"
        elif self.__current_peice == self.__computer_peice:
            self.__title.text = "Computer's turn!"
        else:
            self.__title.text = "Player {}'s turn!".format(self.__current_peice)

        self.__title.draw() # Draw the title.
        self.__restart_button.draw() # Draw 'restart' button.
        self.__quit_button.draw() # Draw 'quit' button.
        self.__screen.blit(self.__board_surface, self.__board_rect)

    def __restart(self):
        """
        Restart the game state with the previous settings, i.e. computer_peice, player_peice stay the same.
        """
        self.__screen.fill(black) # Fill screen black
        self.__board = Board() # Create new empty board.
        # Reset game state.
        self.__wait = True
        self.__winfo = self.__win = self.__is_draw = self.__game_over = False
        # Reset to the default starting peice: Nought.
        self.__current_peice = CROSS
        # Reset the button state.
        self.__restart_button.reset()
        self.__quit_button.reset()

    def __reset(self):
        """
        Completely reset the game state.
        """
        self.__screen.fill(black) # Fill the screen with black.
        self.__board = Board()  # Create an empty 3x3 board.
        self.__wait = True
        self.__win = self.__is_draw = self.__game_over = self.__visible = False
        # Reset variables used in singleplayer
        self.__computer_peice = self.__player_peice = None
        # Reset to the default starting peice: Nought.
        self.__current_peice = CROSS
        # Reset the button state.
        self.__restart_button.reset()
        self.__quit_button.reset()

    def play(self, gamemode, max_ai_depth, computer_first = False):
        """
        Starts a loop displaying the game on the given surface
        until the game is over.
        Params: gamemode, int, 1 for singleplayer, 2 for multiplayer.
                max_ai_depth, int, The maximum recursion depth the minimax can go before stopping.
                computer_first, bool, Will the computer play first if the gamemode is single player?
        Returns: None
        """
        # Setup the game
        if gamemode == SINGLEPLAYER:
            self.__sp_setup(max_ai_depth, computer_first)

        # When computer goes first, the minimax algorithm will be ran immediately
        # in order to fix this, display one frame then run the minimax.
        self.__wait = True
        # Conditional for main loop.
        # When true this indicates that the user wants to go back to the
        # main menu.
        clock = pygame.time.Clock()
        self.__finished = False
        # Main loop.
        while not self.__finished:
            clock.tick(20)
            if self.__restart_button.clicked:
                self.__restart()
            elif self.__quit_button.clicked:
                self.__finished = True
            # Poll the event queue for input.
            self.__input()
            # Update the game state
            self.__update()
            # Draw
            self.__draw()
            # Update the screen to display everything that had just been drawn.
            pygame.display.update()

        # Reset the game state variables for the next use.
        self.__reset()
Exemplo n.º 15
0
class GameManager:
    def __init__(self, n_players, n_chips_per_player, highest_double,
                 initial_double):
        self.chips = []
        self.n_chips_per_player = n_chips_per_player
        self.highest_double = highest_double
        self.current_double = initial_double
        self.board = None
        self.turn = 0
        self.endgame = False
        self.endgame_counter = 0
        players = []
        for i in range(n_players):
            players.append(Player(i))
        self.players = players

    def init_round(self):
        self.end_round()
        self.chips = create_chips_without_double(self.highest_double,
                                                 self.current_double)
        random.shuffle(self.chips)

        for player in self.players:
            chips = []
            for i in range(self.n_chips_per_player):
                chips.append(self.chips.pop())
            player.init_turn(chips)

        self.board = Board(len(self.players), self.current_double, self.chips)
        self.current_double -= 1

    def end_round(self):
        min_score = math.inf
        winner = None
        for player in self.players:
            player.add_up_points()
            if player.get_current_points() < min_score:
                winner = player
                min_score = player.get_current_points()
            elif player.get_current_points() == min_score:
                if player.get_total_points() < winner.get_total_points():
                    winner = player
        self.turn = winner.get_index()

    def has_next_round(self):
        return self.current_double >= 0

    def name_players(self, *names):
        if len(names) == len(self.players):
            for i in range(len(names)):
                self.players[i].set_name(names[i])

    def has_next_turn(self):
        if not self.board.can_draw():
            self.endgame = True
            if self.endgame_counter >= len(self.players):
                return False
        return not self.players[self.previous_player_id()].is_round_winner()

    def next_turn(self):
        can_play = self.players[self.turn].can_play_any(self.board)

        if not can_play and self.board.can_draw():
            self.players[self.turn].add_chip(self.board.draw())
            can_play = self.players[self.turn].can_play_any(self.board)

        if can_play:
            self.players[self.turn].play_any(self.board)
            if self.endgame:
                self.endgame_counter = 0
        else:
            self.board.set_train(self.turn)
            if self.endgame:
                self.endgame_counter += 1

        self.turn = self.next_player_id()

    def previous_player_id(self):
        return (self.turn - 1) % len(self.players)

    def next_player_id(self):
        return (self.turn + 1) % len(self.players)

    def play_ai_game(self):
        millis = time.time() * 1000
        while self.has_next_round():
            self.init_round()
            while self.has_next_turn():
                print(self)
                self.next_turn()
        self.end_round()
        print(self)
        print(time.time() * 1000 - millis)

    def __str__(self):
        s = [
            "El tablero está así:\n",
            self.board.__str__(), "\nLos jugadores están así"
        ]
        winner = ""
        min_points = math.inf
        for player in self.players:
            s.append("\n")
            s.append(player.__str__())
            if player.get_total_points() == min_points:
                winner = winner + ", " + player.get_name()
            elif player.get_total_points() < min_points:
                min_points = player.get_total_points()
                winner = player.get_name()
        s.append("\nEs turno de ")
        s.append(self.players[self.turn].get_name())
        s.append("\nVa ganando: ")
        s.append(winner)
        s.append("\n\n\n")
        return ''.join(s)