예제 #1
0
파일: server.py 프로젝트: mtnmts/GGJ2014
 def restart(self):
     spawn_a = (randrange(T_P, WORLD_WIDTH-4*T_P),
                 randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 4*T_P))
     spawn_b = (randrange(T_P, WORLD_WIDTH-4*T_P),
                 randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 4*T_P))
     for client in self.clients:
         client.send_data({'type': END_GAME, 'wins_a': self.wins_a, 'wins_b': self.wins_b, 'spawn_a': spawn_a, 'spawn_b': spawn_b})
     self.player_a = Player(RED, spawn_a)
     self.player_b = Player(BLUE, spawn_b)
     self.world.empty()
     self.updates = self.world.randomize_start()
예제 #2
0
  def test_attributes(self):
    """ test basic attributes on a player """
    name = 'Dez Bryant'
    position = 'WR'
    salary = 14750
    ppg = 13.9

    player = Player(name, position, ppg, salary)
    self.assertEquals(player.get_name(), name)
    self.assertEquals(player.get_position(), position)
    self.assertEquals(player.get_value(), ppg)
    self.assertEquals(player.get_cost(), salary)
예제 #3
0
  def test_configuration_adding_and_size(self):
    ''' test that we can add to a configuration and obtain size '''
    slots = ['QB', 'RB', 'RB', 'WR', 'WR', 'TE', 'FLEX', 'K', 'D']
    config = Configuration(slots, 100000)

    player = Player('Dez Bryant', 'WR', 13.9, 14750)
    player2 = Player('Doug Martin', 'RB', 17.1, 16300)
    config.add_player(player, 'WR1')
    config.add_player(player2, 'RB1')
    self.assertEquals(config.get_value(), 31)
    self.assertEquals(config.get_cost(), 31050)
    self.assertEquals(len(config.get_config()), len(slots))
예제 #4
0
def update_remote_player(player: Player, gm):
    player_obj = gm.get_player_actor(player.name)
    update = RemoteActorUpdate()
    update.position = player_obj.pos
    update.type = P_UPDATE
    view_dimensions = [(player_obj.move_speed * 2) + 1,
                       (player_obj.move_speed * 2) + 1]
    layout = to_layout(player_obj.pos, gm.gamestate.current_level,
                       view_dimensions)
    update.layout = layout[LAYOUT]
    update.layout_coords = coord_radius(player_obj.pos,
                                        to_coord(view_dimensions))

    actors = []
    other_players = [p for p in gm.players if p.name is not player.name]
    for player in other_players:
        player_obj = gm.get_player_actor(player.name)
        if player_obj.pos in update.layout_coords:
            actor_type = PLAYER
            actor_name = player_obj.name
            pos = to_point(player_obj.pos)
            actor_pos = ActorPosition(actor_type, actor_name, pos)
            actors.append(actor_pos)
    for adv in gm.adversaries:
        adversary_obj = gm.get_adversary_actor(adv.name)
        if adversary_obj.pos in update.layout_coords:
            actor_type = adversary_obj.type
            actor_name = adversary_obj.name
            pos = to_point(adversary_obj.pos)
            actor_pos = ActorPosition(actor_type, actor_name, pos)
            actors.append(actor_pos)
    level = gm.gamestate.current_level
    pos_info = check_position(player_obj.pos, level)

    is_room = pos_info[TYPE] == ROOM
    objects = []
    if is_room:
        for room in level.rooms:
            for item in room.items:
                if item.pos in update.layout_coords:
                    obj_pos = ObjectPos(KEY, to_point(item.pos))
                    objects.append(obj_pos)
    for exit_ in level.exits:
        if exit_ in update.layout_coords:
            obj_pos = ObjectPos(EXIT, to_point(exit_))
            objects.append(obj_pos)
    update.actors = actors
    update.objects = objects
    player.recieve_update(update)
예제 #5
0
파일: server.py 프로젝트: mtnmts/GGJ2014
 def __init__(self):
     a_spawn = (randrange(T_P, WORLD_WIDTH-4*T_P),
                 randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 8*T_P))
     b_spawn = (randrange(T_P, WORLD_WIDTH-4*T_P),
                 randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 8*T_P))
     self.player_a = Player(BLACK, a_spawn)
     self.player_b = Player(BLACK, b_spawn)
     self.world = World(WORLD_WIDTH/T_P, WORLD_HEIGHT/T_P, True)
     self.updates = self.world.randomize_start()
     self.clients = []
     self.wins_a = 0
     self.wins_b = 0
     self.run_lock = threading.Lock()
     self.repl = threading.Thread(target=self.repl_thread)
     self.repl.daemon = True
예제 #6
0
    def __init__(self, slots, max_allowed_cost):
        self._configuration = {}
        self._slots = slots
        self._max_allowed_cost = max_allowed_cost

        for slot in self._slots:
            self._configuration[slot] = Player('NULL', 'NULL', 0, 0)
예제 #7
0
파일: server.py 프로젝트: mtnmts/GGJ2014
 def load_level(self, level_location):
     data = json.loads(open('..' + os.sep + 'good-levels' + os.sep + level_location, 'rb').read().decode('zlib'))
     spawn_a = data[0]
     spawn_b = data[1]
     tiles = data[2:]
     for client in self.clients:
         client.send_data({'type': END_GAME, 'wins_a': self.wins_a, 'wins_b': self.wins_b, 'spawn_a': spawn_a, 'spawn_b': spawn_b})
     # clean world
     self.player_a = Player(RED, spawn_a)
     self.player_b = Player(BLUE, spawn_b)
     self.world.empty()
     self.updates = []
     for tile in tiles:
         x, y, t = tile
         self.world.add_tile(x, y, t)
         self.updates.append((x, y, t))
예제 #8
0
 def __init__(self):
     log.debug("Initializing craps")
     self.prev_round = CrapsRound()
     players = [Player(player['bettingStrategy'], player['bankroll']) for player in craps_fig['players']]
     dealer = Dealer()
     log.debug('Playing craps with players=%s and dealer=%s', players, dealer)
     super(Craps, self).__init__(players, dealer)
예제 #9
0
 def test_random_player(self):
     name = 'Dez Bryant'
     position = 'WR'
     salary = 14750
     ppg = 13.9
     player = Player(name, position, ppg, salary)
     player_list = PlayerList(PlayerList.POSITIONS)
     player_list.add_player(player)
     self.assertEquals(player, player_list.get_random_player(position))
예제 #10
0
 def read_from_custom_csv_simple(self, csv_path):
   ''' Read in player list from a simpler custom CVS file '''
   file_handler = open(csv_path, 'r')
   file_handler.next()  # skip header row
   csv_reader = csv.DictReader(file_handler, self.CUSTOM_FIELDS2,
                               delimiter=',')
   for line in csv_reader:
     player = Player(line['player_name'], line['position'], line['ppg'])
     self.add_player(player)
예제 #11
0
 def read_from_draftday_csv(self, csv_path):
   """ read in the players from a draftday csv file """
   file_handler = open(csv_path, 'r')
   file_handler.next()  # skip header row
   csv_reader = csv.DictReader(file_handler, self.DRAFTDAY_FIELDS, ',')
   for line in csv_reader:
     opponent = Teams().get_by_name(line['opp'])
     player = Player(line['player_name'], line['position'],
                     line['ppg'], line['salary'], opponent)
     self.add_player(player)
예제 #12
0
  def test_adding_a_second_player(self):
    ''' test that adding the same player twice throws an exception '''
    slots = ['QB', 'RB', 'RB', 'WR', 'WR', 'TE', 'FLEX', 'K', 'D']
    config = Configuration(slots, 100000)

    player = Player('Dez Bryant', 'WR', 13.9, 14750)
    player2 = player

    config.add_player(player, 'WR')
    self.assertRaises(BaseException, config.add_player, (player2, 'WR2'))
예제 #13
0
    def connect(self, players=2):
        self.players = players
        self.engine = GameEngine()
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((self.host, self.port))
        self.server.listen(players)

        for x in range(players):
            (client, address) = self.server.accept()
            self.clients.append((client, address))
            client.sendall(
                Encoder.encode_string(
                    str(self.engine.height * 50) + 'x' +
                    str(self.engine.width * 50)))

            # SMSG_INIT_DATA contains the map, the number of players and their guids
            client.sendall(Encoder.encode_int(SMSG_INIT_DATA))
            for row in self.engine.raw_map:
                for data in row:
                    client.sendall(Encoder.encode_int(data))
            pl = Player(self.guid_generator, client)
            pl.position = start_positions[pl.guid]
            self.engine.players.append(pl)
            self.engine.objects.append(pl)
            self.guid_generator += 1

        for cl in self.clients:
            # SMSG_INIT_PLAYERS contains the number of players and the guid of each (plus a boolean to mark if it is the player)
            cl[0].sendall(Encoder.encode_int(SMSG_INIT_PLAYERS))
            cl[0].sendall(Encoder.encode_int(players))
            for k in range(players):
                cl[0].sendall(Encoder.encode_int(self.engine.players[k].guid))
                cl[0].sendall(
                    Encoder.encode_int(1 if self.engine.players[k].client ==
                                       cl[0] else 0))

        self.packet_threads = [
            Thread(target=self.packets, args=(client[0], ))
            for client in self.clients
        ]
        for th in self.packet_threads:
            th.start()
        self.update()
예제 #14
0
    def test_basic_player_stuff(self):
        """ test basic attributes on a player """
        name = 'Dez Bryant'
        position = 'WR'
        salary = 14750
        ppg = 13.9
        player = Player(name, position, ppg, salary)

        player_list = PlayerList(PlayerList.POSITIONS)
        player_list.add_player(player)
        player_list.add_player(player)

        self.assertEquals(player_list.get_players()[0], player)
        self.assertEquals(len(player_list.get_players()), 2)
예제 #15
0
    def test_attributes(self):
        """ test basic attributes on a player """
        name = 'Dez Bryant'
        position = 'WR'
        salary = 14750
        ppg = 13.9

        player = Player(name, position, ppg, salary)
        self.assertEquals(player.get_name(), name)
        self.assertEquals(player.get_position(), position)
        self.assertEquals(player.get_value(), ppg)
        self.assertEquals(player.get_cost(), salary)
예제 #16
0
파일: game.py 프로젝트: DownSpiral/py_hive
    def __init__(self, settings):
        self.board = Board(**settings['board_settings'])
        self.game_tick = 0
        self.actions = []

        self.players = []
        self.ants = []
        for i, player_settings in enumerate(settings['players_settings']):
            # Initialize players
            player = Player(player_id=i, **player_settings)
            self.players.append(player)

            # Initialize ants
            tile = self.board.random_empty_tile()
            self.ants.append(Ant(player=player, tile=tile, type="queen"))

        # Initialize food
        amt = settings['food_amount']
        num_sources = settings['food_sources']
        sprawl = settings['food_sprawl']
        tiles = self.board.flat_tiles()
        shuffle(tiles)
        for t in tiles[0:num_sources]:
            self.gen_food(t, amt, sprawl)
예제 #17
0
 def test_random_player_with_position_num(self):
     player = Player('Dez Bryant', 'WR', 13.9, 14750)
     player_list = PlayerList(PlayerList.POSITIONS)
     player_list.add_player(player)
     self.assertEquals(player, player_list.get_random_player('WR2'))
예제 #18
0
 def test_validate_new_player_coordiate_is_empty(self):
     player1 = Player()
     self.assertEqual(player1.input_grid_coord, [])
예제 #19
0
 def test_player_set_input_cord_returns_correct_value(
         self, textposition, coord):
     player1 = Player()
     player1.input_choice = textposition
     player1.set_input_coord()
     self.assertEqual(player1.input_grid_coord, coord)
예제 #20
0
 def test_player_isvalid_position_returns_false(self, textposition, size):
     player1 = Player()
     self.assertFalse(player1.isvalid_position(textposition, size))
예제 #21
0
 def test_validate_new_player_symbol_is_correct(self, character):
     player1 = Player(character)
     self.assertEqual(player1.symbol, character)
예제 #22
0
 def packets(self):
     while not self.quit:
         try:
             opcode = Decoder.decode_int(self.server.recv(4))
             if opcode == SMSG_INIT_DATA:
                 for i in range(self.rows):
                     for j in range(self.cols):
                         self.raw_map[i][j] = Decoder.decode_int(
                             self.server.recv(4))
                 self.map_ready = True
             if opcode == SMSG_INIT_PLAYERS:
                 nr_of_players = Decoder.decode_int(self.server.recv(4))
                 for k in range(nr_of_players):
                     guid = Decoder.decode_int(self.server.recv(4))
                     is_me = Decoder.decode_int(self.server.recv(4))
                     pl = Player(guid)
                     pl.position = start_positions[pl.guid]
                     self.objects.append(pl)
                     if is_me == 1:
                         self.player = pl
                 self.game_started = True
             if opcode == SMSG_UPDATE_POSITION:
                 player_guid = Decoder.decode_int(self.server.recv(4))
                 pos_x = Decoder.decode_int(self.server.recv(4))
                 pos_y = Decoder.decode_int(self.server.recv(4))
                 for obj in self.objects:
                     if obj.guid == player_guid:
                         obj.position = (pos_x, pos_y)
             if opcode == SMSG_PUT_BOMB_ACK:
                 bomb_guid = Decoder.decode_int(self.server.recv(4))
                 pos_x = Decoder.decode_int(self.server.recv(4))
                 pos_y = Decoder.decode_int(self.server.recv(4))
                 b = Bomb(bomb_guid, (pos_x, pos_y))
                 self.objects.append(b)
             if opcode == SMSG_DETONATE_BOMB:
                 bomb_guid = Decoder.decode_int(self.server.recv(4))
                 hit_units = Decoder.decode_int(self.server.recv(4))
                 for i in range(hit_units):
                     guid = Decoder.decode_int(self.server.recv(4))
                     for ob in self.objects:
                         if ob.guid == guid:
                             ob.healths -= 1
                             ob.invulnerability_timer = 1
                 dead_players = []
                 for ob in self.objects:
                     if isinstance(ob, Player):
                         if ob.healths <= 0:
                             dead_players.append(ob.guid)
                 if len(dead_players) != 0:
                     if len(dead_players) > 1:
                         self.game_over = -1
                     else:
                         self.game_over = 1 if dead_players[0] == 2 else 2
                 hit_walls = Decoder.decode_int(self.server.recv(4))
                 for i in range(hit_walls):
                     x = Decoder.decode_int(self.server.recv(4))
                     y = Decoder.decode_int(self.server.recv(4))
                     self.raw_map[x][y] = GameEngine.EMPTY
                 bomb = None
                 for obj in self.objects:
                     if obj.guid == bomb_guid:
                         bomb = obj
                         break
                 if bomb is not None:
                     self.objects.append(
                         Explosion(
                             (bomb.position[0] - 50, bomb.position[1] - 50),
                             100))
                     self.objects.remove(bomb)
             if opcode == SMSG_REMOVE_INVULNERABILITY:
                 guid = Decoder.decode_int(self.server.recv(4))
                 for ob in self.objects:
                     if ob.guid == guid:
                         self.expired_invulnerabilities.append(ob)
         except:
             self.quit = True
예제 #23
0
    print("1 - Two Player game")
    print("2 - One Player versus defensive AI")
    print("3 - One Player versus agressive AI")
    while not validinput:
        gameoption = input("Enter size of board between 3 and 10 ")
        if gameoption.isdigit():
            if int(gameoption) > 0 and int(gameoption) < 4:
                validinput = True
        print("Sorry - You must enter a numeric value!")
    return int(gameoption)


board1 = Board()
gameoption = game_setup()
if gameoption == 1:
    player1 = Player("X")
    player2 = Player("O")
elif gameoption == 2:
    player1 = Player("X")
    player2 = AIPlayer("O", 2, -10)
else:
    player1 = Player("X")
    player2 = AIPlayer("O", 4, -2)
game_complete = False
counter = 0
board1.print()
while not game_complete and not board1.is_winner(RECORD_THE_WINNER):
    player1.take_turn(board1) if (counter %
                                  2) == 0 else player2.take_turn(board1)
    if (board1.is_game_over()):
        print("The game was a tie.")
예제 #24
0
파일: server.py 프로젝트: mtnmts/GGJ2014
class ServerGame(object):
    def __init__(self):
        a_spawn = (randrange(T_P, WORLD_WIDTH-4*T_P),
                    randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 8*T_P))
        b_spawn = (randrange(T_P, WORLD_WIDTH-4*T_P),
                    randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 8*T_P))
        self.player_a = Player(BLACK, a_spawn)
        self.player_b = Player(BLACK, b_spawn)
        self.world = World(WORLD_WIDTH/T_P, WORLD_HEIGHT/T_P, True)
        self.updates = self.world.randomize_start()
        self.clients = []
        self.wins_a = 0
        self.wins_b = 0
        self.run_lock = threading.Lock()
        self.repl = threading.Thread(target=self.repl_thread)
        self.repl.daemon = True

    def repl_thread(self):
        while True:
            result = raw_input(">>>")
            letter = result.split(' ')[0].lower()
            if letter == 'h':
                print "h - help, l - load (map), r - restart, g - available savegames"
            if letter == 'l':
                with self.run_lock:
                    self.load_level(result.split(' ')[1])
            if letter == 'r':
                with self.run_lock:
                    self.restart()
            if letter == 'g':
                print ' '.join([x for x in os.listdir('..' + os.sep + 'good-levels') if 'savegame' in x])

    def load_level(self, level_location):
        data = json.loads(open('..' + os.sep + 'good-levels' + os.sep + level_location, 'rb').read().decode('zlib'))
        spawn_a = data[0]
        spawn_b = data[1]
        tiles = data[2:]
        for client in self.clients:
            client.send_data({'type': END_GAME, 'wins_a': self.wins_a, 'wins_b': self.wins_b, 'spawn_a': spawn_a, 'spawn_b': spawn_b})
        # clean world
        self.player_a = Player(RED, spawn_a)
        self.player_b = Player(BLUE, spawn_b)
        self.world.empty()
        self.updates = []
        for tile in tiles:
            x, y, t = tile
            self.world.add_tile(x, y, t)
            self.updates.append((x, y, t))


    def run(self):
        self.connect_players()
        self.start_game()
        self.update_clients()
        self.repl.start()
        i = 0
        while True:
            with self.run_lock:
                CLOCK.tick(FPS)
                self.get_actions()
                a_ret = self.player_a.update(self.world)
                if a_ret == WIN:
                    self.wins_a += 1
                    self.restart()
                b_ret = self.player_b.update(self.world)
                if b_ret == WIN:
                    self.wins_b += 1
                    self.restart()
                self.update_clients()
                i += 1
                if i % FRAMES_PER_CREDIT == 0:
                    i = 0
                    self.player_a.credits += 1
                    self.player_b.credits += 1

    def restart(self):
        spawn_a = (randrange(T_P, WORLD_WIDTH-4*T_P),
                    randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 4*T_P))
        spawn_b = (randrange(T_P, WORLD_WIDTH-4*T_P),
                    randrange((WORLD_HEIGHT / 2) + 2*T_P, WORLD_HEIGHT - 4*T_P))
        for client in self.clients:
            client.send_data({'type': END_GAME, 'wins_a': self.wins_a, 'wins_b': self.wins_b, 'spawn_a': spawn_a, 'spawn_b': spawn_b})
        self.player_a = Player(RED, spawn_a)
        self.player_b = Player(BLUE, spawn_b)
        self.world.empty()
        self.updates = self.world.randomize_start()

    def start_game(self):
        for client in self.clients:
            client.send_data({'type' : START_GAME, 'role' : client.role, 'spawn_a': self.player_a.spawn_point, 'spawn_b': self.player_b.spawn_point})

    def connect_players(self):
        role_giver = self.role_distributor()
        sock = socket.socket()
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(SERVER_ADDR)
        sock.listen(MAX_CLIENTS)
        while len(self.clients) < MAX_CLIENTS:
            host, endpoint = sock.accept()
            new_client = ClientConnection(host, endpoint, role_giver.next())
            print "Accepted new client:", repr(new_client)
            self.clients.append(new_client)

    def get_actions(self):
        clients_with_actions = select.select(self.clients, [], [], 0)
        for client in clients_with_actions[0]:
            for event in client.get_data():
                if event['type'] == MOVE:
                    self.handle_move(client, event)
                elif event['type'] == ADD_ITEM:
                    self.handle_add_item(client, event)
                elif event['type'] == SUICIDE:
                    if client.role == RUNNER_TEAM_A:
                        self.player_a.die()
                    elif client.role == RUNNER_TEAM_B:
                        self.player_b.die()
                elif event['type'] == DEVMODE:
                    if client.role == DISRUPTOR_TEAM_A:
                        self.player_a.toggle_developer()
                    elif client.role == DISRUPTOR_TEAM_B:
                        self.player_b.toggle_developer()


    def handle_move(self, client, event):
        if client.role == RUNNER_TEAM_A:
            player = self.player_a
        elif client.role == RUNNER_TEAM_B:
            player = self.player_b
        else:
            return

        if event['direction'] == LEFT:
            player.walking_left = event['pressed']
        elif event['direction'] == RIGHT:
            player.walking_right = event['pressed']
        elif event['direction'] == JUMP:
            if event['pressed'] and player.on_ground(self.world):
                player.jump()

    def handle_add_item(self, client, event):
        if client.role == DISRUPTOR_TEAM_A:
            player = self.player_a
        elif client.role == DISRUPTOR_TEAM_B:
            player = self.player_b
        else:
            return

        x = event['x']
        y = event['y']
        t = event['t']

        tile_type = Tile.tile_types[t]
        if tile_type.cost > player.credits and not(player.is_developer()):
            return

        min_dist = tile_type.w * tile_type.h
        a_x, a_y = self.player_a.rect.center
        b_x, b_y = self.player_b.rect.center
        if (((x+0.5)*T_P - a_x)**2 + ((y+0.5)*T_P - a_y)**2 < 9*T_P*T_P*min_dist  or \
            ((x+0.5)*T_P - b_x)**2 + ((y+0.5)*T_P - b_y)**2 < 9*T_P*T_P*min_dist):
            return
        added = self.world.add_tile(x, y, t)
        if added:
            self.updates.append((x, y, t))
            if not(player.is_developer()):
                player.credits -= tile_type.cost

    def update_clients(self):
        p1 = self.player_a.rect
        p2 = self.player_b.rect
        for client in self.clients:
            client.send_data({'player_one': {'x': p1.x, 'y': p1.y,
                'credits': self.player_a.credits},
                'player_two' : {'x': p2.x, 'y': p2.y,
                    'credits': self.player_b.credits},
                'updates': self.updates})
        self.updates = []

    def role_distributor(self):
        yield DISRUPTOR_TEAM_A
        yield RUNNER_TEAM_A
        yield DISRUPTOR_TEAM_B
        yield RUNNER_TEAM_B