Exemplo n.º 1
0
def double_player_game():
    board = GameBoard()
    print("Player 1: Please type in your name: ")
    player_name_1 = input()
    print("Player 2: Please type in your name: ")
    player_name_2 = input()

    player1 = Human('X', player_name_1)
    player2 = Human('O', player_name_2)

    current_player = player1
    other_player = player2
    winner = None
    game_over = False

    while not game_over:
        print(current_player.name, "Please select the column: [1-7]")
        print(board)
        move_allowed = False
        while not move_allowed:
            move = current_player.get_move(board, other_player)
            move_allowed = board.try_place_piece(move, current_player.sign)

        game_over, winner = board.is_game_over(board.board,
                                               current_player.sign,
                                               other_player.sign)
        current_player, other_player = other_player, current_player

    print(board)
    if winner:
        print("Player", other_player.name, "just won! Game over")
    else:
        print("Tie!")
Exemplo n.º 2
0
class Game:

    def __init__(self):
        self.gameboard = GameBoard()
        #self.gameboard.init_board()

    def wait_input(self):
        self.gameboard.print_board()
        while True:
            pos = input()
            x, y = pos.split(' ')
            self.gameboard.proceed_next_state(int(x), int(y))
            self.gameboard.print_board()

    def input_pos(self, x, y):
        self.gameboard.proceed_next_state(int(x), int(y))
        self.gameboard.get_new_row()
        #self.gameboard.print_board()
        


    def insert_row_to_board(self):
        self.gameboard.board.remove(self.gameboard.board[0])
        self.gameboard.board.append(self.gameboard.new_row)
        self.gameboard.cursor_pos[0] -= 1
        self.gameboard.height += 1
Exemplo n.º 3
0
def single_player_game():
    board = GameBoard()
    print("Player 1: Please type in your name: ")
    player_name = input()
    player1 = Human('X', player_name)
    player2 = Computer('O', 6)
    print("Please select the column: [1-7]")

    current_player = player1
    other_player = player2

    winner = None
    game_over = False

    while not game_over:
        print(board)
        move_allowed = False
        while not move_allowed:
            start = time.time()  # Get the start time
            move = current_player.get_move(board, other_player)
            move_allowed = board.try_place_piece(move, current_player.sign)

        game_over, winner = board.is_game_over(board.board,
                                               current_player.sign,
                                               other_player.sign)
        end = time.time()  # Testing end time
        difference = end - start  # Get the time from start to end
        current_player, other_player = other_player, current_player
        print("Computing Time: ", difference)
    print(board)
    if winner:
        print("Computer Won! Game over")
    else:
        print("Tie!")
Exemplo n.º 4
0
def main():
    board = GameBoard()
    board.set_up()
    while True:
        board.print()
        cell_reference = input(
            "Enter cell to fire at (e.g. A1, B1, ...) or q to quit: ")
        if cell_reference == "q" or cell_reference == "Q":
            print("Bye!")
            return
        (row, column) = GameBoard.translate_cell_reference(cell_reference)
        if row == -1:
            print("'", cell_reference, "' is not a valid cell.", sep="")
            continue
        result = board.fire_missile(row, column)
        if result == FiringResult.HIT:
            print("Hit!")
        elif result == FiringResult.MISSED:
            print("Missed!")
        else:
            print("You've already been there!")
        if board.game_is_won:
            break
    board.print()
    print("Congratulations, you Won!")
Exemplo n.º 5
0
def createGame(difficulty):
    global tileList, tileDictionary, gameBoard

    gameBoard = GameBoard()
    tileList = gameBoard.createBoard(difficulty)
    
    tileDictionary = copy.deepcopy(gameBoard.tileDictionary)
Exemplo n.º 6
0
    def update(self):
        # Main event loop
        for self.event in pygame.event.get():
            if self.event.type == pygame.KEYDOWN:
                self.key_check()

        delay = 0.27 - self.level * 0.005
        if self.gameboard.slow_time_on:
            delay *= 2
            if time.perf_counter() - self.slow_activation_time > 6:
                self.gameboard.slow_time_on = False

        if self.gameboard.swap_shape:
            self.shape = self.next_shape
            self.next_shape = Shape()
            self.gameboard.swap_shape = False

        if time.perf_counter() - self.last_time > delay:
            self.last_time = time.perf_counter()
            self.shape.falling()

        if self.shape.active == False:
            self.gameboard.clear_full_rows()
            self.shape = self.next_shape
            self.next_shape = Shape()
        if self.gameboard.check_loss():
            new_score = self.gameboard.score / 2
            num_lines = self.gameboard.num_lines
            self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size)
            self.gameboard.score = new_score
            self.gameboard.num_lines = num_lines
            self.shape = Shape()
            self.next_shape = Shape()
        if time.perf_counter() - self.start_time > 120:
            self.done_level = True
Exemplo n.º 7
0
class GameManager:
    def __init__(self, player1, player2):
        self.size = (3, 3)

        self.board = GameBoard(
            size=self.size
        )  #, preset=[['X', 'O', 'X'],['O', ' ', 'X'],[' ', ' ', 'O']])
        self.players = [player1, player2]
        self.turn_num = 0
        self.current_player = 0
        self.all_boards = []

    def take_turn(self):
        print(self.board)
        self.all_boards.append(self.board)

        move = self.players[self.current_player].take_turn(self.board)
        self.board = self.board.insert_game_piece(move)

        # print(self.board)

        self.current_player = abs(self.current_player - 1)

    def is_game_over(self):
        # TODO: return winner object (or name)
        return self.board.is_game_over()
Exemplo n.º 8
0
    def default_policy(self, node):

        current_state = node.state

        #         simulation_board = GameBoard(current_state.current_board, simulation = True)

        #         depth = 0
        #         while not current_state.is_terminal() and depth < self.MAX_ROLLOUT_DEPTH:

        #             # Pick one random action to play and get next state
        #             current_state = current_state.get_next_state_with_random_choice(simulation_board)
        #             depth += 1

        #         final_state_reward = simulation_board.score

        #         return final_state_reward

        simulation_board = GameBoard(current_state.current_board,
                                     simulation=True)
        total_score = 0
        for i in range(self.MAX_ROLLOUT_DEPTH):
            board = simulation_board.board
            available_choice = simulation_board.get_available_choices()
            choice = random.choice(available_choice)
            score = simulation_board.proceed_next_state(choice[0], choice[1])
            total_score += self.gamma**i * score
        return total_score
Exemplo n.º 9
0
def glider_demo():
    a_game = GameBoard(8)
    a_game = add_glider(a_game)
    for i in range(50):
        print(a_game)
        sleep(1)
        a_game.progress()
Exemplo n.º 10
0
    def score_move(self, board: GameBoard, my_team_index=0, recursion_level=0):
        teams = ['O', 'X']
        game_over, winner = board.is_game_over()
        if game_over:
            if winner == 'O':
                return None, 100 - recursion_level
            elif winner == 'X':
                return None, -100 + recursion_level
            else:
                return None, 0
        else:  # current board has no score so we score recursively
            move_scores = []
            for move in self.find_available_moves(board):
                to_insert = {move: teams[my_team_index]}
                child_board = board.insert_game_piece(to_insert)
                score = self.score_move(child_board,
                                        my_team_index=abs(my_team_index - 1),
                                        recursion_level=recursion_level + 1)[1]
                move_scores.append((move, score))

            min_max_score = move_scores[0]
            if recursion_level == 0:
                print(move_scores)
                print(min_max_score)

            for move_score in move_scores:
                # print(move_score, min_max_score, my_team_index == 0)
                if my_team_index == 0:  # maximizing
                    if move_score[1] > min_max_score[1]:
                        min_max_score = move_score
                elif my_team_index == 1:  # minimizing
                    if move_score[1] < min_max_score[1]:
                        min_max_score = move_score

            return min_max_score
Exemplo n.º 11
0
def fancy_pattern_demo():
    # https://de.wikipedia.org/wiki/Conways_Spiel_des_Lebens#Andere_Objekte
    a_game = GameBoard(33)
    a_game = fancy_pattern(a_game)
    for i in range(55):
        print(a_game)
        sleep(0.1)
        a_game.progress()
Exemplo n.º 12
0
    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((800, 600))
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(r"C:\Windows\Fonts\consola.ttf", 24)
        self.going = True
        self.gameboard = GameBoard()
Exemplo n.º 13
0
 def __init__(self, game_mode):
     self.exit = False
     self.screen = pygame.display.get_surface()
     self.screen.fill((0, 0, 0))
     self.drawableObjects = []
     self.userBoard = GameBoard()
     self.shipBox = GameShipContainer()
     self.drawSelectedShip = False
     self.flyingDutch = Boat("./res/img/boat_one_mast.png", 0, 0, 0)
Exemplo n.º 14
0
 def __init__(self, num_level):
     self.level = num_level
     self.shape = Shape()
     self.next_shape = Shape()
     self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size)
     self.last_time = time.perf_counter()
     self.slow_activation_time = time.perf_counter()
     self.done_level = False
     self.start_time = time.perf_counter()
Exemplo n.º 15
0
 def __init__(self):
     self.board = GameBoard()
     self.human = Human('O')
     difficulty = int(
         input(
             "Enter a difficulty from 1 to 6.\nYou can go higher, but performance will take longer.\n> "
         ))
     showScores = input("Show scores? (y/n)> ")
     self.ai = AI('X', difficulty, showScores)
Exemplo n.º 16
0
def game_simulation(board):
    simulation_board = GameBoard(board)
    total_reward = 0
    for i in range(MAX_ROUND_NUMBER):
        choice = greedy_policy(simulation_board.board, 0, [], target_net, best=True)
        choice2d = deflatten_action(choice)
        reward = simulation_board.proceed_next_state(choice2d[0], choice2d[1])
        total_reward += reward * gamma_rate ** (i + 1)
    return simulation_board.board, total_reward
Exemplo n.º 17
0
    def __init__(self, player1, player2):
        self.size = (3, 3)

        self.board = GameBoard(
            size=self.size
        )  #, preset=[['X', 'O', 'X'],['O', ' ', 'X'],[' ', ' ', 'O']])
        self.players = [player1, player2]
        self.turn_num = 0
        self.current_player = 0
        self.all_boards = []
Exemplo n.º 18
0
 def getSuccessorStates(self):
     """返回接下来的子状态列表, 和getActions[1]顺序是对应的"""
     successorStates = []
     for row, col in self.board.getEmpty():
         gb = GameBoard(anotherBoard=self.board)
         nextPlayer = 3 - self.player  # 把player编号互换1和2
         gb.addStone(self.player, row, col)
         nextState = State(gb, nextPlayer)
         successorStates.append(nextState)
     return successorStates
Exemplo n.º 19
0
 def __init__(self):
     self.stable_mode = True
     self.gameboard = GameBoard()
     pygame.init()
     self.testFont = pygame.font.Font('freesansbold.ttf', 20)
     self.screen = pygame.display.set_mode(
         ((self.gameboard.column_dim + 5) * cell_size,
          self.gameboard.row_dim * cell_size), 0, 32)
     ## round means how many bottom rows are added
     self.round = 0
Exemplo n.º 20
0
 def get_board_creations_per_second(self, num_boards):
     boards = []
     board = GameBoard(self.num_columns, self.num_rows)
     t0 = time.time()
     for _ in range(num_boards):
         new_board = board.make_copy()
         boards.append(new_board)
     t1 = time.time()
     total_time = t1 - t0
     return num_boards / total_time
Exemplo n.º 21
0
    def draw(self, keep=False):
        card = self.gb.drawCard()
        #print "\tGeniusAgent draw: {0}".format(card)
        prewin_tiles = GameBoard.PreWinTiles(self)
        if card in prewin_tiles:
            self.gb.win_agent = self
            self.win_card = card
            self.win_by_draw += 1
            #print("\t[Test] Agent({0}) 自摸 {1}!".format(self.name, card))
            return

        #print("\t[Test] {0} draw {1}...".format(self.name, card))
        ctype = GameBoard.CardType(card)
        if ctype == 1:
            if self.wang_list.count(card) == 3:  # 確認槓牌
                self._kong(ctype, card)
                return self.draw()
            self.wang_list.append(card)
            self.wang_list.sort()
            self.card_count += 1
        elif ctype == 2:
            if self.tube_list.count(card) == 3:  # 確認槓牌
                self._kong(ctype, card)
                return self.draw()
            self.tube_list.append(card)
            self.tube_list.sort()
            self.card_count += 1
        elif ctype == 3:
            if self.bamb_list.count(card) == 3:  # 確認槓牌
                self._kong(ctype, card)
                return self.draw()
            self.bamb_list.append(card)
            self.bamb_list.sort()
            self.card_count += 1
        elif ctype == 4:
            if self.word_list.count(card) == 3:  # 確認槓牌
                self._kong(ctype, card)
                return self.draw()
            self.word_list.append(card)
            self.word_list.sort()
            self.card_count += 1
        elif ctype == 5:
            if self.wind_list.count(card) == 3:  # 確認槓牌
                self._kong(ctype, card)
                return self.draw()
            self.wind_list.append(card)
            self.wind_list.sort()
            self.card_count += 1
        else:
            self.flow_list.append(card)
            self.flow_list.sort()
            return self.draw()

        dcard = self.drop()
        return dcard
Exemplo n.º 22
0
def main():
    game_board = GameBoard()
    graphics = Graphics((800, 800), game_board)

    while True:
        play_game(game_board, graphics)

        if players_are_bored(graphics):
            break

        game_board = GameBoard()
        graphics.game_board = game_board
Exemplo n.º 23
0
 def __init__(self, gameid, player1, player2):
     self.gameid = gameid
     self.game_over = False
     self.player1 = player1
     self.player2 = player2
     self.board = GameBoard()
     self.spectators = []
     self.status = ''
     self.movecount = '0'
     self.player1.tcphandler.game = self
     self.player2.tcphandler.game = self
     self.player1.start_game(self.board, 'X', player2.name)
     self.player2.start_game(self.board, 'O', player1.name)
Exemplo n.º 24
0
    def __init__(self):

        # settings
        self.buttonSize = 25
        self.defaultCanvasWidth = 500
        self.defaultCanvasHeight = 500
        self.padding = 20
        self.buttonImagePadding = 10
        self.adjBombTextSize = 25

        # window
        self.window = Tk()
        self.window.title("BOMBMOPPER")

        # frames
        self.statusFrame = Frame(self.window)
        self.statusFrame.pack(side=TOP)

        self.gameFrame = Frame(self.window)
        self.gameFrame.pack(side=BOTTOM)

        # canvas
        self.canvasWidth = self.defaultCanvasWidth
        self.canvasHeight = self.defaultCanvasHeight
        self.canvas = Canvas(self.gameFrame)
        self.canvas.config(width=self.canvasWidth,
                           height=self.canvasHeight,
                           background='gray',
                           highlightthickness=0)
        self.canvas.grid(column=0, row=0, sticky=(N, W, E, S))

        # play button
        self.playButton = PlayButton(self)

        # difficulty buttons
        self.easyButton = DifficultyButton(self, 'easy')
        self.intermediateButton = DifficultyButton(self, 'intermediate')
        self.hardButton = DifficultyButton(self, 'hard')

        # initialize board
        self.board = GameBoard(self)

        # initialize status bar
        self.statusBar = StatusBar(self)
        self.statusBar.packContents()
        self.window.update()
        self.statusBar.deactivate()

        # allow quitting without errors
        self.window.protocol('WM_DELETE_WINDOW', self.setInactive)
        self.isActive = True
 def reset_state(self) -> None:
     self.game_board = GameBoard(self.game_board.row_count,
                                 self.game_board.col_count,
                                 self.game_board.wall_count,
                                 self.game_board.box_count,
                                 self.game_board.term_count,
                                 self.original_player_loc)
     self.game_board.init_objects(self.original_walls_loc, Object.WALL)
     self.game_board.init_objects(self.original_boxes_loc, Object.BOX)
     self.game_board.init_objects(self.original_terminal_loc,
                                  Object.TERMINAL)
     self.game_board.init_objects([c for c in self.original_player_loc],
                                  Object.PLAYER)
     self.terminated = False
Exemplo n.º 26
0
class GameClient:
    board = None
    human = None
    ai = None
    winnerFound = False
    humansTurn = True
    currentRound = 1
    MAX_ROUNDS = 42  #max number of turns before game baord is full

    def __init__(self):
        self.board = GameBoard()
        self.human = Human('O')
        while True:  # Integer Input Validation Loop
            try:
                difficulty = int(
                    input(
                        "Enter a difficulty from 1 to 6.\nYou can go higher, but performance will take longer.\n> "
                    ))
            except ValueError:
                print("Invalid input!")
                continue
            else:
                break
        showScores = input("Show scores? (y/n)> ")
        self.ai = AI('X', difficulty, showScores)

    def play(self):
        print("Playing game...")
        self.board.printBoard()
        winner = "It's a DRAW!"
        while self.currentRound <= self.MAX_ROUNDS and not self.winnerFound:
            if self.humansTurn:
                print("Player's turn...")
                playedChip = self.human.playTurn(self.board)
                self.winnerFound = self.board.isWinner(self.human.chip)
                if self.winnerFound: winner = "PLAYER wins!"
                self.humansTurn = False
                print("Player played chip at column ", playedChip[1] + 1)
            else:
                print("AI's turn...")
                playedChip = self.ai.playTurn(self.board)
                self.winnerFound = self.board.isWinner(self.ai.chip)
                if self.winnerFound: winner = "AI wins!"
                self.humansTurn = True
                print("AI played chip at column ", playedChip[1] + 1)
            self.currentRound += 1
            self.board.printBoard()
        return winner

    def reset(self):
        #reset variables
        self.currentRound = 1
        self.winnerFound = False
        self.humansTurn = True
        self.board.resetBoard()
        difficulty = int(
            input(
                "Enter a difficulty from 1 to 6.\nYou can go higher, but performance will take longer.\n> "
            ))
        self.ai.setDifficulty(difficulty)
Exemplo n.º 27
0
    def default_policy(self, node):
        policy_probi, values = self.agent.inference(node.state.current_board)
        node.policy_probi = policy_probi
        current_state = node.state

        simulation_board = GameBoard(current_state.current_board,
                                     simulation=True)
        total_score = 0
        for i in range(3):
            board = simulation_board.board
            choice = self.agent.best_move(board)
            score = simulation_board.proceed_next_state(choice[0], choice[1])
            total_score += self.gamma**i * score
        #print(total_score)
        return total_score
Exemplo n.º 28
0
class SnakeGame:
    def __init__(self):
        self.board = GameBoard()

    def start_game(self):
        pass

    def update_game(self, direction):
        self.board.update_game_board(direction)

    def finish_game(self):
        pass

    def get_board(self):
        return self.board
Exemplo n.º 29
0
    def draw(self, keep=False):
        """ Draw card. (Required API by Agent)
        Gameboard will call this API to informat agent to draw card. Here should be responsible for:
        1. Call API:drawCard() from GameBoard object to draw card.
        2. Add drawn card into hand.
        3. Return card as dropped card. (In general, you will call API:drop() for dropped card)
        * Return:
          Dropped card."""
        card = self.gb.drawCard()
        if GameBoard.GoalState(self, card):  # Check goal state
            self.gb.win_agent = self
            self.win_card = card
            self.win_by_draw += 1
            print("\t[Test] Agent({0}) 自摸 {1}!".format(self.name, card))
            return
        #print("\t[Test] {0} draw {1}...".format(self.name, card))
        ctype = GameBoard.CardType(card)
        if ctype == 1:
            self.wang_list.append(card)
            self.wang_list.sort()
            self.card_count += 1
        elif ctype == 2:
            self.tube_list.append(card)
            self.tube_list.sort()
            self.card_count += 1
        elif ctype == 3:
            self.bamb_list.append(card)
            self.bamb_list.sort()
            self.card_count += 1
        elif ctype == 4:
            self.word_list.append(card)
            self.word_list.sort()
            self.card_count += 1
        elif ctype == 5:
            self.wind_list.append(card)
            self.wind_list.sort()
            self.card_count += 1
        else:
            self.flow_list.append(card)
            self.flow_list.sort()
            return self.draw()

        dcard = None
        if not keep:
            dcard = self.drop()
            #print("\t[Test] {0} drop {1}...".format(self.name, dcard))
            #self.gb.disCard(self, dcard)
        return dcard
Exemplo n.º 30
0
def default_policy(node):

    # Get the state of the game
    current_state = node.state
    #print(current_state.current_board)

    #############
    ## Then add the inferencing score
    #big_score = big_inferencer.inference(current_state.current_board)
    # small_score = small_inferencer.inference(current_state.current_board)
    # return big_score + small_score
    #############

    ############
    simulation_board = GameBoard(current_state.current_board, simulation=True)

    while current_state.is_terminal(rollout=True) == False:

        # Pick one random action to play and get next state
        current_state = current_state.get_next_state_with_random_choice(
            simulation_board)

    final_state_reward = current_state.compute_reward(simulation_board)

    return final_state_reward  #+ big_score
Exemplo n.º 31
0
    def run(self, player1 = "local_player", player2 = "local_player"):
        self.running = False
        self.clock = pygame.time.Clock() #to track FPS
        self.fps= 0

        ChessBoardAssets.load_assets()

        self.board_pos_mouseover_label = render_text("0 / 0", (100, 100, 200))

        self.game_board = GameBoard()

        self.white_pieces = []
        self.black_pieces = []

        self.captured_pieces = []
        
        self.fill_board()


        self.turn = TURN.PLAYER_1
        self.moves = []

        if player1 == "local_player":
            self.player1 = Player("black", self.game_board, self.white_pieces, self.black_pieces)
        elif player1 == "ai_player":
            self.player1 = RandomAI("black", self.game_board, self.white_pieces, self.black_pieces)

        if player2 == "local_player":
            self.player2 = Player("white", self.game_board, self.white_pieces, self.black_pieces)
        elif player2 == "ai_player":
            self.player2 = RandomAI("white", self.game_board, self.white_pieces, self.black_pieces)

        self.mainLoop()
Exemplo n.º 32
0
 def __init__(self, players):
     self.board = GameBoard()
     self.players = [PlayerState(i) for i in range(0, players)]
     self.longestroad = None #int - PlayerId
     self.largestarmy = None #int - PlayerId
     self.turn = None #int - PlayerId
     #Phases: discard, buildsettle, buildroad, moverobber, respondtrade, chooseplayer, standard, ended, turnended
     self.phase = None
     self.phaseinfo = None
     self.lastroll = None #int - Roll value
     self.numturns = 0
Exemplo n.º 33
0
def findSquares(board):
    """Find complete squares of 3x3

    Return None if nothing is found
    Otherwise return a tuple.
        The first element is the number of squares found.
        The second is a copy of the board with each dead square marked."""

    newBoard = GameBoard()

    newBoard.copy(board)

    squareCount = 0

    # All setup, just mark those squares (if they exist)

    for j in range(newBoard.getHeight() - 3):
        for i in range(newBoard.getWidth() - 3):
            if newBoard.squareAt(i, j, 1):
                squareCount = squareCount + 1

    # Marked, check things

    if squareCount > 0:
        return (squareCount, newBoard)
    else:
        return None
Exemplo n.º 34
0
class Game:

    def __init__(self, board_size, row_size):

        self.result = "Neither"
        self.game_board = GameBoard(board_size)

    '''
        Check if the specified pawn color has a winning position
    '''

    def checkForWin(self, color):

        c = color # R, B

    '''
        Rotate the game board 90 degrees clockwise
    '''

    def rotateClockwise90(self):

        self.game_board.rotateClockwise90()
Exemplo n.º 35
0
    def slotNewGameAction(self):
        self.disconnect(self.options.boardSizeBox,QtCore.SIGNAL('valueChanged(int)'),self.slotBoardSize)
        #self.options.boardSizeBox.disconnect()
        self.gameBoard = GameBoard(self)
        self.setCentralWidget(self.gameBoard)
        self.gameBoard.initializeGameBoard()
        self.gameBoard.update()

        if(self.playerFirstMove == True):
            self.gameState = PlayerMoveState(self.gameBoard)
        else:
            self.gameState = AIMoveState(self.gameBoard)
            
        self.gameState.performAction()
Exemplo n.º 36
0
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.resize(500, 540)
        self.setMaximumSize(500,540)
        self.setMinimumSize(500,540)
        self.setWindowTitle('PSZT Gomoku Game')
        self.setWindowIcon(QtGui.QIcon('ico.png'))
        self.centerWindow()

        self.initializeGame()
        self.gameBoard = GameBoard(self)
        self.setCentralWidget(self.gameBoard)

        self.initializeState()
        self.initializeMenu()
        self.statusBar()    
Exemplo n.º 37
0
    def gameSetup(self, gameInfo):
        log.msg('gameInfo: %s' % gameInfo)
        size = gameInfo['size']
        toWin = gameInfo['toWin']
        players = gameInfo['players']
        maxPlayers = gameInfo['maxPlayers']
        queue = gameInfo['queue']
        board = gameInfo['board']

        self.board = GameBoard(size=size, toWin=toWin, maxPlayers=maxPlayers)

        for player in players:
            self.addPlayer(player)
            self.board.addPlayer(player)

        self.showBoard()

        d = self.perspective.callRemote('takePlayerBoard', self)
        d.addCallback(self.whenReady)
Exemplo n.º 38
0
class GameState(object):
    def __init__(self, players):
        self.board = GameBoard()
        self.players = [PlayerState(i) for i in range(0, players)]
        self.longestroad = None #int - PlayerId
        self.largestarmy = None #int - PlayerId
        self.turn = None #int - PlayerId
        #Phases: discard, buildsettle, buildroad, moverobber, respondtrade, chooseplayer, standard, ended, turnended
        self.phase = None
        self.phaseinfo = None
        self.lastroll = None #int - Roll value
        self.numturns = 0

    def accept(self, v):
        v.visit(self)
        for p in self.players:
            p.accept(v)
        self.board.accept(v)
    def maxPlayerScore(self):
        return max([player.score for player in self.players])
    def addResource(self, player, resource, amount):
        self.players[player].addResource(resource, amount)
    def removeResource(self, player, resource, amount):
        self.players[player].removeResource(resource, amount)
    def countResources(self, player):
        return self.players[player].resourceCount()
    def getRandomResource(self, player):
        return self.players[player].getRandomResource()

    def getSurroundingResources(self, nodeid):
        return self.board.getSurroundingResources(nodeid)

    def addCard(self, player, card):
        self.players[player].addCard(card)
    def removeCard(self, player, card):
        self.players[player].removeCard(card)

    def getBuildings(self, dieroll):
        return self.board.getBuildings(dieroll)
    def updateAllScores(self):
        for i in xrange(0,len(self.players)):
            self.updateScore(i)

    def updateScore(self, player):
        c = self.board.getCount(player, 'city')
        s = self.board.getCount(player, 'settlement')
        army = 2 if (player == self.largestarmy) else 0
        road = 2 if (player == self.longestroad) else 0
        vpcards = self.players[player].cards['vp']
        self.players[player].score = c*2 + s + army + road

    def addBuilding(self, player, building, corner):
        self.board.addBuilding(corner, player, building)
        self.players[player].remBuildings[building] -= 1
        if building == 'city':
            self.players[player].remBuildings['settlement'] += 1

    def addRoad(self, player, corner1, corner2):
        self.board.addRoad(corner1,corner2,player)
        self.players[player].remBuildings["road"] -= 1

    def getLongestRoads(self):
        return self.board.getLongestRoad()
    # This could be too slow!! Called when things are built
    def updateRemaining(self, player):
        c = self.board.getCount(player, 'city')
        startingCities = self.players[player].startingBuildings["city"]
        r = self.board.getCount(player, 'road')
        startingRoads = self.players[player].startingBuildings["road"]
        s = self.board.getCount(player, 'settlement')
        startingSettlement = self.players[player].startingBuildings["settlement"]
        self.players[player].remBuildings["city"] = startingCities - c
        self.players[player].remBuildings["road"] = startingRoads - r
        self.players[player].remBuildings["settlement"] = startingSettlement - s

    def getAdjacentPlayers(self, tile):
        return self.board.getAdjacentPlayers(tile)

    def setRobberTile(self, tile):
        self.board.setRobber(tile)
    def getRobberTile(self):
        return self.board.getRobberPos()
Exemplo n.º 39
0
'''
Created on May 11, 2015

@author: Jugal112
'''
from GameBoard import GameBoard

board = GameBoard();
board.menu();
Exemplo n.º 40
0
class TG(pb.Referenceable, Game.TwistedGame):
    def showBoard(self):
        size = self.board.size
        boardSize = self.boardSize
        px0 = self.px0
        py0 = self.py0

        boxSize = int(boardSize / size)

        for x in range(size):
            for y in range(size):
                pos = (x, y)
                px = px0 + x*boxSize
                py = py0 + y*boxSize
                s = Drawable.Square(side=boxSize-4, color=BLACK)
                s.set_position((px, py))
                stat = Drawable.Stationary(sprite=s)
                stat.draw()
                if pos in self.board.board:
                    name = self.board.board[pos]
                    color = COLORS[self.players.index(name)]
                    c = Drawable.Circle(radius=boxSize-10, color=color)
                    c.set_position((px, py))
                    stat = Drawable.Stationary(sprite=c)
                    stat.draw()

    def set_name(self):
        if len(sys.argv) > 1:
          name = sys.argv[1]
        else:
            try:
                name = os.getlogin()
            except:
                name = 'guest0'
        self.name = name

    def connect(self):
        print 'connecting as', self.name
        d = pb.connect("localhost", 8800, self.name, 'guest',
                             "TwistTacToeService")
        d.addCallback(self.connected)
        d.addErrback(self.connectionFailed)

    def connectionFailed(self, msg):
        if self.name.startswith('guest'):
            n = int(self.name[-1])
            if n < 3:
                n += 1
                self.name = 'guest%s' % n
                self.connect()
            else:
                self.connectionReallyFailed()
        else:
            self.name = 'guest0'
            self.connect()

    def connectionReallyFailed(self):
        log.msg('Connection Failed')
        errMsg = Drawable.String(message='Connection Failed')
        errMsg.set_position((200, 200))
        self.errMsg = Drawable.Stationary(sprite=errMsg)
        self.errMsg.draw()

        if not self.startedServer:
            print 'trying to start server'
            self.startedServer = 1
            os.spawnlp(os.P_NOWAIT, 'python', 'python', 'GameServer.py')
            time.sleep(9)
            self.set_name()
            self.connect()

    def connected(self, perspective):
        print 'ok'
        if hasattr(self, 'errMsg'):
            self.errMsg.uclear()
        self.perspective = perspective
        d = self.perspective.callRemote('get_gameInfo')
        d.addCallback(self.gameSetup)

    def gameSetup(self, gameInfo):
        log.msg('gameInfo: %s' % gameInfo)
        size = gameInfo['size']
        toWin = gameInfo['toWin']
        players = gameInfo['players']
        maxPlayers = gameInfo['maxPlayers']
        queue = gameInfo['queue']
        board = gameInfo['board']

        self.board = GameBoard(size=size, toWin=toWin, maxPlayers=maxPlayers)

        for player in players:
            self.addPlayer(player)
            self.board.addPlayer(player)

        self.showBoard()

        d = self.perspective.callRemote('takePlayerBoard', self)
        d.addCallback(self.whenReady)

    def whenReady(self, one=None):
        restart = Widget.StationaryTextButton(self.window, text='START', group=self.events)
        restart.set_callback(self.reset)
        restart.set_position((conf.WINWIDTH/2, 5))
        restart.draw()
        self.msg2 = restart

    def reset(self, pygameEvent):
        if hasattr(self, 'msg2'):
            self.msg2.clear()
            del(self.msg2)
        self.board.reset_board()
        self.showBoard()
        self.ready()

    def ready(self, one=None):
        self.perspective.callRemote('startGame')

    def remote_joined(self, playerName):
        self.board.addPlayer(playerName)
        self.addPlayer(playerName)

    def addPlayer(self, playerName):
        r = int(self.boardSize / (2 * self.board.maxPlayers))
        #print r
        mx = conf.WINWIDTH - (2 * r)
        my = r
        self.players.append(playerName)
        log.msg('players: %s' % self.players)
        color = COLORS[self.players.index(playerName)]
        marker = Drawable.Circle(self.window, r,
                                   color=color)
        name = Drawable.String(self.window, playerName.center(9),
                                 fontSize=int(r/2))
        stack = Drawable.StationaryStack(self.window)
        self.playerMarkers[playerName] = stack
        marker.set_position((mx, (2*r)*(len(self.players)-1) + r))
        name.set_position((mx + (r/4), (2*r)*(len(self.players)-1) + r + my))
        stack.push(marker)
        stack.push(name)

    def remote_start(self):
        self.board.startGame()
        self.start()

    def start(self):
        pass

    def remote_left(self, playerName):
        self.board.removePlayer(playerName)
        self.players.remove(playerName)
        self.removePlayer(playerName)

    def removePlayer(self, playerName):
        self.playerMarkers[playerName].empty()

    def remote_badMove(self):
        self.badMove()
        self.makeMove()

    def badMove(self):
        log.msg('errrk')

    def remote_sync(self, board):
        """This should not happen.

        XXX: If it does, this will not work anyhow.

        """

        self.board.board = board

    def remote_showMove(self, playerName, position):
        self.board.move(playerName, position)
        self.showMove(playerName, position)

    def showMove(self, playerName, position):
        x, y = position
        px0 = self.px0
        py0 = self.py0
        boxSize = int(self.boardSize / self.board.size)
        markerSize = int(boxSize / 2) - 5

        color = COLORS[self.players.index(playerName)]
        px = px0 + x*boxSize + 2
        py = py0 + y*boxSize + 2
        c = Drawable.Circle(self.window, markerSize, color=color)
        c.set_position((px, py))
        stat = Drawable.Stationary(self.window, c)
        stat.draw()
        log.msg("%s moved %s" % (playerName, position))

    def remote_go(self):
        if hasattr(self, 'msg'):
            self.msg.clear()
        goMsg = Drawable.String(self.window, 'YOUR TURN')
        goMsg.set_position((20, 5))
        self.msg = Drawable.Stationary(self.window, goMsg)
        self.msg.draw()
        self.makeMove()

    def makeMove(self):
        #log.msg('Your turn: ')
        self.myTurn = 1

    def move(self, position):
        if self.myTurn:
            self.myTurn = 0
            self.perspective.callRemote('move', position)
            self.showMove(self.name, position)
            self.msg.clear()
            del(self.msg)

    def remote_wait(self, playerName):
        if hasattr(self, 'msg'):
            self.msg.clear()
        waitMsg = Drawable.String(message='%s TURN' % playerName)
        waitMsg.set_position((20, 5))
        self.msg = Drawable.Stationary(sprite=waitMsg)
        self.msg.draw()
        self.wait(playerName)

    def wait(self, playerName):
        p = self.players.index(playerName)
        self.board.player = p
        #log.msg('%s turn' % playerName)

    def remote_gameOver(self, playerName):
        self.gameOver(playerName)

    def gameOver(self, playerName):
        log.msg('GAME OVER %s' % playerName)
        if hasattr(self, 'msg'):
            self.msg.clear()
        overMsg = Drawable.String(message='GAME OVER')
        overMsg.set_position((20, 5))
        self.msg = Drawable.Stationary(sprite=overMsg)
        self.msg.draw()
        self.whenReady()

    def positionClicked(self, pygameEvent=None):
        if pygameEvent is None:
            #print 'no event'
            return
        pos = pygameEvent.pos
        px, py = pos
        #print 'pos', pos

        size = self.board.size
        boardSize = self.boardSize
        boxSize = int(boardSize / size)

        px0 = self.px0
        py0 = self.py0
        pxMax = px0 + size*boxSize
        pyMax = py0 + size*boxSize

        if px < px0 or px > pxMax or py < py0 or py > pyMax:
            return None
        else:
            x = -1
            for xEdge in range(px0, pxMax, boxSize):
                if px > xEdge:
                    x += 1
            y = -1
            for yEdge in range(py0, pyMax, boxSize):
                if py > yEdge:
                    y += 1
            self.move((x, y))

    def initialize(self):
        self.set_background(tilename='bg9.png')
        self.boardSize = int(conf.WINHEIGHT * 0.8)
        self.px0 = self.py0 = int(conf.WINHEIGHT * 0.1)

        self.players = []
        self.myTurn = 0
        self.playerMarkers = {}
        self.set_name()
        self.connect()

        self.startedServer = 0

        self.events.add(Event.MOUSEBUTTONDOWN_Event(button=1,
                                            callback=self.positionClicked))
Exemplo n.º 41
0
class ChessGame:
    def __init__(self):
        pass

    def run(self, player1 = "local_player", player2 = "local_player"):
        self.running = False
        self.clock = pygame.time.Clock() #to track FPS
        self.fps= 0

        ChessBoardAssets.load_assets()

        self.board_pos_mouseover_label = render_text("0 / 0", (100, 100, 200))

        self.game_board = GameBoard()

        self.white_pieces = []
        self.black_pieces = []

        self.captured_pieces = []
        
        self.fill_board()


        self.turn = TURN.PLAYER_1
        self.moves = []

        if player1 == "local_player":
            self.player1 = Player("black", self.game_board, self.white_pieces, self.black_pieces)
        elif player1 == "ai_player":
            self.player1 = RandomAI("black", self.game_board, self.white_pieces, self.black_pieces)

        if player2 == "local_player":
            self.player2 = Player("white", self.game_board, self.white_pieces, self.black_pieces)
        elif player2 == "ai_player":
            self.player2 = RandomAI("white", self.game_board, self.white_pieces, self.black_pieces)

        self.mainLoop()


    #wait until a key is pressed, then return
    def waitForKey(self):
        press=False
        while not press:
            for event in pygame.event.get():
                if event.type == KEYUP:
                    press = True
             
    #enter the main loop, possibly setting max FPS
    def mainLoop(self, fps=0):
        self.running = True
        self.fps= fps
        
        while self.running:
            pygame.display.set_caption("FPS: %i" % self.clock.get_fps())
            
            events = pygame.event.get()
            self.player1.handleEvents(events, self.turn==TURN.PLAYER_1, self)
            self.player2.handleEvents(events, self.turn==TURN.PLAYER_2, self)

            self.update()
            self.draw()
            pygame.display.flip()
            self.clock.tick(self.fps)
            
    def update(self):
        self.game_board.update(self.white_pieces + self.black_pieces)
        self.player1.update(self.captured_pieces)
        self.player2.update(self.captured_pieces)

        if self.turn == TURN.PLAYER_1:
            move = self.player1.get_move()

        elif self.turn == TURN.PLAYER_2:
            move = self.player2.get_move()

        if move: # if received move, execute it
            move.execute(self.white_pieces, self.black_pieces, self.captured_pieces)
            self.moves.append(move)
            self.turn = (self.turn + 1) % 2
        # wait for p1 move, execute - wait for p2 move, execute (with time limit?)

        
    def draw(self):
        self.game_board.draw()
        for piece in self.black_pieces:
            piece.draw()
        for piece in self.white_pieces:
            piece.draw()

        if Options.show_captured_pieces: # draw captured pieces on the side of the board
            xoffset = 10
            for piece in self.captured_pieces: #Refactor: move this to piece class?
                piece.draw(xoffset)
                xoffset += 5


        self.draw_color_helpers()
        
        screen.blit(self.board_pos_mouseover_label, (10, 450))


       
    def draw_color_helpers(self):
        if self.turn == TURN.PLAYER_1 and self.player1.type == "local_player" and self.player1.selected_piece:
            if Options.highlight_selected:
                screen.blit(ChessBoardAssets.selected_piece, (self.player1.selected_piece.board_x * tile_size + offset[0], self.player1.selected_piece.board_y * tile_size + offset[1]))# draw selected

            for pos in self.player1.selected_piece.possible_moves: # draw possible captures & moves
                if Options.highlight_capturable and self.game_board.board[pos[0]][pos[1]].occupying_piece:
                    screen.blit(ChessBoardAssets.possible_capture, (pos[0] * tile_size + offset[0], pos[1] * tile_size + offset[1])) # draw possible captures
                elif Options.highlight_possible_moves:
                    screen.blit(ChessBoardAssets.possible_move, (pos[0] * tile_size + offset[0], pos[1] * tile_size + offset[1])) # draw possible moves

        elif self.turn == TURN.PLAYER_2 and self.player2.type == "local_player" and self.player2.selected_piece:
            if Options.highlight_selected:
                screen.blit(ChessBoardAssets.selected_piece, (self.player2.selected_piece.board_x * tile_size + offset[0], self.player2.selected_piece.board_y * tile_size + offset[1]))

            for pos in self.player2.selected_piece.possible_moves:
                if Options.highlight_capturable and self.game_board.board[pos[0]][pos[1]].occupying_piece:
                    screen.blit(ChessBoardAssets.possible_capture, (pos[0] * tile_size + offset[0], pos[1] * tile_size + offset[1])) # draw possible captures
                elif Options.highlight_possible_moves:
                    screen.blit(ChessBoardAssets.possible_move, (pos[0] * tile_size + offset[0], pos[1] * tile_size + offset[1])) # draw possible moves


    def fill_board(self):
        for i in range(8):
            self.black_pieces.append(Pawn("black", i, 6, tile_size, tile_size, ChessBoardAssets.black_pawn_surface))
            self.white_pieces.append(Pawn("white", i, 1, tile_size, tile_size, ChessBoardAssets.white_pawn_surface))

        # rooks
        self.black_pieces.append(Rook("black", 7, 7, tile_size, tile_size, ChessBoardAssets.black_rook_surface))
        self.black_pieces.append(Rook("black", 0, 7, tile_size, tile_size, ChessBoardAssets.black_rook_surface))

        self.white_pieces.append(Rook("white", 7, 0, tile_size, tile_size, ChessBoardAssets.white_rook_surface))
        self.white_pieces.append(Rook("white", 0, 0, tile_size, tile_size, ChessBoardAssets.white_rook_surface))

        # Bishop
        self.black_pieces.append(Bishop("black", 5, 7, tile_size, tile_size, ChessBoardAssets.black_bishop_surface))
        self.black_pieces.append(Bishop("black", 2, 7, tile_size, tile_size, ChessBoardAssets.black_bishop_surface))

        self.white_pieces.append(Bishop("white", 5, 0, tile_size, tile_size, ChessBoardAssets.white_bishop_surface))
        self.white_pieces.append(Bishop("white", 2, 0, tile_size, tile_size, ChessBoardAssets.white_bishop_surface))

        # knights
        self.black_pieces.append(Knight("black", 6, 7, tile_size, tile_size, ChessBoardAssets.black_knight_surface))
        self.black_pieces.append(Knight("black", 1, 7, tile_size, tile_size, ChessBoardAssets.black_knight_surface))

        self.white_pieces.append(Knight("white", 6, 0, tile_size, tile_size, ChessBoardAssets.white_knight_surface))
        self.white_pieces.append(Knight("white", 1, 0, tile_size, tile_size, ChessBoardAssets.white_knight_surface))

        # Queens
        self.black_pieces.append(Queen("black", 3, 7, tile_size, tile_size, ChessBoardAssets.black_queen_surface))
        self.white_pieces.append(Queen("white", 3, 0, tile_size, tile_size, ChessBoardAssets.white_queen_surface))

        # Kings
        self.black_pieces.append(King("black", 4, 7, tile_size, tile_size, ChessBoardAssets.black_king_surface))
        self.white_pieces.append(King("white", 4, 0, tile_size, tile_size, ChessBoardAssets.white_king_surface))

    def keyDown(self, key):
        pass
        
    def keyUp(self, key):
        pass
    
    def mouseUp(self, button, pos):
        pass
        
    def mouseMotion(self, buttons, pos, rel):
        pass
Exemplo n.º 42
0
 def test_basicMove(self):
     g = GameBoard()
     position = (17, 3)
     roll = 3
     landings = g.move(position, roll, position)
     assert landings == ((16, 3), (18, 3), (17, 4), (17, 2), (16, 5), (18, 5), (17, 6))
Exemplo n.º 43
0
    def __init__(self, board_size, row_size):

        self.result = "Neither"
        self.game_board = GameBoard(board_size)
Exemplo n.º 44
0
class GameWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.resize(500, 540)
        self.setMaximumSize(500,540)
        self.setMinimumSize(500,540)
        self.setWindowTitle('PSZT Gomoku Game')
        self.setWindowIcon(QtGui.QIcon('ico.png'))
        self.centerWindow()

        self.initializeGame()
        self.gameBoard = GameBoard(self)
        self.setCentralWidget(self.gameBoard)

        self.initializeState()
        self.initializeMenu()
        self.statusBar()    

    # Method is used to initialize Menu
    def initializeMenu(self):
        self.newGame = QtGui.QAction(QtGui.QIcon('newGame.png'),'New game',self)
        self.newGame.setShortcut('Ctrl+N')
        self.newGame.setStatusTip('Star new game')
        self.connect(self.newGame,QtCore.SIGNAL('triggered()'),self.slotNewGameAction)

        self.options = QtGui.QAction(QtGui.QIcon('options.png'),'Options',self)
        self.options.setShortcut('Ctrl+O')
        self.options.setStatusTip('Configure options')
        self.connect(self.options, QtCore.SIGNAL('triggered()'), self.slotOptionsAction)
                
        self.exit = QtGui.QAction(QtGui.QIcon('exit.png'), 'Exit', self)
        self.exit.setShortcut('Ctrl+Q')
        self.exit.setStatusTip('Exit application')
        self.connect(self.exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))

        self.about = QtGui.QAction(QtGui.QIcon('about.png'),'About',self)
        self.about.setShortcut('Ctrl+A')
        self.about.setStatusTip('Read about Game and autors')
        self.connect(self.about,QtCore.SIGNAL('triggered()'),self.slotAboutAction)

        self.aboutPyQt = QtGui.QAction(QtGui.QIcon('aboutPyQt.png'),'About PyQt',self)
        self.aboutPyQt.setShortcut('Ctrl+T')
        self.aboutPyQt.setStatusTip('Read about PyQt')
        self.connect(self.aboutPyQt,QtCore.SIGNAL('triggered()'),self.slotAboutPyQtAction)
        
        menubar = self.menuBar()
        file = menubar.addMenu('&Game')
        file.addAction(self.newGame)
        file.addAction(self.options)
        file.addAction(self.exit)
        help = menubar.addMenu('&Help')
        help.addAction(self.about)
        help.addAction(self.aboutPyQt)

        self.initializeOptions()

    # Method is used to initialize Game Options Widget
    def initializeOptions(self):
        self.options = QtGui.QWidget()
        self.options.resize(400, 200)
        self.options.setMaximumSize(400,200)
        self.options.setMinimumSize(400,200)
        self.options.setWindowTitle('PSZT Gomoku Game - Options')
        self.options.setWindowIcon(QtGui.QIcon('options.png'))                
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.options.geometry()
        self.options.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

        # Init board size options
        self.options.setBoardSize = QtGui.QLabel("Set Board size:",self.options)
        self.options.setBoardSize.move(20,10)
        self.options.boardSizeBox = QtGui.QSpinBox(self.options)
        self.options.boardSizeBox.setGeometry(20,30,50,20)
        self.options.boardSizeBox.setMinimum(7)
        self.options.boardSizeBox.setMaximum(25)
        self.options.boardSizeBox.setValue(25)
        self.options.boardSizeBox.setSingleStep(2)
        self.options.sizeValue = 27

       # Init alpha-beta options
        self.options.setABDepth = QtGui.QLabel("Set A-B depth:",self.options)
        self.options.setABDepth.move(150,10)
        self.options.depthBox = QtGui.QSpinBox(self.options)
        self.options.depthBox.setGeometry(150,30,50,20)
        self.options.depthBox.setMinimum(1)
        self.options.depthBox.setMaximum(10)
        self.options.depthBox.setValue(2)

        self.options.setMaxSearchTime = QtGui.QLabel("Set max. search time:",self.options)
        self.options.setMaxSearchTime.move(230,10)
        self.options.timeBox = QtGui.QDoubleSpinBox(self.options)
        self.options.timeBox.setGeometry(230,30,50,20)
        self.options.timeBox.setMinimum(0.1)
        self.options.timeBox.setMaximum(10.0)
        self.options.timeBox.setValue(3.0)
        self.options.timeBox.setSingleStep(0.1)

        # backup values
        self.options.depthValue = 2
        self.options.timeValue = 3.0
        
        self.connect(self.options.boardSizeBox,QtCore.SIGNAL('valueChanged(int)'),self.slotBoardSize)
        self.connect(self.options.timeBox,QtCore.SIGNAL('valueChanged(double)'),self.slotMaxTime)
        self.connect(self.options.depthBox,QtCore.SIGNAL('valueChanged(int)'),self.slotMaxDepth)


        self.options.abButtonGroup = QtGui.QButtonGroup()

        self.options.chooseABValue = QtGui.QLabel("Choose A-B value:",self.options)
        self.options.chooseABValue.move(180,80)

        self.options.useDepth = QtGui.QRadioButton("Use depth",self.options)
        self.options.useDepth.move(180,100)
        self.connect(self.options.useDepth, QtCore.SIGNAL('pressed()'), self.slotUseDepth)
        
        self.options.useTime = QtGui.QRadioButton("Use time",self.options)
        self.options.useTime.move(180,120)
        self.options.useTime.toggle()
        self.connect(self.options.useTime, QtCore.SIGNAL('pressed()'), self.slotUseTime)

        self.options.abButtonGroup.addButton(self.options.useDepth)
        self.options.abButtonGroup.addButton(self.options.useTime)

        # backup values
        self.options.useDepthValue = False
        self.options.useTimeValue = True

        # Init figure options
        self.options.figureButtonGroup = QtGui.QButtonGroup()

        self.options.choosePlayerFigure = QtGui.QLabel("Choose Player figure:",self.options)
        self.options.choosePlayerFigure.move(20,80)

        self.options.useWhite = QtGui.QRadioButton("Use white",self.options)
        self.options.useWhite.move(20,100)
        self.connect(self.options.useWhite, QtCore.SIGNAL('pressed()'), self.slotUseWhite)

        self.options.useBlack = QtGui.QRadioButton("Use black",self.options)
        self.options.useBlack.move(20,120)
        self.options.useBlack.toggle()
        self.connect(self.options.useBlack, QtCore.SIGNAL('pressed()'), self.slotUseBlack)

        self.options.figureButtonGroup.addButton(self.options.useBlack)
        self.options.figureButtonGroup.addButton(self.options.useWhite)

        # backup values
        self.options.playerFigureValue = 2
        self.options.aiFigureValue = 1
        self.options.playerFirstMoveValue = True

        self.options.okButton = QtGui.QPushButton("OK",self.options)
        self.options.okButton.move(20,160)

        self.options.cancelButton = QtGui.QPushButton("Cancel",self.options)
        self.options.cancelButton.move(180,160)

        self.connect(self.options.okButton, QtCore.SIGNAL('pressed()'), self.okClose)                                                               
        self.connect(self.options.cancelButton, QtCore.SIGNAL('pressed()'), self.options.close)

    # Method is used to confirm option changes and close options window.
    def okClose(self):
        self.boardSize = self.options.sizeValue
        self.gameBoard.boardSize = self.boardSize
        self.gameBoard.update()
        self.maxDepth = self.options.depthValue
        self.maxTime = self.options.timeValue
        self.useTime = self.options.useTimeValue
        self.useDepth = self.options.useDepthValue
        self.playerFigure = self.options.playerFigureValue
        self.aiFigure = self.options.aiFigureValue
        self.playerFirstMove =self.options.playerFirstMoveValue
        
        self.options.close()

    # Method is used to set game board size.
    def slotBoardSize(self,value):
        self.options.sizeValue = value +2

    # Method is used to set max search depth of alpha-beta algorithm.
    def slotMaxDepth(self,value):
        self.options.depthValue = value

    # Method is used to set max search time of alpha-beta algorithm.
    def slotMaxTime(self,value):
        self.options.timeValue = value
    
    # Method is used to set that alpha-beta will use time bound.
    def slotUseTime(self):
        if(self.options.useTime.isDown):
            self.options.useTimeValue = True
            self.options.useDepthValue = False

    # Method is used to set that alpha-beta will use depth boudn.
    def slotUseDepth(self):
        if(self.options.useDepth.isDown):
            self.options.useTimeValue = False
            self.options.useDepthValue = True

    # Method is used to set that Player will use white figure and starts second.
    def slotUseWhite(self):
        if(self.options.useWhite.isDown):
            self.options.playerFigureValue = 1
            self.options.aiFigureValue = 2
            self.options.playerFirstMoveValue = False
            self.aiFigure = 2

    # Method is used to set that Player will use black figure and starts first.
    def slotUseBlack(self):
        if(self.options.useBlack.isDown):
            self.options.playerFigureValue = 2
            self.options.aiFigureValue = 1
            self.options.playerFirstMoveValue = True
            self.aiFigure = 1

    # Method is used to initialize game
    def initializeGame(self):
        self.boardSize = 27
        self.maxDepth = 2
        self.maxTime = 0.1
        self.useTime = True
        self.useDepth = False
        self.playerFigure = 2
        self.aiFigure = 1
        self.playerFirstMove = True

    # Method is used to initialize game state.
    def initializeState(self):
        # set initial game state - Idle
        self.gameState = IdleState(self.gameBoard)
        self.gameState.performAction()

    # Method is used to center widnow on screen.
    def centerWindow(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size =  self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

    # Method is used to catch key press event.
    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()

    # Method is used to start game.
    def slotNewGameAction(self):
        self.disconnect(self.options.boardSizeBox,QtCore.SIGNAL('valueChanged(int)'),self.slotBoardSize)
        #self.options.boardSizeBox.disconnect()
        self.gameBoard = GameBoard(self)
        self.setCentralWidget(self.gameBoard)
        self.gameBoard.initializeGameBoard()
        self.gameBoard.update()

        if(self.playerFirstMove == True):
            self.gameState = PlayerMoveState(self.gameBoard)
        else:
            self.gameState = AIMoveState(self.gameBoard)
            
        self.gameState.performAction()

    # Method is used to show options.
    def slotOptionsAction(self):
        self.options.activateWindow()
        self.options.setVisible(True)
    
    # Method is used to execute about action. Show game rules and credits.
    def slotAboutAction(self):
        QtGui.QMessageBox.about(self,"Gomoku", "Game Gomoku with Alpha-beta AI algorithm "
                                "developed by Michal Andrzejewski and Szymon Jablonski, students "
                                "of Warsaw University of Technology for Basics of Artificial Intelligence course.")

    # Method is used to execute aboutPyQt action. Show information about Qt.
    def slotAboutPyQtAction(self):
        QtGui.QMessageBox.aboutQt(self)

    # Method is used to set game to gameOver state, show winner and close
    # application.
    def gameOver(self, winner):
        #enter idle state
        self.gameState = IdleState(self.gameBoard)
        self.gameState.performAction()
        self.over = QtGui.QWidget()
        self.over.resize(300, 200)
        self.over.setMaximumSize(300,200)
        self.over.setMinimumSize(300,200)
        self.over.setWindowTitle('PSZT Gomoku Game - Game Over!')
        self.over.setWindowIcon(QtGui.QIcon('options.png'))                
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.over.geometry()
        self.over.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

        if winner == self.aiFigure:
            self.over.winnerLabel = QtGui.QLabel("AI won!",self.over)
        elif winner == self.playerFigure:
            self.over.winnerLabel = QtGui.QLabel("Player won!",self.over)
        elif winner == 0:
            self.over.winnerLabel = QtGui.QLabel("Draw!",self.over)

        self.over.winnerLabel.move(110,40)

        self.over.exitButton = QtGui.QPushButton("Exit",self.over)
        self.over.exitButton.move(100,75)
        
        self.over.activateWindow()
        self.over.setVisible(True)
        
        self.connect(self.over.exitButton, QtCore.SIGNAL('pressed()'), self.exitSlot)

    # Method is used to close application.
    def exitSlot(self):
        self.over.close()
        self.close()