Пример #1
0
def test_step():
    game = Game(wait_agent, wait_agent)
    game.step()

    players = game.players

    ships0 = players[0].ships
    ship_array0 = players[0].ship_array
    shipyards0 = players[0].shipyards
    shipyard_array0 = players[0].shipyard_array

    ships1 = players[1].ships
    ship_array1 = players[1].ship_array
    shipyards1 = players[1].shipyards
    shipyard_array1 = players[1].shipyard_array

    assert len(players) == 2
    assert len(ships0) == 1
    assert len(shipyards0) == 0
    assert len(ships1) == 1
    assert len(shipyards1) == 0

    s0 = ships0[0]
    assert s0.x == 5 and s0.y == 10
    assert ship_array0[10][5] == [s0]

    s1 = ships1[0]
    assert s1.x == 15 and s1.y == 10
    assert ship_array1[10][15] == [s1]
Пример #2
0
def main():
  config = Config(
    FPS,
    WIN_WIDTH,
    WIN_HEIGHT
  )

  game = Game(config)

  game.sprite_manager.register([
    SpriteConfig('bg', os.path.join(local_dir, "assets/bg.png"), [pygame.transform.scale2x]),
    SpriteConfig('bird1', os.path.join(local_dir, "assets/bird1.png"), [pygame.transform.scale2x]),
    SpriteConfig('bird2', os.path.join(local_dir, "assets/bird2.png"), [pygame.transform.scale2x]),
    SpriteConfig('bird3', os.path.join(local_dir, "assets/bird3.png"), [pygame.transform.scale2x]),
    SpriteConfig('base', os.path.join(local_dir, "assets/base.png"), [pygame.transform.scale2x]),
    SpriteConfig('pipe', os.path.join(local_dir, "assets/pipe.png"), [pygame.transform.scale2x]),
  ])

  background = Background(game.sprite_manager.get('bg'))
  birds = [
    Bird(230, 350, game.sprite_manager.get('bird1')),
    Bird(130, 350, game.sprite_manager.get('bird1')),
  ]

  game.state.add([background] + birds)

  game.start()
Пример #3
0
def test_get_full_game_representation_strategy():
    def game_representation_strategy(game):
        return Game.get_full_game_representation_strategy(game)

    snake_length = 3
    width = 8
    height = 8
    input_nodes = width * height + 4
    hidden_layer_nodes = [64]
    output_nodes = 3
    number_of_nn_weights = get_number_of_nn_weights(input_nodes,
                                                    hidden_layer_nodes,
                                                    output_nodes)
    weight_lower_threshold = -1
    weight_upper_threshold = 1

    sample_genotype = SimpleGenotype.get_random_genotype(
        number_of_nn_weights, weight_lower_threshold, weight_upper_threshold)
    sample_phenotype = Phenotype(sample_genotype.weights, input_nodes,
                                 hidden_layer_nodes, output_nodes)
    sample_game = Game(width, height, sample_phenotype, 777,
                       game_representation_strategy, snake_length)

    game_representation = Game.get_full_game_representation_strategy(
        sample_game)
    assert len(game_representation) == 8 * 8 + 4
    assert game_representation[36] == 1
    assert game_representation[44] == 1
    assert game_representation[52] == 1
Пример #4
0
def test_ship_collision2():

    game = Game(wait_agent, wait_agent)
    s1 = Ship(10, 11, game.players[0])
    s1.halite = 10
    s2 = Ship(10, 11, game.players[1])
    s2.halite = 20
    game.players[0].add_ship(s1)
    game.players[1].add_ship(s2)

    assert len(game.players[0].ships) == 2
    assert len(game.players[0].ship_array[11][10]) == 1

    assert len(game.players[1].ships) == 2
    assert len(game.players[1].ship_array[11][10]) == 1

    game.ship_collisions()

    assert len(game.players[0].ships) == 2
    assert len(game.players[0].ship_array[11][10]) == 1
    assert game.players[0].ship_array[11][10][0] == s1

    assert len(game.players[1].ships) == 1
    assert len(game.players[1].ship_array[11][10]) == 0

    assert s1.halite == 30
 def handle_player_action(self, player_id: str, action: PlayerAction,
                          game: Game, action_data: Dict[str, object]):
     super().handle_player_action(player_id, action, game, action_data)
     bid_value = action_data[constants.BID_VALUE]
     bidder_pos = game.get_next_bidder_pos()
     game.set_bidder_history(bidder_pos, bid_value)
     return self.find_and_set_next_bidder_pos_and_bid_value(
         game, bid_value, bidder_pos)
Пример #6
0
def test_shipyard_collision2():
    game = Game(wait_agent, wait_agent)

    sy = Shipyard(5, 10, game.players[1])
    game.players[1].add_shipyard(sy)

    game.shipyard_collisions()

    assert len(game.players[1].shipyards) == 0
    assert game.players[1].shipyard_array[10][5] == 0
Пример #7
0
    def __init__(self):
        Game.__init__(self, "Tron", [16, 16])
        self.fps = 20
        self.frameCounter = 0

        self.players = [
            Player([33, 150, 243], [int(self.size[0] * 1 / 5.0),
                                    int(self.size[1] / 2.0)], "RIGHT"),
            Player([76, 175, 80], [int(self.size[0] * 4 / 5.0),
                                   int(self.size[1] / 2.0)], "LEFT")]
        self.counter = self.fps * Tron.GROW_SECONDS
Пример #8
0
    def __init__(self):
        Game.__init__(self, "Snake", [16, 16])
        self.fps = 30
        self.death = False

        # Spieler erstellen
        self.player = []

        for i in range(3):
            self.player.append(Block(i, 0, [150, 0, 0]))

        # fruit erstellen
        self.food = Block(0, 0, [255, 255, 0])
Пример #9
0
    def __init__(self):
        Game.__init__(self, "Bird", [16, 16])

        self.fps = 30
        self.x = 0
        self.sky = Sky(BirdGame.SKY_DX)
        self.grass = Grass(BirdGame.GRASS_DX)
        self.state = "START"

        my_path = os.path.abspath(os.path.dirname(__file__))
        self.scorePath = os.path.join(my_path, "highscore.txt")

        self.initColors()
Пример #10
0
def test_collect():
    game = Game(wait_agent, wait_agent)

    s = game.players[0].ships[0]

    game.halite[10, 5] = 40

    assert game.players[0].halite == 5000

    s.collect()

    assert game.get_halite(5, 10) == 30
    assert s.halite == 10
    assert game.players[0].halite == 5000
Пример #11
0
    def test_white_chips(self):
        """Тестируем постановку белых фишек, и определения белых групп"""

        game = Game()
        self.move((450, 450), (6, 4), game, self.color_white)
        self.move((485, 450), (7, 4), game, self.color_white)
        self.move((520, 450), (8, 4), game, self.color_white)
        self.move((275, 275), (1, 9), game, self.color_white)
        self.move((555, 555), (9, 1), game, self.color_white)

        expected_white_groups = [[(6, 4), (7, 4), (8, 4)], [(1, 9)], [(9, 1)]]
        actual_white_groups = game.get_white_groups()

        self.assertEqual(actual_white_groups, expected_white_groups)
Пример #12
0
    def __init__(self):
        Game.__init__(self, "Test", [16, 16])
        self.fps = 7

        try:
            import RPi.GPIO as gpio
            pygame.display.set_mode([16, 16])
            self.ref = "/home/pi/Documents/pixelGames/games/anim/gifs"

        except ImportError:
            script_path = os.path.dirname(os.path.realpath(__file__))
            self.ref = os.path.join(script_path, "gifs")

        self.switchTime = 20
        self.sheets = []
Пример #13
0
def test_convert3():
    game = Game(wait_agent, wait_agent)
    s = game.players[0].ships[0]

    game.players[0].halite = 499

    assert s.halite == 0

    s.convert()

    assert game.players[0].halite == 499

    players = game.players

    ships0 = players[0].ships
    ship_array0 = players[0].ship_array
    shipyards0 = players[0].shipyards
    shipyard_array0 = players[0].shipyard_array

    ships1 = players[1].ships
    ship_array1 = players[1].ship_array
    shipyards1 = players[1].shipyards
    shipyard_array1 = players[1].shipyard_array

    assert len(ships0) == 1
    assert len(ships1) == 1

    assert ship_array0[10][5] != []
    assert ship_array1[10][15] != []

    assert len(shipyards0) == 0
    assert len(shipyards1) == 0

    assert shipyard_array0[10][5] == 0
    assert shipyard_array1[10][15] == 0
Пример #14
0
 def reset(self):
     #Reset games
     self.games = [Game(None,None) for _ in range(self.batch_size)]
     self.game_length = self.games[0].length
     
     self.gradient_batch = [tf.zeros((2,self.batch_size,*w.shape),dtype=tf.float32) for w in self.vbm.parameters()]
     self.vbm.reset()
Пример #15
0
    def reset(self):
        #Reset games
        self.games = [Game(None,None) for _ in range(self.batch_size)]
        self.game_length = self.games[0].length

        self.loss_batch = [[0. for i in range(self.batch_size)] for k in range(2)]
        
        self.vbm.reset()
Пример #16
0
    def test_black_chips(self):
        """Тестируем постановку черных фишек, и определения черных групп"""

        game = Game()
        self.move((555, 310), (9, 8), game, self.color_black)
        self.move((520, 310), (8, 8), game, self.color_black)
        self.move((485, 310), (7, 8), game, self.color_black)
        self.move((450, 310), (6, 8), game, self.color_black)
        self.move((275, 555), (1, 1), game, self.color_black)
        self.move((310, 555), (2, 1), game, self.color_black)
        self.move((345, 555), (3, 1), game, self.color_black)

        expected_black_groups = [[(9, 8), (8, 8), (7, 8), (6, 8)],
                                 [(1, 1), (2, 1), (3, 1)]]
        actual_black_groups = game.get_black_groups()

        self.assertEqual(actual_black_groups, expected_black_groups)
Пример #17
0
def test_add_ship():
    game = Game(wait_agent, wait_agent)
    s = Ship(0, 0, game.players[0])

    game.players[0].add_ship(s)

    assert len(game.players[0].ships) == 2
    assert game.players[0].ship_array[0][0] != []
Пример #18
0
    def __init__(self, title, winWidth):
        # These class variables will be useful for positioning GUI
        self.winWidth = winWidth
        self.winHeight = self.winWidth * 9 // 16

        # initialize pygame
        pg.init()
        pg.font.init()
        pg.key.set_repeat(100, 100)

        pg.display.set_caption(title)
        self.window = pg.display.set_mode((self.winWidth, self.winHeight))
        self.window.fill((51, 51, 51))
        self.clock = pg.time.Clock()

        self.game = Game(self)
        self.running = True
Пример #19
0
def test_remove_ship():
    game = Game(wait_agent, wait_agent)
    s = game.players[0].ships[0]

    s.remove()

    assert len(game.players[0].ships) == 0
    assert game.players[0].ship_array[10][5] == []
Пример #20
0
def test_halite_regeneration():
    game = Game(wait_agent, wait_agent)

    game.set_halite(0, 0, 100)
    assert game.get_halite(0, 0) == 100

    game.halite_regeneration()

    assert game.get_halite(0, 0) == 102
    assert game.get_halite(0, 1) == 0
Пример #21
0
    def test_defender(self):
        """Тест защиты бота.
        Окружаем белую фишку тремя черными.
        Бот должен увеличить дыхания для данной фишки"""

        game = Game()
        self.move((380, 450), (4, 4), game, self.color_bot)

        self.move((345, 450), (3, 4), game, self.color)
        self.move((415, 450), (5, 4), game, self.color)
        self.move((380, 485), (4, 3), game, self.color)

        bot = SmartBot(game)
        response = bot.action()
        game.set_new_move()
        expected_white_groups = [[(4, 4), (4, 5)]]
        actual_white_groups = game.get_white_groups()
        self.assertEqual(actual_white_groups, expected_white_groups)
Пример #22
0
 def load_game():
     config = ConfigParser()
     config.read("./engine/data/config.ini")
     defaults = config["DEFAULT"]
     default_properties = {"FPS":defaults.getint("FPS")}
     window_settings = config["WINDOW SETTINGS"]
     window_properties = {"size":(window_settings.getint("width"),window_settings.getint("height")),
                          "caption":window_settings.get("title")}
     return Game(default_properties, window_properties)
Пример #23
0
    def reset(self):
        #Reset games

        self.games = [Game(*self.bots[i]) for i in range(self.batch_size)]
        self.game_length = self.games[0].length

        self.vbm.reset()

        self.rewards = np.zeros(self.batch_size)
Пример #24
0
    def test_attack(self):
        """Тест атаки бота.
        Заполняем доску четырмя фишками, отдаленных друг от друга.
        Такие фишки легко закрыть с помощью 16 ходов: 4 дыхания на каждую фишку"""

        game = Game()
        self.move((275, 275), (9, 9), game, self.color)
        self.move((555, 555), (9, 1), game, self.color)
        self.move((555, 380), (9, 6), game, self.color)
        self.move((380, 450), (4, 4), game, self.color)

        bot = SmartBot(game)
        for i in range(16):
            response = bot.action()
            game.set_new_move()
        expected_black_groups = []
        actual_black_groups = game.get_black_groups()
        self.assertEqual(actual_black_groups, expected_black_groups)
Пример #25
0
class Viewer:
    def __init__(self, bot1, bot2, vbm):
        self.game = Game(bot1, bot2)
        self.vbm = vbm

    def step(self):
        inp_sh_p0, inp_sy_p0, inp_sh_p1, inp_sy_p1 = get_nn_input(self.game)

        proba0 = self.game.players[0].agent.compute_actions_proba(
            (inp_sh_p0, inp_sy_p0))
        proba1 = self.game.players[1].agent.compute_actions_proba(
            (inp_sh_p1, inp_sy_p1))

        self.vbm.flush()

        actions_list0 = self.game.players[0].agent.sample_actions(proba0)
        actions0 = compute_action_dict(actions_list0, self.game.players[0])
        actions_list1 = self.game.players[1].agent.sample_actions(proba1)
        actions1 = compute_action_dict(actions_list1, self.game.players[1])

        self.game._step(actions0, actions1)

    def view(self):
        inp_sh_p0, inp_sy_p0, _, _ = get_nn_input(self.game)
        inp = tf.concat([inp_sh_p0, inp_sy_p0], axis=0)[0]
        for i in range(7):
            plt.subplot(self.game.length + 1, 7, self.game.nb_step * 7 + i + 1)
            if i == 0:
                plt.text(-10,
                         2,
                         str(self.game.players[0].halite)[:4] + "-" +
                         str(self.game.players[1].halite)[:4],
                         fontsize=10,
                         color='black')  #, backgroundcolor = 'white')
            plt.imshow(inp[:, :, i])
            plt.xticks([])
            plt.yticks([])

    def play(self):
        self.view()
        for i in range(self.game.length):
            self.step()
            self.view()
        plt.show()
Пример #26
0
def test_game_max_points_threshold():
    def game_representation_strategy(game):
        return Game.get_full_game_representation_strategy(game)

    snake_length = 5
    width = 32
    height = 18
    snack_eaten_points = 2

    input_nodes = width * height + 4
    hidden_layer_nodes = [64]
    output_nodes = 3
    number_of_nn_weights = get_number_of_nn_weights(input_nodes,
                                                    hidden_layer_nodes,
                                                    output_nodes)
    weight_lower_threshold = -1
    weight_upper_threshold = 1
    max_points_threshold = 200
    min_points_threshold = -10

    sample_genotype = SimpleGenotype.get_random_genotype(
        number_of_nn_weights, weight_lower_threshold, weight_upper_threshold)
    sample_phenotype = Phenotype(sample_genotype.weights, input_nodes,
                                 hidden_layer_nodes, output_nodes)

    sample_game = Game(width,
                       height,
                       sample_phenotype,
                       777,
                       game_representation_strategy,
                       snake_length,
                       snack_eaten_points,
                       max_points_threshold=max_points_threshold,
                       min_points_threshold=min_points_threshold)
    sample_game.score = 200

    next_game_state = Game.get_next_game(sample_game)
    assert next_game_state.status == GameStatus.ENDED

    next_game_state.score = -10
    next_game_state = Game.get_next_game(next_game_state)
    assert next_game_state.status == GameStatus.ENDED
Пример #27
0
    def test_smart_attack(self):
        """Тест умной атаки.
        Белые и Черные фишки имеют достаточно дыханий и стоят рядом (>=3).
        Это самая частая ситуация в ГО. В данной ситуации нужно атаковать-защищать"""

        game = Game()
        self.move((275, 275), (1, 9), game, self.color)
        self.move((275, 310), (1, 8), game, self.color)
        self.move((275, 345), (1, 7), game, self.color)
        self.move((275, 380), (1, 6), game, self.color)

        self.move((310, 310), (2, 8), game, self.color_bot)

        bot = SmartBot(game)
        response = bot.action()
        game.set_new_move()

        expected_white_groups = [[(2, 8), (2, 7)]]
        actual_white_groups = game.get_white_groups()
        self.assertEqual(actual_white_groups, expected_white_groups)
Пример #28
0
    def __init__(self, rewards=None, rounds_number=100, verbose=False):
        self.action_space = spaces.Discrete(3)
        self.observation_space = spaces.Tuple(
            (spaces.Discrete(3), spaces.Discrete(3),
             spaces.Box(0, 10, shape=(3, ))))

        self._game = Game(verbose=verbose)
        self._player1 = Player(self._game)
        self._player2 = Player(self._game)
        self._done = False
        self._rounds_number = rounds_number

        if rewards is None:
            rewards = dict(local=1, glob=0)

        self.rewards = rewards

        self._game.move(choice(FIELDS), choice(FIELDS))

        self.stats = {'games_played': 0}
Пример #29
0
    def __init__(self, code, game = None):
        self.data = json.loads(code)
        self.objects = {}
        self.events = {}
        self.battles = {}
        self.places = {}
        self.actions = {}

        if game is None:
            self.game = Game()
        else:
            self.game = game
Пример #30
0
def create_new_gamestate(user):

    # starting a new game for the player
    g = Game()

    g.start_new_day()

    pps = pickle.dumps(g.player_state)
    pus = pickle.dumps(g.update_state)
    ps = pickle.dumps(g.street)

    gamestate = g.game_state

    user_gamestate = GameState(user = user,
                        player_state = pps,
                        update_state = pus,
                        street_state = ps,
                        game_state = gamestate,
                        time_left = g.time_left)

    user_gamestate.save()
Пример #31
0
    def test_white_black_chips(self):
        """Тестируем постановку фишек обоих цветов, и определения обоих групп"""

        game = Game()
        self.move((345, 380), (3, 6), game, self.color_white)
        self.move((310, 380), (2, 6), game, self.color_white)
        self.move((275, 380), (1, 6), game, self.color_white)
        self.move((380, 555), (4, 1), game, self.color_white)
        self.move((415, 555), (5, 1), game, self.color_white)

        self.move((380, 310), (4, 8), game, self.color_black)
        self.move((380, 310), (4, 8), game, self.color_black)
        self.move((310, 310), (2, 8), game, self.color_black)
        self.move((275, 310), (1, 8), game, self.color_black)

        expected_black_groups = [[(4, 8)], [(2, 8), (1, 8)]]
        actual_white_groups = game.get_white_groups()
        actual_black_groups = game.get_black_groups()
        expected_white_groups = [[(3, 6), (2, 6), (1, 6)], [(4, 1), (5, 1)]]
        self.assertEqual(actual_black_groups, expected_black_groups)
        self.assertEqual(actual_white_groups, expected_white_groups)
Пример #32
0
def load_game(state_data):
    g = Game()

    g.player_state = pickle.loads(state_data.player_state)
    g.update_state = pickle.loads(state_data.update_state)
    g.street = pickle.loads(state_data.street_state)
    g.game_state = state_data.game_state
    g.update_time_left(100-(int(state_data.time_left)))

    return g
Пример #33
0
def play(request):

	#Get the current user profile
    up = UserProfile.objects.get(user= User.objects.get(username = request.user))
	
	#If the user is resuming a game
    if up.current_game != None:
	
		#Load the pickled game data
        g = pickle.loads(up.current_game)
		
		#If the player has died
        if g.is_game_over():
		
			#Return the game over screen
            context_dict = {'game_over':True}
            return render(request,'zombie/play.html',context_dict)
		
		#Else if the in-game day is over
        elif g.is_day_over():
		
			#Return the day over screen and begin a new day, saving the game data
            g.end_day()
            context_dict = {"end_of":g.player_state.days, 'player':g.player_state}
            g.start_new_day()
            _save(up,g)
            return render(request,'zombie/play.html',context_dict)
			
	#If the player is starting a new game
    else:
		#Initialise a new game instance and start it
        g = Game()
        g.start_new_day()
		
	#Get the current game status, save the game data and return it
    context_dict = fill_dict(g)
    _save(up,g)
    return render(request,'zombie/play.html',context_dict)
Пример #34
0
 def __init__(self,screen):
     Game.__init__(self)
     self.gui_game_end = False
     self.screen = screen
     self.surface = pygame.Surface(screen.get_size())
     self.clock = pygame.time.Clock()
     self.building_grid = []
     self.trading_house_grid = []
     self.ships_grid = []
     self.plantation_grid = []
     self.barrel_grid = []
     for row in range(3):
         for column in range(6):
             self.building_grid.append(pygame.Rect(25+(120+6)*column, 25+(65+6)*row,120,65))
     for column in range(6):
         self.building_grid.append(pygame.Rect(25+(120+6)*column, 25+(65+6)*3,120,136))
     for column in range(4):
         self.trading_house_grid.append(pygame.Rect(column*45+575,550,40,40))
     for column in range(3):
         self.ships_grid.append(pygame.Rect(column*45+575,480,40,40))
     for column in range(8):
         self.plantation_grid.append(pygame.Rect(column*(75+5)+25,502,75,75))
     for column in range(5):
         self.barrel_grid.append(pygame.Rect(130 +40*column,450,40,40))
Пример #35
0
 def game_end(self):
     return self.gui_game_end or Game.game_end(self)
Пример #36
0
def main_menu(window):
    """
    Create a main menu
    """
    # Play music
    jukebox = Jukebox()
    jukebox.load('intro')
    jukebox.play()

    # Create background
    background = pygame.Surface(window.get_size())
    background = background.convert()
    background.fill(CIEL)

    if pygame.font:
        font = pygame.font.Font(FONT_DK_SAMHAIN, 46)
        play_txt = font.render(_('JOUER'), 1, (10, 10, 10))
        play_txt_pos = play_txt.get_rect(
            centerx=200,
            centery=background.get_height()/2
        )
        background.blit(play_txt, play_txt_pos)

        load_txt = font.render(_('CHARGER'), 1, (10, 10, 10))
        load_txt_pos = load_txt.get_rect(
            centerx=550,
            centery=background.get_height()/2
        )
        background.blit(load_txt, load_txt_pos)

    window.blit(background, (0, 0))
    pygame.display.flip()

    #bomb = Bomb()
    allsprites = pygame.sprite.RenderPlain()

    for number in range(random.randint(4, 6)):
        altitude = random.randint(0, 300)
        speed = random.randint(1, 6)
        allsprites.add(Cloud(altitude, speed))

    hero = Hero()
    allsprites.add(hero)

    pygame.draw.rect(background, GREEN_PELOUSE, (0, 500, WINDOW_WIDTH, 100))

    brand, brand_rect = core.load_image('Battle-story.png', -1)
    brand_rect.left = WINDOW_WIDTH / 2 - brand_rect.width / 2
    brand_rect.top = WINDOW_HEIGHT / 3 - brand_rect.height / 2
    background.blit(brand, brand_rect)

    #bombsprites = pygame.sprite.RenderPlain((bomb))
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                quit_menu(window)
            elif event.type == MOUSEBUTTONDOWN:
                posx, posy = pygame.mouse.get_pos()
                if posx >= play_txt_pos.left and \
                   posx <= play_txt_pos.left + play_txt_pos.width and \
                   posy >= play_txt_pos.top and \
                   posy <= play_txt_pos.top + play_txt_pos.height:
                    print("jeu")
                    game = Game('map1')
                    game.play(window)
                elif posx >= load_txt_pos.left and \
                   posx <= load_txt_pos.left + load_txt_pos.width and \
                   posy >= load_txt_pos.top and \
                   posy <= load_txt_pos.top + load_txt_pos.height:
                    print("Load")
        hero.play_auto_animation()
        allsprites.update()
        #bombsprites.update()
        window.blit(background, (0, 0))
        allsprites.draw(window)
        pygame.display.flip()
        FPS_CLOCK.tick(FPS_FREQUENCY)
Пример #37
0
import pygame

from engine.game import Game
from engine.state import NormalNode

if __name__ == '__main__':
	pygame.init()

	screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE)
	#screen = pygame.display.set_mode((0, 0))
	
	pygame.display.set_caption('Game Adventure')
	
	game = Game()
	
	game.run(NormalNode(game, "level0"), screen)
	
	pygame.quit()
Пример #38
0
from __future__ import division

from engine.game import Game

game = Game()

while True:
    game.step()


# TODO: Neural networks return values of 1, why? Eye position setting is compeltely wrong.
Пример #39
0
def game(request):
    g=Game()
    t=''
    player = request.user.userprofile
    #Can initialise these using player state !!??
    pps = pickle.dumps(g.player_state)
    kills = 0
    days = 0
    food = 3
    ammo = 2
    people = 1
    g.player_state = pickle.loads(pps)


    context_dict = {'player':player, 'game_over':False, 'new_day':False, 'kills':kills, 'food':food, 'days':days, 'ammo': ammo, 'party': people,
                    'player_state': g.player_state }

    if g.is_game_over():
        context_dict['game_over'] = True
    else:
        g.start_new_day()

    if g.is_day_over():
        g.end_day()
        g.start_new_day()

    if context_dict['game_over'] == False and context_dict['new_day'] == False:
        if t == 'MOVE':
            g.take_turn('MOVE')
        elif t == ('ENTER'):
            g.take_turn('ENTER')
        elif t == ('WAIT'):
            g.take_turn('WAIT')
        elif t == ('FIGHT'):
            g.take_turn('FIGHT')
        elif t == ('SEARCH'):
            g.take_turn('SEARCH')
        elif t == ('EXIT'):
            g.take_turn('EXIT')
        elif t ==('RUN'):
            g.take_turn('RUN')

        context_dict = fill_dict(g)
        context_dict['state'] = str(g.player_state)
        context_dict['gstate'] = g.game_state
        context_dict['time'] = g.time_left

    if g.is_game_over():
        context_dict={'game_over':True}
    elif g.is_day_over():
        context_dict={'new_day':True}
        if g.update_state.party<0:
            print "You lost: {0} people".format(abs(g.update_state.party))

        elif g.update_state.party>0:
            print "{0} more people have joined your party".format(g.update_state.party)

        elif g.update_state.ammo > 0:
            print "You found: {0} units of ammo".format(g.update_state.ammo)

        elif g.update_state.ammo < 0:
            print "You used: {0} units of ammo".format(abs(g.update_state.ammo))

        elif g.update_state.food > 0:
            print "You found: {0} units of food".format(g.update_state.food)

        elif g.update_state.food < 0:
            print "You used: {0} units of food".format(abs(g.update_state.food))

        elif g.update_state.kills > 0:
            print "You killed: {0} zombies".format(g.update_state.kills)

        elif g.update_state.days > 0:
            print "New Day: You survived another day!"
    #Put these updates into a dictionary Q pickle ?

    return render(request, 'zombieGame/game.html', context_dict)
Пример #40
0
def house(request):
    g = Game()
    g.start_new_day() #need to pickle so not resetting up again
    context_dict = house_dict(g)
    return render(request, 'zombieGame/house.html', context_dict)
Пример #41
0
from engine.game import Game

if __name__ == '__main__':
    game = Game()
    game.loop()
Пример #42
0
Файл: views.py Проект: em21/Wad1
def game(request):
    g = Game()
    g.start_new_day()
    context_dict=fill_dict(g)
    return render(request, 'zombieGame/game.html', context_dict)
Пример #43
0
def game(request):
    if request.POST.get("is_new_game") == "yes":
        g = Game()
    else:
        if not os.path.isfile('gameData/'+request.user.username+'.txt'): #new game
            g = Game()
        else: #continue game
            f = open('gameData/'+request.user.username+'.txt', 'rb')
            g = dill.load(f)
            f.close()
    
    
    if g.game_state is None: #game is uninitialised
        g.start_new_day()
    
    #update max_party
    if g.update_state.party >0:
        g.player_state.max_party += g.update_state.party
    
    new_day = False
    
    if g.is_day_over():
        new_day = True
        g.start_new_day()
    
    if request.method == 'POST':
        print "-------------------------"
        print request.POST.get('action')
        print request.POST.get('pos')
        print "-------------------------"
        action = request.POST.get('action')
        if action == 'MOVEENTER':
            pos = request.POST.get('pos')
            g.take_turn('MOVE', int(pos))
            g.take_turn('ENTER')
        elif action == 'SEARCH':
            pos = request.POST.get('pos')
            g.take_turn(action, int(pos))
        else:
            g.take_turn(action)
    
    if g.is_game_over():
        days_survived = g.player_state.days
        zombie_kills = g.player_state.kills
        most_survivors = g.player_state.max_party
        user_prof = UserProfile.objects.get(user=request.user)
        
        score = Score.objects.create(user=user_prof, zombie_kills=zombie_kills, most_survivors=most_survivors, days_survived=days_survived)
        score.save()
        
        os.remove('gameData/'+request.user.username+'.txt')
        
        return render(request, "zombie/gamedeath.html", {'days_survived':days_survived, 'zombie_kills':zombie_kills, 'most_survivors':most_survivors})
    
    f = open('gameData/'+request.user.username+'.txt', 'wb')
    dill.dump(g, f)
    f.close()
    
    t = str(int(((84-g.time_left)/6)+10))+":"+str(int((84-g.time_left)%6))+"0";
    
    return render(request, 'zombie/game.html', {'game':g, 'time':t, 'new_day':new_day})