コード例 #1
0
    def setUp(self):

        print(
            "################ Testing Class Initialization ###################"
        )

        self.env = Game()

        print(
            "################             Passed           ###################"
        )
コード例 #2
0
def main():
    """Main script.
    """

    # Use Agg backend for matplotlib. Why?
    matplotlib.use('Agg')

    # Load in parameters
    params = PARAMS.copy()

    # Calculate dimension of the strategy arrays
    params['DIMENSION'] = (100 / params['GRANULARITY'] + 1)

    # Calculate the value of a single unit of a strategy based on uniform dist.
    params['UNIT_VALUE'] = 1.0 / (params['DIMENSION'] ** 2)

    params['NUMBER_OF_TEAMS'] = len(params['TEAM_SPEC'])

    # Initialize game
    game = Game(**params)

    # Initialize plot
    fig, axarr, img, cbar = initialize_figure(game, **params)

    # MAIN LOOP
    for round_number in range(params['ROUNDS']):
        game.calc_scores(**params)

        game.update_data(round_number, **params)

        print "*******************************"
        print "round_number:", round_number

        for team in game.teams:
            print team.stats.loc[round_number]

        print "*******************************"

        fig, axarr, img, cbar = update_figures(fig, axarr, img, cbar, game, 
                                               round_number, **params)

        filename = params['SIM_NAME'] + "%04d.png" % round_number
        fig.savefig(os.path.join("output", "tmp", filename), dpi=120)

    remove_file(os.path.join("output", "videos", params["SIM_NAME"] + ".mp4"))

    create_video_from_frames(params['SIM_NAME'])

    clear_directory(os.path.join("output", "tmp"))
コード例 #3
0
async def create_game(game: Game):
    game = Game()
    query = f"INSERT INTO game_tests VALUES {game._id}, {game.game_name}, {game.evaluation}"
    connection.autocommit = True
    cursor = connection.cursor()
    cursor.execute(query)
    return {"game_id": Game.id}
コード例 #4
0
def main():
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.init()
    # Set the width and height of the screen [width, height]
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    #Set the title of the window:
    pygame.display.set_caption("Adventure in the sky")
    #Set the mouse invisible.
    pygame.mouse.set_visible(False)
    #Loop until the user clicks the close button.
    done = False
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    try:
        game = Game(screen)  #Create Game Object;
    except pygame.error:
        done = True
    # -------- Main Program Loop -----------
    while not done:
        done = game.eventHandler()
        # Game logic
        game.run_logic()

        # --- Drawing code should go here
        game.displayFrame(screen)
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
        # --- Limit to 30 frames per second
        clock.tick(30)
    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
コード例 #5
0
def main():

    pygame.init()

    # -- Set up game window --
    screen = pygame.display.set_mode([SCR_WIDTH, SCR_HEIGHT])
    pygame.display.set_caption("Aprendiz De Mecânico (demo)")

    # -- Used to set the frame rate --
    clock = pygame.time.Clock()

    # -- Used to maintain/break the main loop --
    done = False

    game = Game()

    # -- Main loop --
    while not done:
        done = game.process_events()

        game.run_logic()

        game.draw_frame(screen)

        clock.tick(60)
        pygame.display.set_caption('Aprendiz De Mecânico (demo): {}fps'.format(
            clock.get_fps()))

    pygame.quit()
コード例 #6
0
ファイル: main.py プロジェクト: edward344/alien_adventure
def main():
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.init()
    # Set the width and height of the screen [width, height]
    screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
    #Set the title of the window:
    pygame.display.set_caption("Alien Adventure")
    #Set the mouse invisible.
    pygame.mouse.set_visible(False)
    #Loop until the user clicks the close button.
    done = False
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    try:
        game = Game(screen) #Create Game Object;
    except pygame.error:
        done = True
    # -------- Main Program Loop -----------
    while not done:
        done = game.eventHandler()
        # Game logic
        game.run_logic()
        # --- Drawing code should go here
        game.displayFrame(screen)
        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()
        # --- Limit to 30 frames per second
        clock.tick(30)
    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
コード例 #7
0
def main():
    """Main script.
    """

    # Use Agg backend for matplotlib. Why?
    matplotlib.use('Agg')

    # Load in parameters
    params = PARAMS.copy()

    # Calculate dimension of the strategy arrays
    params['DIMENSION'] = (100 / params['GRANULARITY'] + 1)

    # Calculate the value of a single unit of a strategy based on uniform dist.
    params['UNIT_VALUE'] = 1.0 / (params['DIMENSION']**2)

    params['NUMBER_OF_TEAMS'] = len(params['TEAM_SPEC'])

    # Initialize game
    game = Game(**params)

    # Initialize plot
    fig, axarr, img, cbar = initialize_figure(game, **params)

    # MAIN LOOP
    for round_number in range(params['ROUNDS']):
        game.calc_scores(**params)

        game.update_data(round_number, **params)

        print "*******************************"
        print "round_number:", round_number

        for team in game.teams:
            print team.stats.loc[round_number]

        print "*******************************"

        fig, axarr, img, cbar = update_figures(fig, axarr, img, cbar, game,
                                               round_number, **params)

        filename = params['SIM_NAME'] + "%04d.png" % round_number
        fig.savefig(os.path.join("output", "tmp", filename), dpi=120)

    remove_file(os.path.join("output", "videos", params["SIM_NAME"] + ".mp4"))

    create_video_from_frames(params['SIM_NAME'])

    clear_directory(os.path.join("output", "tmp"))
コード例 #8
0
class TestGameOfLife(unittest.TestCase):
    def setUp(self):

        print(
            "################ Testing Class Initialization ###################"
        )

        self.env = Game()

        print(
            "################             Passed           ###################"
        )

    def test_default_board_dimensions(self):

        print(
            "################   Testing Board Dimensions   ###################"
        )

        self.assertEqual(self.env.width, 40)
        self.assertEqual(self.env.height, 30)

        print(
            "################             Passed           ###################"
        )

    def test_get_neighbours(self):

        print(
            "############### Testing Neighbour Call Function ###################"
        )

        self.assertEqual(
            self.env.get_neighbours(2, 2),
            [[1, 1], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [3, 3]])
        self.assertEqual(self.env.get_neighbours(0, 0),
                         [[0, 1], [1, 0], [1, 1]])
        self.assertEqual(self.env.get_neighbours(44, 0), [])

        print(
            "###############             Passed           ###################")

    def test_update_board(self):

        print(
            "############### Testing Update Board Function ###################"
        )

        for i in range(3):
            for j in range(3):
                self.env.board[i][j] = self.env.patterns["LWSpaceship"][i][j]
        self.env.update_board()
        self.assertEqual(self.env.board[0][1], 1)
        self.assertEqual(self.env.board[2][1], 0)
        self.assertEqual(self.env.board[2][0], 1)

        print(
            "###############             Passed           ###################")

    def test_key_pressed(self):

        print("############### Testing Key Presses ###################")

        self.assertEqual(self.env.patterns[self.env.menu[ord('2')]],
                         [[1, 1, 1], [1, 0, 1], [1, 1, 1], [1, 1, 1],
                          [1, 1, 1], [1, 1, 1], [1, 0, 1], [1, 1, 1]])

        print(
            "###############             Passed           ###################")
コード例 #9
0
LOWER_RIGHT = 9

MOVES_ARRAY = [
    TOP_LEFT, TOP_MIDDLE, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_MIDDLE, MIDDLE_RIGHT,
    LOWER_RIGHT, LOWER_MIDDLE, LOWER_LEFT
]

game_play = True
while game_play:
    player1 = input("player1:    ")
    player2 = input("player2:    ")

    guy1 = Player(player1, 1)
    guy2 = Player(player2, 2)
    winner = None
    new_game = Game(guy1, guy2)

    print('Instructions:')
    print('Each grid location is numbered.'
          'Please use those numbers to place your tictactoe')
    print('_1_|_2_|_3_')
    print('_4_|_5_|_6_')
    print(' 7 | 8 | 9 ')

    i = 0
    next_move_man = guy1
    while not new_game.someone_win(next_move_man) and \
            new_game.all_places_not_full():
        if i % 2 == 0:
            move = input(guy1.name + " makes a move:    ")
            if move.isdigit():
コード例 #10
0
from game_class import Game
from player_class import RandomPlayer
from player_class import CustomPlayer

players = [RandomPlayer(), CustomPlayer()]
game = Game(players)
game.state
{
    'turn': 1,
    'board_size': [7, 7],
    'players': {
        1: {
            'scout_coords': (4, 1),
            'home_colony_coords': (4, 1)
        },
        2: {
            'scout_coords': (4, 7),
            'home_colony_coords': (4, 7)
        }
    },
    'winner': None
}

game.complete_turn()
print(game.state)
'''{
    'turn': 2,
    'board_size': [7,7],
    'players': {
        1: {
            'scout_coords': (will vary),
コード例 #11
0
    player_two = None
    game = None  #główny obiekt programu, do którego wywysyłane są wszyskie dane z opcji, obiekty graczy, obiekty cpu, i którymi zarządza
    #endregion
    ##############################################################################################
    options = None
    run_game = True

    while run_game:

        options = main_menu.use_menu()

        if options == 1:
            options = new_game_menu.use_menu()
            game = Game(map_size.map_size, [
                four_masted_fleet_size.fleet_size,
                three_masted_fleet_size.fleet_size,
                two_masted_fleet_size.fleet_size,
                single_mast_fleet_size.fleet_size
            ])

            #region(gra jednoosobowa)
            if options == 11:
                pass
            #endregion

            #region(gra dwuosobowa)
            if options == 12:
                game.set_player_one()
                game.set_player_two()

                game.play_game()
                #game.TEST_method_show_about_yourself()
コード例 #12
0
ファイル: main.py プロジェクト: Nesmith-Charlesii/rpsls_proj
from game_class import Game

if __name__ == '__main__':
    play_game = Game()
    play_game.run_game()
コード例 #13
0
    def calculate(self):
        self.numbers1 = 48 + 1
        self.counter = 1
        insideLoopCounter = 0 #This is for every ticket, loop three times.
        # User buys a ticket 3 times a week, every week.
        if self.numb_of_qpick == 1: #One quick pick for every drawing.
            self.numb_of_weeks *= 3 #where 3 is the number that gopher five plays
                # everyweek times the total number of week in a the years entered.
            while self.counter <= self.numb_of_weeks:
                Game.userQPickFive(self)
                # Change the number in the perimeter between 1 and 5.
                Game.computerDrawingFives(self, 2)
                self.counter += 1

        # User buys a ticket that is good for 3 drawing (full week).
        elif self.numb_of_qpick == 2: #User buys quick pick once everyweek.
            self.numb_of_qpick = 3
            while self.counter <= self.numb_of_weeks:
                insideLoopCounter = 1
                Game.userQPickFive(self)
                while insideLoopCounter <= self.numb_of_qpick:
                    Game.computerDrawingFives(self, 2)
                    insideLoopCounter += 1
                self.counter += 1
        else:
            self.numb_of_qpick = 6
            while self.counter <= self.numb_of_weeks:
                insideLoopCounter = 1
                Game.userQPickFive(self)
                while insideLoopCounter <= self.numb_of_qpick:
                    Game.computerDrawingFives(self, 2)
                    insideLoopCounter += 2
                self.counter += 2
コード例 #14
0
 def calculate(self):
     self.numbers1 = 31 + 1 #When using range for loops the last number is not counted.
     self.counter = 1
     insideLoopCounter = 0
     if self.numb_of_qpick == 1:
         self.numb_of_weeks *= 7
         while self.counter <= self.numb_of_weeks:
             Game.userQPickFive(self)
             # Change the number in the perimeter between 1 and 5.
             Game.computerDrawingFives(self, 3)
             self.counter += 1
     # User decides to buy once every week and the ticket is good for 7 drawings.
     elif self.numb_of_qpick == 2:
         self.numb_of_qpick = 7
         while self.counter <= self.numb_of_weeks:
             insideLoopCounter = 1
             Game.userQPickFive(self)
             # Every week, we need to update the quick pick drawing for the user.
             while insideLoopCounter <= self.numb_of_qpick: # number of times North Star drawings.
                 Game.computerDrawingFives(self, 3)
                 insideLoopCounter += 1
             self.counter += 1
     # User selected one quick pick that is good for two weeks, or fourteen drawings.
     else:
         self.numb_of_qpick = 14
         while self.counter <= self.numb_of_weeks:
             insideLoopCounter = 1
             Game.userQPickFive(self)
             while insideLoopCounter <= self.numb_of_qpick:
                 Game.computerDrawingFives(self, 3)
                 insideLoopCounter += 1
             self.counter += 2
コード例 #15
0
            return int(players)
        else:
            print('Некорректный ввод')
            choose_players()

    def name_players():
        players_counter = choose_players()
        player_one = input('Введите имя первого игрока - ')

        if players_counter == 2:
            player_two = input('Введите имя второго игрока - ')
        else:
            player_two = None
        return {'player_one': player_one, 'player_two': player_two}

    def choose_difficult():
        difficult = input('Выберите сложность (1/2/3) - ')

        if check_options(difficult, [1, 2, 3]):
            return {'difficult': int(difficult)}
        else:
            print('Некорректный ввод')
            choose_difficult()

    return {**name_players(), **choose_difficult()}


# Инициализация игры и запуск
current_game = Game(**game_options())
current_game.start_game
コード例 #16
0
from game_class import Game

if __name__ == '__main__':

    env = Game()
    env.start_game()
コード例 #17
0
from game_class import Game
from player_class import RandomPlayer
from player_class import CustomPlayer

players = [CustomPlayer(), CustomPlayer()]
game = Game(players)
game.state['players']
{
    1: {
        'scout_coords': (4, 1),
        'home_colony_coords': (4, 1)
    },
    2: {
        'scout_coords': (4, 7),
        'home_colony_coords': (4, 7)
    }
}

game.complete_movement_phase()
assert game.state['players'] == {
    1: {
        'scout_coords': (4, 2),
        'home_colony_coords': (4, 1)
    },
    2: {
        'scout_coords': (4, 6),
        'home_colony_coords': (4, 7)
    }
}

assert game.complete_combat_phase(
コード例 #18
0
                break
            if sum(game.wins) > 0:
                break
        except:
            break

    print("Lost connection")
    try:
        del games[game_id]
        print("Closing Game", game_id)
    except:
        pass
    ID_COUNT -= 2
    conn_server.close()


while True:
    conn_s, addr = sock.accept()
    print(f"Connected to {addr}")
    ID_COUNT += 1
    PLAYER_NUMBER = 0
    GAME_ID = (ID_COUNT - 1) // 2
    if ID_COUNT % 2 == 1:
        games[GAME_ID] = Game(GAME_ID)
        print("Creating a new game...")
    else:
        games[GAME_ID].allset = True
        PLAYER_NUMBER = 1

    start_new_thread(threaded_client, (conn_s, PLAYER_NUMBER, GAME_ID))