예제 #1
0
파일: SkyBlox.py 프로젝트: BKreisel/SkyBlox
def main():
    seconds = 0
    surface = init()

    clock = pygame.time.Clock()
    picker = BlockPicker(surface)

    render_screen(surface)

    scoreboard = Scoreboard(surface)
    board = Gameboard(picker.get_current(),scoreboard)
    render_gameboard(surface,board)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == USEREVENT + 1:
                seconds += 1
                if board.block_fall() == False:
                    pygame.event.clear(KEYDOWN)
                    board.new_block(picker.pick_block())
                render_gameboard(surface, board)

                #print(seconds)

            if event.type == KEYDOWN:
                control_block(event, surface, board)

        pygame.display.update()
        clock.tick(30)
예제 #2
0
def main():
    many = int(
        input(
            "Welcome to Memorize, how many pairs of cards do you want to play with?"
        ))
    cardsp1 = []
    play = Gameboard(many, cardsp1)
    play.gameboard(many, cardsp1)  #calling the gameboard function
    Game(many, Points.pointsp1, Points.pointsp2,
         Gameboard.cardsp1).game()  #calling the game function
예제 #3
0
        def check_if_attached_properly(gb: gameboard.Gameboard):
            """Check if for currently state of gameboard call attach_tetromino_blocks will attach blocks properly"""

            gb.attach_tetromino_blocks()
            x, y = gb.falling_tetromino.current_x, gb.falling_tetromino.current_y

            for y_shift, row in enumerate(gb.falling_tetromino.fields):
                for x_shift, block in enumerate(row):
                    if block == config.BUFFER_BLOCK: # checks only Tetromino BUFFER_BLOCKS (only these are attached)
                        self.assertEqual(gb.fields[y + y_shift][x + x_shift], config.FALLEN_BLOCK)
예제 #4
0
class Game(object):

    _gamespeed = 0.6
    _snake = None
    _gameboard = None
    _screen = None

    def __init__(self):
        # Create the screen object
        curses.initscr()
        self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
        self._screen.keypad(1)
        self._screen.nodelay(1)
        self._screen.timeout(150)
        self._screen.border(1)


        curses.noecho()
        curses.cbreak()

        self._gameboard = Gameboard((20, 20), self._screen)
        self._snake = Snake(self._gameboard)

    def run(self):
        key = KEY_RIGHT
        try:
            while 1:
                event = self._screen.getch()
                key = key if event == -1 else event
                s = None

                if key == KEY_UP:
                    s = SnakeMoveDirection.up
                elif key == KEY_DOWN:
                    s = SnakeMoveDirection.down
                elif  key == KEY_LEFT:
                    s = SnakeMoveDirection.left
                elif key == KEY_RIGHT:
                    s = SnakeMoveDirection.right

                self._snake.move(s)
                self._gameboard.draw()
        finally:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
예제 #5
0
파일: launcher_GUI.py 프로젝트: Tolkatos/P3
    def __init__(self, config_file, nbr_total_item):
        """Constructeur.

        Argument(2):
        config_file : structure du labyrinthe
        nbr_total_item : nombre total d'objet présent dans la structure"""

        pygame.init()
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_WIDTH))
        pygame.display.set_caption("P3 : labyrinthe")
        font = pygame.font.Font(None, 64)
        self.text_victoire = font.render("Victoire !", 1, (0, 255, 0))
        self.text_defeat = font.render("Défaite !", 1, (255, 0, 0))
        self.level = Gameboard(config_file, nbr_total_item)
        self.character = Character(self.level)
        self.keeper = Keeper()
        i = 0
        while i < nbr_total_item:
            self.item = Item(self.level.gameboard)
            self.level.gameboard[self.item.pos_y][self.item.pos_x] = "I"
            i += 1
예제 #6
0
def main():
    rows = int(input("Enter number of rows: "))
    columns = int(input("Enter number of columns "))
    board = Gameboard(rows, columns)
    print("The 0th generation looks like this: ")
    board.drawBoard()
    cont = input("Continue? (Yes: Type Enter - No: Type q): ")
    while cont=="":
        print("The ", board.fetchGenerationNumber(),"\'th generation looks like this: ")
        board.drawBoard()
        cont = input("Continue? (Yes: Type Enter - No: Type q): ")
예제 #7
0
    def __init__(self):
        # Create the screen object
        curses.initscr()
        self._screen = curses.newwin(20, 20, 0, 0) #curses.initscr()
        self._screen.keypad(1)
        self._screen.nodelay(1)
        self._screen.timeout(150)
        self._screen.border(1)


        curses.noecho()
        curses.cbreak()

        self._gameboard = Gameboard((20, 20), self._screen)
        self._snake = Snake(self._gameboard)
예제 #8
0
파일: game.py 프로젝트: jcow/codenames
    def __init__(self):

        self.red_players = set()
        self.blue_players = set()

        self.red_spymaster = None
        self.blue_spymaster = None

        game_key = self.url_maker.make_game_key()

        self.game_key = game_key
        self.red_spymaster_url = self.url_maker.get_url(game_key)
        self.blue_spymaster_url = self.url_maker.get_url(game_key)
        self.red_url = self.url_maker.get_url(game_key)
        self.blue_url = self.url_maker.get_url(game_key)

        self.gameboard = Gameboard()
예제 #9
0
 def __init__(self, x, y, game):
     Window.__init__( self, x, y, 200, 2) 
     
     Visettings.Speed = -1
     
     if Visettings.AutoEnd :
         Visettings.CurrentMode = VISMODE.PLAY
     else:
         Visettings.CurrentMode = VISMODE.PAUSE
     
     Visettings.MaxX = game.states[0].boardX-1
     Visettings.MaxY = game.states[0].boardY-1
     
     Visettings.Player1Name = game.getName(0)
     Visettings.Player2Name = game.getName(0)
     
     Visettings.Game = game
     
     self.Window.erase()
     self.Window.refresh()
     
     self.moveWindow( x, Visettings.MaxY*2+4 )
     
     self.score = Scoreboard( x+Visettings.MaxX*2+5, y, 31, Visettings.MaxY*2+4 )
     self.gameboard = Gameboard( x, y, Visettings.MaxX*2+4, Visettings.MaxY*2+4 )
     self.plantInfo = Plantinfo( x+Visettings.MaxX*2+5+31, y, 32, Visettings.MaxY+1 )
     self.minimap = Minimap( \
     x+Visettings.MaxX*2+5+31+30/2 - Visettings.MaxX/2, \
     Visettings.MaxY+1, \
     Visettings.MaxX+3, \
     Visettings.MaxY+3 )
     
     Visettings.CurX = 0
     Visettings.CurY = 0
     
     self.Window.erase()
예제 #10
0
파일: loops.py 프로젝트: lewismazzei/Fusion
def usernameSubmitted(newGame, username):
	found = False #be default, assume that the name will not be found within the 'game saves' folder
	for fileName in os.listdir('/home/lewis/Documents/School/Fusion/External Files/Game Saves'): #for each file in the 'game saves' folder
		if fileName == '{}.pickle'.format(username): #if a currently unfinished game is being stored using that username...
			found = True #...then flag this fact
	if found: #if the name was found within the folder 
		if newGame: #...and it's a new game then the user will not be able to pick this name
			drawLabel('This username is currently being used.', font(25), BLACK, (250, 450)) #...so draw a message saying so...
			drawLabel('Please use another one.', font(25), BLACK, (250, 480))
			pygame.display.update() #...display it...
			pygame.time.wait(500) #...for a brief moment...
			drawNameInputScreen(newGame, username) #...and then draw the screen again, covering/hiding the message
		else: #if the user is loading a game and the name exists...
			gameboard = openGameSave(username) #...then reload the gameboard attributes from that file into a new gameboard object...
			gameLoop(gameboard) #...and start the game from the point that user left off
	else: #if the name is not found...
		if newGame: #...and the user is starting a new game
			 gameboard = Gameboard(username = username, state = [['Empty' for col in range(5)] for row in range(5)], level = 1, tiles = [], score = 0) #... then instantiate a new gameboard with the username entered...
			 gameLoop(gameboard) #...and start a new game
		else: #if the user is trying to load a game with a name that does not exist within the 'game saves' folder...
			drawLabel('This username is not currently being used', font(25), BLACK, (250, 450)) #...then draw a message saying so...
			pygame.display.update() #...display it...
			pygame.time.wait(500) #...for a brief moment...
			drawNameInputScreen(newGame, username) #...and then draw the screen again, covering/hiding the message
예제 #11
0
class Game():
    """This class handles the game: pits bots versus bots and plays tourneys.
    """
    def __init__(self, board_dimension, perform_experiments, tourney_rounds,
                 human_playing):
        # Set global parameters
        self.board_dimension = board_dimension
        self.perform_experiments = perform_experiments
        self.tourney_rounds = tourney_rounds

        # Create our bots
        self.bot1 = bot('rnd', 'random', self.board_dimension)

        self.bot2 = bot('ab3R',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=3,
                        use_dijkstra=False,
                        use_tt=False,
                        id_time_limit=0)
        self.bot3 = bot('ab3D',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=3,
                        use_dijkstra=True,
                        use_tt=False,
                        id_time_limit=0)
        self.bot4 = bot('ab4D',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=False,
                        id_time_limit=0)

        self.bot6 = bot('ab4D_TT',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=0)

        self.bot7 = bot('ab_TT_ID1',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=1)
        self.bot8 = bot('ab_TT_ID5',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=5)
        self.bot9 = bot('ab_TT_ID10',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=10)

        self.bot10 = bot('mcts500',
                         'mcts',
                         self.board_dimension,
                         iterations=500)
        self.bot11 = bot('mcts1k',
                         'mcts',
                         self.board_dimension,
                         iterations=1000)
        self.bot12 = bot('mcts5k',
                         'mcts',
                         self.board_dimension,
                         iterations=5000)
        self.bot13 = bot('mcts10k',
                         'mcts',
                         self.board_dimension,
                         iterations=10000)

        self.bot14 = bot('mctsinf_T1',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=1)
        self.bot15 = bot('mctsinf_T5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=5)
        self.bot16 = bot('mctsinf_T10',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=10)

        self.bot17 = bot('mctsinf_T1_C0.1',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.1,
                         mcts_time_limit=1)
        self.bot18 = bot('mctsinf_T1_C0.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.5,
                         mcts_time_limit=1)
        self.bot19 = bot('mctsinf_T1_C1.0',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=1,
                         mcts_time_limit=1)
        self.bot20 = bot('mctsinf_T1_C1.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=1.5,
                         mcts_time_limit=1)

        self.bot21 = bot('ab4D_TT_ID10',
                         'alphabeta',
                         self.board_dimension,
                         search_depth=4,
                         use_dijkstra=True,
                         use_tt=True,
                         id_time_limit=10)
        self.bot22 = bot('mctsinf_T10_C0.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.5,
                         mcts_time_limit=10)

        # Experiments
        self.ex1 = [self.bot2, self.bot3, self.bot4]
        self.ex2 = [self.bot4, self.bot6]
        self.ex3 = [self.bot7, self.bot8, self.bot9]
        self.ex4 = [self.bot10, self.bot11, self.bot12, self.bot13]
        self.ex5 = [self.bot14, self.bot15, self.bot16]
        self.ex6 = [self.bot17, self.bot18, self.bot19, self.bot20]
        self.ex7 = [self.bot21, self.bot22]

        # Create a gameboard
        self.gameboard = Gameboard(board_dimension)
        self.board = self.gameboard.board

        # Allow the human to play against the given bot
        if human_playing:
            res = self.Play_human_match(self.bot1, self.board)

        # Choose to perform experiments
        if self.perform_experiments:
            self.Perform_experiments(self.board,
                                     self.ex1)  # Change the experiment here!

            print('End of experiments, shutting down.')
            exit(1)

        else:
            # Or just a few matches between two bots
            for _ in range(20):
                res = self.Play_single_bot_match(self.bot1, self.bot2,
                                                 self.board)
                print("Player " + str(res) + " won")

    def Play_TrueSkill_match(self, board, rounds, bot1, bot2):
        """Plays a tourney with the given bots for the given round. Prints results to screen.

        Args:
            rounds (int): number of rounds to be played
            bot1 (class object): object of bot1
            bot2 (class object): object of bot2

        Returns:
            bot1, bot2 (class objects): bot1 and bot2 objects with updated scores            
        """
        # Retrieve rating from the bot and put it in TrueSkill object
        r_bot1 = Rating(bot1.rating)
        r_bot2 = Rating(bot2.rating)
        # Play a single match and record its output
        outcome = self.Play_single_bot_match(bot1, bot2, board)

        if outcome == 0:  # it is a draw
            r_bot1, r_bot2 = rate_1vs1(r_bot1, r_bot2, True)

        elif outcome == 1:  # bot1 wins
            r_bot1, r_bot2 = rate_1vs1(r_bot1, r_bot2)

        elif outcome == 2:  # bot2 wins
            r_bot2, r_bot1 = rate_1vs1(r_bot2, r_bot1)

        # Update rating
        bot1.rating = r_bot1
        bot2.rating = r_bot2

        return bot1, bot2

    def Play_single_bot_match(self, bot1, bot2, board):
        """Plays a botmatch between the two provided bots. Returns the outcome of the game. 0 means draw,
        1 means bot1 won, 2 means bot 2 won.

        Args:
            bot1 (class object): object of bot1
            bot2 (class object): object of bot2
            board (np array): of the gameboard

        Returns:
            int: describing who won
        """

        # Empty board before the game
        board = np.zeros(shape=(self.board_dimension + 1,
                                self.board_dimension + 1),
                         dtype=int)

        # Empty lingering transposition tables
        bot1.transposition_table = {}
        bot2.transposition_table = {}

        # Play the game until a game ending condition is met.
        while (True):
            # If the board is not yet full, we can do a move
            if not self.gameboard.Check_board_full(board):
                # This finds a bot move and handles board update
                board, elapsed_time = self.Handle_bot_move(
                    board, bot1, 'player1')
                bot1.elapsed_time += elapsed_time
                if self.bot1.Check_winning(board) == 1:
                    print(bot1.name, 'has won!')
                    outcome = 1
                    break
            else:
                print('Board is full!')
                outcome = 0
                break
            # If player 1 did not win, check if the board is full
            if not self.gameboard.Check_board_full(board):
                # Do move for second player
                board, elapsed_time = self.Handle_bot_move(
                    board, bot2, 'player2')
                bot2.elapsed_time += elapsed_time
                if self.bot1.Check_winning(board) == 2:
                    print(bot2.name, 'has won!')
                    outcome = 2
                    break
            else:
                print('Board is full!')
                outcome = 0
                break

        # Print the gameboard
        self.gameboard.Print_gameboard(board)

        return outcome

    def Play_human_match(self, bot1, board):
        """Plays a match between the provided bot and a human. Returns the outcome of the game. 0 means draw,
        1 means the human won, 2 means bot 2 won.

        Args:
            bot1 (class object): object of bot1
            board (np array): of the gameboard

        Returns:
            int: describing who won
        """

        # Empty board before the game
        board = np.zeros(shape=(self.board_dimension + 1,
                                self.board_dimension + 1),
                         dtype=int)

        # Play the game until a game ending condition is met.
        while (True):
            # If the board is not yet full, we can do a move
            if not self.gameboard.Check_board_full(board):
                # Print the board for easy visibility
                self.gameboard.Print_gameboard(board)
                # Ask for input
                row = int(input("What Row do you want to play? "))
                col = int(input("What Column do you want to play? "))

                board = self.gameboard.Update_numpy_board(
                    board, row, col, 'player1')

                if self.bot1.Check_winning(board) == 1:
                    print('The human has won!')
                    outcome = 1
                    break
            else:
                print('Board is full!')
                outcome = 0
                break
            # If player 1 did not win, check if the board is full
            if not self.gameboard.Check_board_full(board):
                # Do move for second player
                board, elapsed_time = self.Handle_bot_move(
                    board, bot1, 'player2')
                bot1.elapsed_time += elapsed_time
                if self.bot1.Check_winning(board) == 2:
                    print(bot1.name, 'has won!')
                    outcome = 2
                    break
            else:
                print('Board is full!')
                outcome = 0
                break

        # Print the gameboard
        self.gameboard.Print_gameboard(board)

        return outcome

    def Handle_bot_move(self, board, given_bot, player):
        """Handles everything regarding the moving of a bot: calls bot class to determine move and 
        updates the board and returns it with the new move.

        Args:
            board (np array): of the gameboard
            given_bot (object): bot object, used to determine the move
            player (string): used in board class to colour the field

        Returns:
            board: updated board
            elapsed_time: time needed for the bot to play its move
        """

        start = time.time()
        # Play the bot move
        row, col = self.bot1.Do_move(board, given_bot)
        end = time.time()

        elapsed_time = round(end - start, 2)
        # Check if the move is legal (also handled in bot class)
        if row < 0 or row > self.board_dimension or col < 0 or col > self.board_dimension:
            raise Exception(
                'Row or col exceeds board boundaries: \n\trow: {0}\n\tcol: {1}\n\tdimension: {2}'
                .format(row, col, self.board_dimension))

        board = self.gameboard.Update_numpy_board(board, row, col, player)

        return board, elapsed_time

    def Create_line_plot(self, df, filename):
        """Simple function that creates a line plot of the given dataframe.

        Args:
            df (pd df): dataframe with TrueSkill scores of the bots
            filename (string): filename to be given
        """
        from matplotlib.ticker import MaxNLocator
        # Y Cap.
        trueskill_max = 50

        # Take the names of the columns and plot these
        ax = df.plot.line(
            title='Round Robin on {0}x{0}'.format(self.board_dimension + 1))

        ax.set_xlabel("Number of rounds played")
        ax.set_ylabel("TrueSkill score")

        plt.xlim([0, self.tourney_rounds])
        plt.ylim([0, trueskill_max])

        # To make X axis nice integers
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))

        # plt.show()
        plt.savefig('plots/{0}-{1}.png'.format(
            filename,
            datetime.datetime.now().strftime("%H:%M:%S")))

    def Create_bar_plot(self, df, filename):
        """Simple function that creates a bar plot of the given dataframe.

        Args:
            df (pd df): dataframe with TrueSkill scores of the bots
            filename (string): filename to be given
        """
        ax = df.T.plot(
            title='Round Robin on {0}x{0}'.format(self.board_dimension + 1),
            kind='bar')

        ax.set_xlabel("Bots")
        ax.set_ylabel("Number of elapsed seconds")

        plt.draw()
        ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

        ax.get_legend().remove()

        # plt.show()
        plt.savefig('plots/{0}3.png'.format(filename))

    def Perform_experiments(self, board, bot_list):
        """This class performs the experiments as required in the Assignment
        """

        column_names = []
        rating_dict = {}
        time_dict = {}

        # Create the pandas dataframe
        for bot in bot_list:
            column_names.append(bot.name)
            rating_dict[bot.name] = bot.rating  # Create a dictionary

        df = pd.DataFrame(columns=column_names)
        # Add initial rating
        df = df.append(rating_dict, ignore_index=True)

        for i in range(self.tourney_rounds):
            print("Round", i)
            # Play a round robin between the players
            bot_list = self.Play_round_robin(bot_list, board)
            # Empty dict and add new ratings
            rating_dict = {}
            for bot in bot_list:
                rating_dict[bot.name] = bot.rating.mu  # Create a dictionary
            # Add scores to dataframe
            df = df.append(rating_dict, ignore_index=True)

        print(df)
        self.Create_line_plot(df, 'round_robin')

        # Now find the elapsed seconds to plot
        for bot in bot_list:
            print('Bot {0} needed {1} seconds.'.format(bot.name,
                                                       bot.elapsed_time))
            time_dict[bot.name] = bot.elapsed_time  # Create a dictionary

        df2 = pd.DataFrame(columns=column_names)
        df2 = df2.append(time_dict, ignore_index=True)

        print(df2)

        # self.Create_bar_plot(df2, 'elapsed_time')

        # Print the number of searched nodes and cutoffs
        for bot in bot_list:
            if bot.searched_nodes > 0:
                print('Bot {0} searched {1} nodes.'.format(
                    bot.name, bot.searched_nodes))
            if bot.cutoffs > 0:
                print('Bot {0} had {1} cutoffs.'.format(bot.name, bot.cutoffs))

    def Play_round_robin(self, bot_list, board):
        """Creates and plays a round robin tourney with the bots given.
        This code is from the pypi library round-robin-tournament
        https://pypi.org/project/round-robin-tournament/

        Args:
            bot_list (list): with bot objects to play the round robin
            board (np array): of the game board

        Returns:
            list: of bots and their updated scores
        """
        from round_robin_tournament import Tournament

        tournament = Tournament(bot_list)

        matches = tournament.get_active_matches()

        # Play a number of round robin tournaments
        while len(matches) > 0:
            # print("{} matches left".format(len(matches)))
            match = matches[0]
            bots = match.get_participants()
            # Get the participants of the current round
            first_participant = bots[0]
            first_participant_bot = first_participant.get_competitor()
            second_participant = bots[1]
            second_participant_bot = second_participant.get_competitor()
            # Print their names
            print('########################################')
            print("{} vs {}".format(first_participant_bot.name,
                                    second_participant_bot.name))
            first_participant_bot, second_participant_bot = self.Play_TrueSkill_match(
                self.tourney_rounds, board, first_participant_bot,
                second_participant_bot)
            # Make sure this match is marked as played
            tournament.add_win(match, first_participant_bot)
            matches = tournament.get_active_matches()

        return bot_list
예제 #12
0
class Viscontrol( Window ):
    score = 0
    gameboard = 0
    plantInfo = 0
    minimap = 0
    
    def __init__(self, x, y, game):
        Window.__init__( self, x, y, 200, 2) 
        
        Visettings.Speed = -1
        
        if Visettings.AutoEnd :
            Visettings.CurrentMode = VISMODE.PLAY
        else:
            Visettings.CurrentMode = VISMODE.PAUSE
        
        Visettings.MaxX = game.states[0].boardX-1
        Visettings.MaxY = game.states[0].boardY-1
        
        Visettings.Player1Name = game.getName(0)
        Visettings.Player2Name = game.getName(0)
        
        Visettings.Game = game
        
        self.Window.erase()
        self.Window.refresh()
        
        self.moveWindow( x, Visettings.MaxY*2+4 )
        
        self.score = Scoreboard( x+Visettings.MaxX*2+5, y, 31, Visettings.MaxY*2+4 )
        self.gameboard = Gameboard( x, y, Visettings.MaxX*2+4, Visettings.MaxY*2+4 )
        self.plantInfo = Plantinfo( x+Visettings.MaxX*2+5+31, y, 32, Visettings.MaxY+1 )
        self.minimap = Minimap( \
        x+Visettings.MaxX*2+5+31+30/2 - Visettings.MaxX/2, \
        Visettings.MaxY+1, \
        Visettings.MaxX+3, \
        Visettings.MaxY+3 )
        
        Visettings.CurX = 0
        Visettings.CurY = 0
        
        self.Window.erase()
        
    def updateMode(self, mode):
        Visettings.CurrentMode = mode
        if mode == VISMODE.PLAY or mode == VISMODE.REWIND:
            Visettings.Speed = Visettings.PlaySpeed
        elif mode == VISMODE.PAUSE:
            Visettings.Speed = -1
            
    
    def run( self ):
        if Visettings.AutoEnd and Visettings.Done:
            return 0
            
        if Visettings.FirstRun:
            self.update()
            Visettings.FirstRun = 0
            
        
        Visettings.Screen.timeout( Visettings.Speed )
        c = Visettings.Screen.getch()
       
        try:
            ch = curses.keyname( c )
        except:
            ch = c
        
        
        if ch == 'q':
            return 0
        elif ch == ' ' or ch == 'p':
            if Visettings.CurrentMode == VISMODE.PAUSE:
                self.updateMode( VISMODE.PLAY )
            else:
                self.updateMode( VISMODE.PAUSE )
        elif ch == 'r':
            self.updateMode( VISMODE.REWIND )
        elif ch == '.':
            self.updateMode( VISMODE.PAUSE )
            self.nextFrame()
        elif ch == ',':
            self.updateMode( VISMODE.PAUSE )
            self.prevFrame()
        elif ch == '=':
            Visettings.PlaySpeed -= 5
            if Visettings.PlaySpeed < 0:
                Visettings.PlaySpeed = 1
            self.updateMode( Visettings.CurrentMode )
        elif ch == '-':
            Visettings.PlaySpeed += 5
            self.updateMode( Visettings.CurrentMode )
        elif ch == 's':
            Visettings.FrameNumber = 0
        elif ch == 'e':
            Visettings.FrameNumber = len(Visettings.Game.states)-1
        elif c == curses.KEY_LEFT:
            Visettings.CurX -= 1
        elif c == curses.KEY_RIGHT:
            Visettings.CurX += 1
        elif c == curses.KEY_UP:
            Visettings.CurY -= 1
        elif c == curses.KEY_DOWN:
            Visettings.CurY += 1
        elif c == curses.KEY_MOUSE:
            k = 0
            
        if Visettings.CurrentMode == VISMODE.PLAY:
            self.nextFrame()
        elif Visettings.CurrentMode == VISMODE.REWIND:
            self.prevFrame()
            
        self.update()
        
        return 1
            
    def nextFrame( self ):
        Visettings.FrameNumber += 1
        if Visettings.FrameNumber >= len(Visettings.Game.states):
            Visettings.FrameNumber = len(Visettings.Game.states)-1
        
        
    def prevFrame( self ):
        Visettings.FrameNumber -= 1
        if Visettings.FrameNumber < 0:
            Visettings.FrameNumber = 0
        
    def update( self ):
        Window.update(self)
        self.Window.attrset( curses.color_pair( Legend.DEFAULT_COLOR ) )
        
        Visettings.Screen.refresh()
        
        # TODO: A bunch of attribute stuff is missing.
        
        Visettings.State = Visettings.Game.states[Visettings.FrameNumber];
        Visettings.Player1Score = Visettings.Game.states[Visettings.FrameNumber].player0Score
        Visettings.Player2Score = Visettings.Game.states[Visettings.FrameNumber].player1Score
        Visettings.Player1Light = Visettings.Game.states[Visettings.FrameNumber].player0Light
        Visettings.Player2Light = Visettings.Game.states[Visettings.FrameNumber].player1Light
        
        self.score.update()
        self.gameboard.newState()
        self.minimap.newState()
        self.plantInfo.update()
        
        offset = 50
        
        percent = float(Visettings.FrameNumber+1)/len(Visettings.Game.states)
        
        if percent > 1:
            percent = 1
        
        blocks = int((Visettings.MaxX*2+offset-10)*percent)
        
        for i in range(1, blocks+1):
            self.Window.addch( 0, i, curses.ACS_HLINE )
        for i in range( blocks+1, Visettings.MaxX*2+offset-9 ):
            self.Window.addch( 0, i, ' ' )
            
        self.Window.addch( 0, 0, curses.ACS_LLCORNER )
        self.Window.addch( 0, Visettings.MaxX*2+offset-9, curses.ACS_LRCORNER )
        
        if Visettings.CurrentMode == VISMODE.PAUSE:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "PAUSED      " )
        elif Visettings.CurrentMode == VISMODE.PLAY:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "PLAYING     " )
        elif Visettings.CurrentMode == VISMODE.REWIND:
            self.Window.addstr( 0, Visettings.MaxX*2+offset-7, "REWINDING   " )
            
        blue = 0
        red = 0
        width = 93
        
        red = Visettings.Player1Plants
        blue = Visettings.Player2Plants
        
        size = Visettings.MaxX * Visettings.MaxY

        rPercent = float(red)/size
        bPercent = float(blue)/size
        gPercent = float(1 - rPercent - bPercent)

        line = 2

        self.Window.attrset( curses.color_pair( Legend.PLAYER_1_PIECE_COLOR ) )
        self.Window.attron( curses.A_BOLD )
        self.Window.addch( 1, 1, curses.ACS_LLCORNER )
        self.Window.attrset( curses.color_pair( Legend.PLAYER_2_PIECE_COLOR ) )
        self.Window.attron( curses.A_BOLD )
        self.Window.addch( 1, 95, curses.ACS_LRCORNER )

        for i in range(0, width):
            if i+1 < rPercent*width:
                self.Window.attrset( curses.color_pair( Legend.PLAYER_1_PIECE_COLOR ) )
            elif i < (rPercent+gPercent)*width:
                self.Window.attrset( curses.color_pair( Legend.BACKGROUND_COLOR ) )
            else:
                self.Window.attrset( curses.color_pair( Legend.PLAYER_2_PIECE_COLOR ) )
            self.Window.attron( curses.A_BOLD )

            if i == width/2:
                self.Window.addch( 1, 2+i, '|' )
            else:
                self.Window.addch( 1, 2+i, curses.ACS_HLINE )

        self.Window.attroff( curses.A_BOLD )


        
        self.Window.refresh()
        Visettings.Screen.refresh()
예제 #13
0
파일: main.py 프로젝트: moe221/Chess_game
screen = t.Screen()
screen.title('Chess Game')
screen.setup(width=1300, height=835)  # og 835, 835
# add all icons to screen
for image in [
        'BB', 'KB', 'KnB', 'KnW', 'KW', 'PB', 'PW', 'QB', 'RB', 'RW', 'BW',
        'QW'
]:
    screen.addshape(f'Images/{image}.gif')

# turn animation off
screen.tracer(0)
screen.listen()

# setup Chess board
gameboard = Gameboard()
screen.update()

# setup players
player1 = Player(color='white')
player1.player_turn = True
player2 = Player(color='black')

for piece in gameboard.pieces_list:
    if piece.player == 'white':
        player1.player_pieces.append(piece)
    else:
        player2.player_pieces.append(piece)

# to highlight selected piece
for positions in gameboard.positions:
예제 #14
0
 def handle_MDF(self, MDF_msg):
     self.map = Gameboard(self.power, MDF_msg)
     self.send_dcsp(YES(MAP(self.variant)))
예제 #15
0
파일: launcher_GUI.py 프로젝트: Tolkatos/P3
class GUIApplication:
    """Class qui gère l'execution du jeux."""
    def __init__(self, config_file, nbr_total_item):
        """Constructeur.

        Argument(2):
        config_file : structure du labyrinthe
        nbr_total_item : nombre total d'objet présent dans la structure"""

        pygame.init()
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_WIDTH))
        pygame.display.set_caption("P3 : labyrinthe")
        font = pygame.font.Font(None, 64)
        self.text_victoire = font.render("Victoire !", 1, (0, 255, 0))
        self.text_defeat = font.render("Défaite !", 1, (255, 0, 0))
        self.level = Gameboard(config_file, nbr_total_item)
        self.character = Character(self.level)
        self.keeper = Keeper()
        i = 0
        while i < nbr_total_item:
            self.item = Item(self.level.gameboard)
            self.level.gameboard[self.item.pos_y][self.item.pos_x] = "I"
            i += 1

    def event_keyboard(self):
        """Methode qui lit l'entrée clavier"""

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    return "z"
                if event.key == pygame.K_DOWN:
                    return "s"
                if event.key == pygame.K_RIGHT:
                    return "d"
                if event.key == pygame.K_LEFT:
                    return "q"
            elif event.type == pygame.QUIT:
                sys.exit()

    def display_GUI(self, img):
        """Methoque qui affiche le gameboard de manière graphique

        Paramètre(1):
        img = dictionnaire contenant les images"""

        for pos_y in range(NBR_LIGNE):
            for pos_x in range(NBR_SPRITE):
                if self.level.is_a_floor(pos_x, pos_y):
                    self.window.blit(
                        img[0], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                elif self.level.is_a_wall(pos_x, pos_y):
                    self.window.blit(
                        img[1], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                elif self.level.is_a_item(pos_x, pos_y):
                    self.window.blit(
                        img[0], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                    self.window.blit(
                        img["I"], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                elif self.level.is_a_keeper(pos_x, pos_y):
                    self.window.blit(
                        img[0], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                    self.window.blit(
                        img["G"], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                elif self.level.is_a_character(pos_x, pos_y):
                    self.window.blit(
                        img[0], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
                    self.window.blit(
                        img["M"], (pos_y * SPRITE_SIZE, pos_x * SPRITE_SIZE))
        pygame.display.flip()

    def run(self, img):
        """Methode qui gère l'execution du programme

        Paramètre(1):
        img : dictionnaire contenant les images"""

        while self.character.check_item(self.keeper):
            move = self.event_keyboard()
            self.character.move(move)
            self.display_GUI(img)
예제 #16
0
 def fill_row_no(gb : gameboard.Gameboard, row_no : int):
     for i in range(config.BOARD_FIRST_COLUMN, config.BOARD_LAST_COLUMN+1):
         gb.fields[row_no][i] = config.FALLEN_BLOCK
예제 #17
0
                           ymin=position[0][0] + 0.5,
                           ymax=position[1][0] + 0.5,
                           linestyles='dashed',
                           color='red')
            else:
                plt.hlines(position[0][0] + 0.5,
                           xmin=position[0][1] + 0.5,
                           xmax=position[1][1] + 0.5,
                           linestyles='dashed',
                           color='red')

        plt.show()
        return


if __name__ == '__main__':
    gameboard = Gameboard()
    gameboard.add_random_ship(length=5)
    gameboard.add_random_ship(length=3)
    gameboard.add_random_ship(length=5)
    gameboard.add_random_ship(length=3)
    gameboard.add_random_ship(length=3)
    gameboard.add_random_ship(length=3)
    gameboard.add_random_ship(length=3)
    for ship in gameboard.ships:
        print(str(ship))
    while len(gameboard.ships) > 0:
        ship = gameboard.ships[0]
        for cell in ship.position:
            gameboard.hit(cell)
예제 #18
0
"""running this file starts a game of StarFight and loads in savegame.txt"""

#first check whether pygame is installed, and if not, it gets installed
#DELETE THIS PART if you don't want to waste time and you have pygame installed
from pygame_installer2 import install
install()

from gameboard import Gameboard

RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (255, 0, 255)
CYAN = (0, 255, 255)

#initialize a gameboard with some random input and load in the savegame.txt straight away
gameboard = Gameboard(['Kristof', 'The Evil Enemy'], [RED, BLUE])
gameboard.buttons[0].want_maintenance = False
gameboard.buttons[-1].command()
#start pygame window:
#gameboard.start()
gameboard.buttons[-1].reload_game()
예제 #19
0
파일: loops.py 프로젝트: lewismazzei/Fusion
def openGameSave(username):
	with open('/home/lewis/Documents/School/Fusion/External Files/Game Saves/{}.pickle'.format(username), 'rb') as file: #open the relevant 'game save' file
		username, state, level, tiles, score = pickle.load(file) #load all the gameboard attributes into corresponding variables...
		return Gameboard(username, state, level, tiles, score) #...so that we can then return the gameboard with the attributes it had when the user left the game
def main():
    #游戏板对象
    gameboard = Gameboard()

    #提示输入信息
    while True:

        print("please select character: 0 - AI  1 - human ")
        print("format: 0 1 or 1 0 or 1 1 or 0 0")  #按照输入格式顺序
        print("(The input order represents the order of the chess)")
        input1 = input()
        input2 = input1.split()  #处理输入格式
        n1 = int(input2[0])
        n2 = int(input2[1])
        #人类与人类pk
        if n1 == 1 and n2 == 1:
            player1 = Human('X', gameboard)
            player2 = Human('O', gameboard)
            break
        else:
            #先手AI,后手人类
            if n1 == 0 and n2 == 1:
                player1 = AI('X', gameboard)
                player2 = Human('O', gameboard)
                break
            #先手人类,后手AI
            elif n1 == 1 and n2 == 0:
                player1 = Human('X', gameboard)
                player2 = AI('O', gameboard)
                break
            #AI与AIpk
            elif n1 == 0 and n2 == 0:
                player1 = AI('X', gameboard)
                player2 = AI2('O', gameboard)
                # player1 = AI2('X', gameboard)
                # player2 = AI('O', gameboard)
                break
            else:
                #格式错误,重新输入
                print("The format is wrong")

    print("Game start!")
    gameboard.print_state()  #输出初始状态
    current_player = player1  #当前玩家
    id = 0
    while True:

        next_step = current_player.decision_making()  #当前玩家做出决策
        #如果没有选择,则只能等待其他玩家下子
        if next_step is None:
            print(
                "                              No step to select,pass!!!!!!!!!"
            )
            print('-----------')
            print('-----------')
        else:
            print_step = (next_step[0] + 1, next_step[1] + 1)  #下子位置
            print("move step: ", print_step)  #输出下子位置
            gameboard.move(current_player.mark, next_step)  #下子
            # gameboard.print_state()
            x_count, o_count, empty_count = gameboard.count_num()
            print('X:', x_count, ' O:', o_count, ' Empty:', empty_count)
            if current_player.id == 0:
                print('score: ', current_player.evaluation_Comprehensive())
            gameboard.print_state_ts(current_player.anti_mark)  #输出下子后的棋盘状态
        #判断游戏是否结束
        if gameboard.is_over():
            break
        #切换状态
        if id == 0:
            current_player = player2
            id = (id + 1) % 2
        else:
            current_player = player1
            id = (id + 1) % 2

    print("Game Over!!!")
    result = gameboard.winner()  #得出结局
    #先手胜利
    if result == 0:
        print("Player1 Win!!!")
    #平局
    elif result == 1:
        print("Draw!!!")
    #后手胜利
    else:
        print("Player2 Win!!!")

    x_count, o_count, empty_count = gameboard.count_num()
    print('X:', x_count, ' O:', o_count, ' Empty:', empty_count)
예제 #21
0
def play_pong():

    right_paddle = Paddle(position=(350, 0), screen_width=600)
    left_paddle = Paddle(position=(-350, 0), screen_width=600)
    ball = Ball()
    scoreboard = Scoreboard()
    gameboard = Gameboard()

    screen.listen()

    screen.onkey(right_paddle.up, "Up")
    screen.onkey(right_paddle.down, "Down")
    screen.onkey(left_paddle.up, "w")
    screen.onkey(left_paddle.down, 's')

    gameboard.centerline()
    game_is_on = True
    while game_is_on:

        gameboard.players()
        point_scored = False
        ball.reset_position()
        screen.update()
        # delays the movement of new ball
        time.sleep(0.5)
        while not point_scored:
            screen.update()
            ball.move()
            time.sleep(ball.move_speed)
            # when the ball reaches either of these y-coordinates,
            # wall_bounce() changes the sign in front of self.move_y
            if ball.ycor() > 280 or ball.ycor() < -280:
                ball.wall_bounce()

            # Because of the stretched nature of the paddle, using ball.distance(paddle) alone will not work.
            # This is because the distance is measured from the center of each object.
            # the ends of the paddles will be further away
            # Therefore I had to check for a max xcor() being reached first. Followed by a larger distance of 50px
            if 310 < ball.xcor() < 330 or -310 > ball.xcor() > -330:
                print(ball.xcor())
                if ball.distance(right_paddle) < 80 or ball.distance(
                        left_paddle) < 80:
                    print("in contact")
                    ball.paddle_bounce()

            if ball.xcor() > 400:
                point_scored = True
                scoreboard.player_1_point()
                if scoreboard.player_1 == 5:
                    scoreboard.update_score()
                    game_is_on = False
                    gameboard.clear()
                    scoreboard.game_over()
            elif ball.xcor() < -400:
                point_scored = True
                scoreboard.player_2_point()
                if scoreboard.player_2 == 5:
                    scoreboard.update_score()
                    game_is_on = False
                    gameboard.clear()
                    scoreboard.game_over()
예제 #22
0
    def __init__(self):
        #initialize the players
        print("Player 1 - Please enter your name")
        name1 = input()
        print()
        print("Player 2 - Please enter your name")
        name2 = input()
        print()
        self.player1, self.player2 = Player(name1), Player(name2)
        while True:
            print("Please enter the size of the game grid. From 4 to 12")
            grid_size = input()
            if grid_size.isdigit() != True or int(grid_size) not in range(
                    4, 12):
                print()
                print("Invalid size")
                continue
            else:
                break

        gameboard = Gameboard(grid_size)

        while True:
            if gameboard.win():
                last_turn = gameboard.game_turn() - 1
                if last_turn % 2 != 0:
                    print(f"{self.player1.name} wins!")
                else:
                    print(f"{self.player2.name} wins!")
                break

            if gameboard.game_turn() % 2 != 0:
                gameboard.display_own_board(self.player1.name)
                gameboard.display_opponent_board()
                print(f"{self.player1.name} take your turn")
                move = self.player1.place_mark()
                gameboard.place_mark(move, self.player1.name)

            else:
                gameboard.display_own_board(self.player2.name)
                gameboard.display_opponent_board()
                print(f"{self.player2.name} take your turn")
                move = self.player2.place_mark()
                gameboard.place_mark(move, self.player2.name)
예제 #23
0
    def __init__(self, board_dimension, perform_experiments, tourney_rounds,
                 human_playing):
        # Set global parameters
        self.board_dimension = board_dimension
        self.perform_experiments = perform_experiments
        self.tourney_rounds = tourney_rounds

        # Create our bots
        self.bot1 = bot('rnd', 'random', self.board_dimension)

        self.bot2 = bot('ab3R',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=3,
                        use_dijkstra=False,
                        use_tt=False,
                        id_time_limit=0)
        self.bot3 = bot('ab3D',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=3,
                        use_dijkstra=True,
                        use_tt=False,
                        id_time_limit=0)
        self.bot4 = bot('ab4D',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=False,
                        id_time_limit=0)

        self.bot6 = bot('ab4D_TT',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=0)

        self.bot7 = bot('ab_TT_ID1',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=1)
        self.bot8 = bot('ab_TT_ID5',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=5)
        self.bot9 = bot('ab_TT_ID10',
                        'alphabeta',
                        self.board_dimension,
                        search_depth=4,
                        use_dijkstra=True,
                        use_tt=True,
                        id_time_limit=10)

        self.bot10 = bot('mcts500',
                         'mcts',
                         self.board_dimension,
                         iterations=500)
        self.bot11 = bot('mcts1k',
                         'mcts',
                         self.board_dimension,
                         iterations=1000)
        self.bot12 = bot('mcts5k',
                         'mcts',
                         self.board_dimension,
                         iterations=5000)
        self.bot13 = bot('mcts10k',
                         'mcts',
                         self.board_dimension,
                         iterations=10000)

        self.bot14 = bot('mctsinf_T1',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=1)
        self.bot15 = bot('mctsinf_T5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=5)
        self.bot16 = bot('mctsinf_T10',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         mcts_time_limit=10)

        self.bot17 = bot('mctsinf_T1_C0.1',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.1,
                         mcts_time_limit=1)
        self.bot18 = bot('mctsinf_T1_C0.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.5,
                         mcts_time_limit=1)
        self.bot19 = bot('mctsinf_T1_C1.0',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=1,
                         mcts_time_limit=1)
        self.bot20 = bot('mctsinf_T1_C1.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=1.5,
                         mcts_time_limit=1)

        self.bot21 = bot('ab4D_TT_ID10',
                         'alphabeta',
                         self.board_dimension,
                         search_depth=4,
                         use_dijkstra=True,
                         use_tt=True,
                         id_time_limit=10)
        self.bot22 = bot('mctsinf_T10_C0.5',
                         'mcts',
                         self.board_dimension,
                         iterations=1000000,
                         c_param=0.5,
                         mcts_time_limit=10)

        # Experiments
        self.ex1 = [self.bot2, self.bot3, self.bot4]
        self.ex2 = [self.bot4, self.bot6]
        self.ex3 = [self.bot7, self.bot8, self.bot9]
        self.ex4 = [self.bot10, self.bot11, self.bot12, self.bot13]
        self.ex5 = [self.bot14, self.bot15, self.bot16]
        self.ex6 = [self.bot17, self.bot18, self.bot19, self.bot20]
        self.ex7 = [self.bot21, self.bot22]

        # Create a gameboard
        self.gameboard = Gameboard(board_dimension)
        self.board = self.gameboard.board

        # Allow the human to play against the given bot
        if human_playing:
            res = self.Play_human_match(self.bot1, self.board)

        # Choose to perform experiments
        if self.perform_experiments:
            self.Perform_experiments(self.board,
                                     self.ex1)  # Change the experiment here!

            print('End of experiments, shutting down.')
            exit(1)

        else:
            # Or just a few matches between two bots
            for _ in range(20):
                res = self.Play_single_bot_match(self.bot1, self.bot2,
                                                 self.board)
                print("Player " + str(res) + " won")
예제 #24
0
import time
import threading

from gameboard import Gameboard
from terminal_renderer import TerminalRenderer
from keyboard_input import KeyboardInput
from player_manager import PlayerManager
from game_manager import GameManager

gboard = Gameboard()
renderer = TerminalRenderer(gboard)
inputer = KeyboardInput()
player = PlayerManager(gboard)
game = GameManager(gboard)

inputer.start()
game.start()


def game_loop():
    for i in range(25):
        nput = inputer.get_input()
        player.update(nput)
        game.update()
        renderer.render()
        time.sleep(.05)  # TODO: Calculate exact sleep time


thread = threading.Thread(target=game_loop)
thread.start()
thread.join()
예제 #25
0
def openGameSave(username):
    with open(
            '/home/lewis/Documents/School/Computing Project/External Files/Game Saves/{}.pickle'
            .format(username), 'rb') as file:
        username, state, level, tiles, score = pickle.load(file)
        return Gameboard(username, state, level, tiles, score)
예제 #26
0
class BaseClient():
    def __init__(self, host='127.0.0.1', port=16713):
        self.host = host
        self.port = port
        self.sock = None
        self.connected = False
        self.name = 'BaseClient'
        self.version = '1.0'
        self.map = None
        self.power = None
        self.passcode = None
        self.variant = None
        self.press = 0

    def connect(self):
        '''
        Opens a socket connection to the DAIDE server
        '''
        server_address = (self.host, self.port)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.sock.connect(server_address)
            self.connected = True
        except Exception:
            print("Unable to connect.\n")
            self.sock.close()
            self.connected = False

    def close(self):
        '''
        Closes socket connection to the DAIDE server
        '''
        self.sock.close()
        self.connected = False

    def get_header(self):
        '''
        Attempts to receive the header of a Diplomacy message
        from the server. Returns a tuple of the message type and
        message length.
        '''
        if (self.connected):
            header = self.sock.recv(4)
            (msg_type, msg_len) = struct.unpack('!bxh', header)
            return (msg_type, msg_len)
        else:
            raise Exception("Not connected to server.")

    def recv_msg(self):
        '''
        Attempts to receive a Diplomacy message from the server.
        Returns a tuple of the message type, message length,
        and actual message.
        '''
        try:
            (msg_type, msg_len) = self.get_header()
            bufsize = 1024
            bytes_recvd = 0
            msg = []

            while (bytes_recvd < msg_len):
                chunk = self.sock.recv(min(msg_len - bytes_recvd, bufsize))
                if chunk == b'':
                    raise RuntimeError("socket connection broken")
                msg.append(chunk)
                bytes_recvd = bytes_recvd + len(chunk)

            if msg:
                return (msg_type, msg_len, b''.join(msg))

        except Exception as e:
            print(e)
            self.connected = False
            self.sock.close()

    def write(self, message, msg_type):
        byte_length = len(message)
        header = struct.pack('!bxh', msg_type, byte_length)
        message = header + message
        if self.sock:
            self.sock.send(message)
        else:
            raise RuntimeError("socket connection broken")

    def send_FM(self):
        self.write(0, 3)

    def send_dcsp(self, msg):
        self.write(msg.pack(), 2)

    def send_OBS(self):
        self.send_dcsp(+OBS)

    def send_NME(self):
        self.send_dcsp(NME(self.name)(self.version))

    def send_IAM(self):
        if self.power and self.passcode:
            self.send_dcsp(IAM(self.power)(self.passcode))

    def send_initial_msg(self):
        msg = struct.pack('!HH', 1, 0xDA10)
        self.write(msg, 0)

    def register(self):
        if not self.connected:
            self.connect()
        self.send_initial_msg()
        self.send_NME()

    def play(self):
        self.register()
        while self.connected:
            msg = self.recv_msg()
            if msg:
                self.print_incoming_message(msg)
                self.handle_incoming_message(msg)

    def request_MAP(self):
        self.send_dcsp(+MAP)

    def reply_YES(self, msg):
        self.send_dcsp(YES(msg))

    def reply_REJ(self, msg):
        self.send_dcsp(REJ(msg))

    def handle_incoming_message(self, msg):
        msg_type, msg_len, message = msg

        if (msg_type == util.RM):
            self.handle_representation_message(message)
        elif (msg_type == util.DM):
            self.handle_diplomacy_message(message)
        elif (msg_type == util.EM):
            self.handle_error_message(message)

    def print_incoming_message(self, msg):
        msg_type, msg_len, message = msg
        message = Message.translate_from_bytes(message)
        print(message)

    def handle_diplomacy_message(self, msg):
        msg = Message.translate_from_bytes(msg)
        method_name = 'handle_' + str(msg[0])
        if msg[0] in (YES, REJ):
            method_name += '_' + str(msg[2])
        method = getattr(self, method_name, None)
        if method:
            return method(msg)

    def handle_representation_message(self, msg):
        raise NotImplementedError

    def handle_error_message(self, msg):
        raise NotImplementedError

    def handle_MDF(self, MDF_msg):
        self.map = Gameboard(self.power, MDF_msg)
        self.send_dcsp(YES(MAP(self.variant)))

    def handle_MAP(self, msg):
        map_name = msg.fold()[1][0]
        self.variant = map_name
        if self.map is None:
            self.send_dcsp(+MDF)
        elif (map_name == 'STANDARD'):
            self.reply_YES(msg)

    def handle_HLO(self, msg):
        # TODO: right now very basic handling of variant options
        folded_HLO = msg.fold()
        self.power = folded_HLO[1][0]
        self.map.power_played = self.power
        self.passcode = folded_HLO[2][0]
        self.press = folded_HLO[3][0][1]

    def handle_SCO(self, msg):
        self.map.process_SCO(msg)

    def handle_NOW(self, msg):
        self.map.process_NOW(msg)
        if self.map.missing_orders():
            self.generate_orders()
        self.submit_orders()

    def handle_ORD(self, msg):
        self.map.process_ORD(msg)

    # End of game
    def handle_OFF(self, msg):
        self.close()

    def handle_SLO(self, msg):
        self.close()

    def handle_DRW(self, msg):
        self.close()

    def handle_SMR(self, msg):
        self.close()

    def generate_orders(self):
        raise NotImplementedError

    def submit_orders(self):
        '''
        Submit orders to the server. The Message takes the form of
        'SUB (order) (order) ...'
        See section 3 of the DAIDE syntax document for more details.
        '''
        orders = self.map.get_orders()
        if orders != Message():
            self.send_dcsp(+SUB + orders)