Exemplo n.º 1
0
	def register_team(self, team, sock):
		if not team in self.team_whitelist:
			sock.close(code=messaging.DO_NOT_RECONNECT, reason="This team is not registered for the competition.")
			return

		if team in self.sock_to_team.values():
			sock.close(code=messaging.DO_NOT_RECONNECT, reason="This team already has a connection to the game server.")
			return
		self.sock_to_team[sock] = team

		# All games in a given competition will use the same seed.
		if not self.common_seed:
			self.common_seed = random.randint(1, 1 << 30)

		if not team in self.team_to_game:
			game = Board(seed=self.common_seed)
			game.game_id = util.generate_game_id()
			self.team_to_game[team] = game
		elif self.started:
			# We must be resuming a broken connection.
			Competition.request_next_move(self.team_to_game[team], sock)
			return

		# Game IDs are visible to the client only in testing.
		if self.is_test_run:
			Competition.notify_game_created(sock, game.game_id)
		else:
			Competition.notify_game_created(sock)
Exemplo n.º 2
0
class LocalServer(object):
    def __init__(self, seed):
        self.seed = seed

    def submit_game_move(self, game_id, move_list, moves_made):
        # update local state, return json object
        game_state = self.game
        made_move = False
        if game_state.state != "failed":
            if time.time() - self.game.game_started_at > util.AI_CLIENT_TIMEOUT:
                game_state.state = "failed"
            else:
                game_state.send_commands(move_list)
                made_move = True
        game_state.total_steps += int(bool(made_move))

        if game_state.state == "failed":
            raise GameOverError(game_state.to_dict())
        return dict(
            ret="ok",
            game=dict(id=0, number_moves_made=game_state.total_steps, game_state=game_state.to_dict()),
            competition_seconds_remaining=util.AI_CLIENT_TIMEOUT - (time.time() - self.game.game_started_at) - 1,
        )

    def get_local_game(self):
        # return a json object
        self.game = Board(self.seed)
        self.game.game_started_at = time.time()
        self.game.game_id = 0
        self.game.total_steps = 0
        return dict(
            ret="ok",
            game=dict(id=0, number_moves_made=self.game.total_steps, game_state=self.game.to_dict()),
            competition_seconds_remaining=util.AI_CLIENT_TIMEOUT - 1,
        )
Exemplo n.º 3
0
    def __init__(self):
        self.SQUARE_SIZE = 100
        self.RADIUS_SIZE = self.SQUARE_SIZE / 2 - 10
        self.b = Board()

        pygame.init()

        height = self.b.NUM_OF_ROWS * self.SQUARE_SIZE
        width = self.b.NUM_OF_COLS * self.SQUARE_SIZE
        size = (width, height)

        self.screen = pygame.display.set_mode(size)
        self.screen.fill('Lavender')
        self.myfont = pygame.font.SysFont("monospace", 75)

        self.draw_grid(self.b.grid)
        pygame.display.update()
Exemplo n.º 4
0
def container_from_game_row(row, offset=0):
	return Container(id=row[offset],
			 number_moves_made=row[offset + 1],
			 game_state=Board.from_dict(json.loads(row[offset + 2])),
			 team_id=row[offset + 3],
			 competition_id=row[offset + 4],
			 score=row[offset + 5],
			 finished_ts=row[offset + 6],
			 )
Exemplo n.º 5
0
def test_is_col_full():
    b = Board()
    player = 1
    assert b.is_col_full(0) is False
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0) is False
    assert b.is_col_full(0) is True
Exemplo n.º 6
0
def test__check_vertical():
    b = Board()
    player = 1
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b._check_vertical(1, 0, 3) is False
    assert b.add_disc(player, 0)
    assert b._check_vertical(1, 0, 2)
Exemplo n.º 7
0
 def get_local_game(self):
     # return a json object
     self.game = Board(self.seed)
     self.game.game_started_at = time.time()
     self.game.game_id = 0
     self.game.total_steps = 0
     return dict(
         ret="ok",
         game=dict(id=0, number_moves_made=self.game.total_steps, game_state=self.game.to_dict()),
         competition_seconds_remaining=util.AI_CLIENT_TIMEOUT - 1,
     )
Exemplo n.º 8
0
        def _create_game(self, competition_id, team_id, game_seed):
                assert isinstance(competition_id, ACCEPTABLE_INT_TYPES), "bad competition id%r" % (competition_id,)
                assert isinstance(team_id, ACCEPTABLE_INT_TYPES), "bad team id%r" % (team_id,)
                assert isinstance(game_seed, ACCEPTABLE_INT_TYPES), "bad game seed id%r" % (game_seed,)
                sql = """
INSERT INTO game (
number_moves_made,
game_state,
team_id,
competition_id
)
VALUES
(%s, %s, %s, %s)
"""
                gs = Board(game_seed)
                self.execute(sql, (0, json.dumps(gs.to_dict()), team_id, competition_id))
                game_id = self.lastrowid
                return Container(id=game_id,
                                 number_moves_made=0,
                                 game_state=gs,
                                 team_id=team_id,
                                 competition_id=competition_id)
Exemplo n.º 9
0
def test_add_disc():
    b = Board()
    player = 1
    assert b.add_disc(player, 0)
    assert b.grid[5][0] == player
    assert b.add_disc(player, 0)
    assert b.grid[4][0] == player
    assert b.add_disc(player, 0)
    assert b.grid[3][0] == player
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 0) is False
Exemplo n.º 10
0
    def play(self):
        b = Board()
        player = None  # first player
        has_won_condition = False
        valid_input_condition = False

        while not has_won_condition:

            if player is None or player == 2:
                player = 1
            else:
                player = 2

            print("Current grid:")
            print(b.__repr__())

            while not valid_input_condition:
                play = input(" Player " + str(player) +
                             ": Please enter column number (0 - 6).")
                if play.isdigit():
                    play = int(play)
                    if 0 <= play <= 6:
                        if b.add_disc(player, play):
                            has_won_condition = b.has_won(
                                player, b.current_col, b.current_row)
                            valid_input_condition = True
                        else:
                            print("Full column, try another column.")
                    else:
                        print("Column not in range.")
                else:
                    print("Column must be a number.")

            valid_input_condition = False

        self._announce_win(player)
Exemplo n.º 11
0
class ServerLogic:
    def __init__(self):
        logging.basicConfig(format="%(levelname)s: %(message)s",
                            level=logging.INFO)
        self.b = Board()

    async def generate_reply(self, player_id, request_data):
        logging.info("recieved request_data:")
        logging.info(request_data)
        logging.info("from player id:")
        logging.info(player_id)

        reply = {}

        if not request_data['op'] == pygame.QUIT:
            if self._is_valid_keydown(request_data):
                disc_added = self.b.add_disc(player_id,
                                             request_data['key'] - 48)
                if disc_added:
                    if self.b.has_won(player_id, self.b.current_col,
                                      self.b.current_row):
                        reply['op'] = ServerOpCodes.USER_WON
                    else:
                        reply['op'] = ServerOpCodes.UPDATE_GRID
                        # reply['grid'] = self.b.grid
                else:
                    reply['op'] = ServerOpCodes.COL_FULL
            else:
                reply['op'] = ServerOpCodes.ILLEGAL_INPUT
        else:
            reply['op'] = ServerOpCodes.GAME_ENDED

        return reply

    def _is_valid_keydown(self, request_data):
        return 48 <= request_data['key'] <= 54
Exemplo n.º 12
0
        def get_game_by_team_and_competition_id(self, team_id, competition_id):
                sql = """
SELECT id, number_moves_made, game_state, team_id, competition_id, score
FROM game
WHERE team_id = %s AND competition_id = %s
"""
                self.execute(sql, (team_id, competition_id))
                game_row = self.fetchone()
                if game_row is None:
                        return None

                return Container(id=game_row[0],
                                 number_moves_made=game_row[1],
                                 game_state=Board.from_dict(json.loads(game_row[2])),
                                 team_id=game_row[3],
                                 competition_id=game_row[4])
Exemplo n.º 13
0
	def on_get_action(self, board: Board) -> Action:
		while True:
			print(board.matrix)
			key = input("Input your action:")
			action = {
				"w": Action.UP,
				"s": Action.DOWN,
				"a": Action.LEFT,
				"d": Action.RIGHT
			}.get(key)
			if action is None:
				print("Please type 'w' 'a' 's' or 'd' but not '", key, "'", sep="")
				continue
			if action not in board.get_options():
				print("Your action is illegal!")
				continue
			return action
Exemplo n.º 14
0
    def __init__(self):
        logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO)

        self.SQUARE_SIZE = 100
        self.RADIUS_SIZE = self.SQUARE_SIZE / 2 - 10
        self.b = Board()

        pygame.init()

        height = self.b.NUM_OF_ROWS * self.SQUARE_SIZE
        width = self.b.NUM_OF_COLS * self.SQUARE_SIZE
        size = (width, height)

        self.screen = pygame.display.set_mode(size)
        self.screen.fill('Lavender')
        self.myfont = pygame.font.SysFont("monospace", 75)

        self.draw_grid(self.b.grid)
        pygame.display.update()

        pygame.event.set_allowed(None)
        pygame.event.set_allowed([pygame.KEYDOWN])
Exemplo n.º 15
0
class GameWithGui:
    def __init__(self):
        self.SQUARE_SIZE = 100
        self.RADIUS_SIZE = self.SQUARE_SIZE / 2 - 10
        self.b = Board()

        pygame.init()

        height = self.b.NUM_OF_ROWS * self.SQUARE_SIZE
        width = self.b.NUM_OF_COLS * self.SQUARE_SIZE
        size = (width, height)

        self.screen = pygame.display.set_mode(size)
        self.screen.fill('Lavender')
        self.myfont = pygame.font.SysFont("monospace", 75)

        self.draw_grid(self.b.grid)
        pygame.display.update()

    async def play(self):
        player = 1  # first player
        has_won_condition = False
        valid_input_condition = False

        while not has_won_condition:

            for event in pygame.event.get():
                self.draw_grid(self.b.grid)
                pygame.display.update()
                if event.type == pygame.QUIT:
                    # Close the program any way you want, or troll users who want to close your program.
                    raise SystemExit
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_0:
                        print("Player " + str(player) + ": Column 0")
                        if self.b.add_disc(player, 0):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_1:
                        print("Player " + str(player) + ": Column 1")
                        if self.b.add_disc(player, 1):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_2:
                        print("Player " + str(player) + ": Column 2")
                        if self.b.add_disc(player, 2):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_3:
                        print("Player " + str(player) + ": Column 3")
                        if self.b.add_disc(player, 3):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_4:
                        print("Player " + str(player) + ": Column 4")
                        if self.b.add_disc(player, 4):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_5:
                        print("Player " + str(player) + ": Column 5")
                        if self.b.add_disc(player, 5):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]
                    elif event.key == pygame.K_6:
                        print("Player " + str(player) + ": Column 6")
                        if self.b.add_disc(player, 6):
                            has_won_condition = self.b.has_won(
                                player, self.b.current_col, self.b.current_row)
                            player = [2, 1][player - 1]

        # label = self.myfont.render("Player " + str(player) + " wins!!", 1, pygame.Color("Yellow"))
        # self.screen.blit(label, (40, 10))
        pygame.time.wait(5000)

    def draw_grid(self, grid):
        # print(self.b.__repr__())
        for i in range(7):
            text = self.myfont.render(str(i), True, pygame.Color("White"),
                                      pygame.Color("Black"))
            self.screen.blit(text, (100 * i, 0))
        for row in range(self.b.NUM_OF_ROWS):
            for col in range(self.b.NUM_OF_COLS):
                pygame.draw.rect(
                    self.screen, pygame.Color('Black'),
                    (col * self.SQUARE_SIZE, row * self.SQUARE_SIZE,
                     self.SQUARE_SIZE, self.SQUARE_SIZE), 10)

                if grid[row][col] == 2:
                    pygame.draw.circle(self.screen, pygame.Color('Red'),
                                       (col * self.SQUARE_SIZE + 50,
                                        row * self.SQUARE_SIZE + 50),
                                       self.RADIUS_SIZE)
                elif grid[row][col] == 1:
                    pygame.draw.circle(self.screen, pygame.Color('Blue'),
                                       (col * self.SQUARE_SIZE + 50,
                                        row * self.SQUARE_SIZE + 50),
                                       self.RADIUS_SIZE)
Exemplo n.º 16
0
 def __init__(self):
     logging.basicConfig(format="%(levelname)s: %(message)s",
                         level=logging.INFO)
     self.b = Board()
Exemplo n.º 17
0
def test__check_diagonal_left():
    b = Board()
    player = 1
    assert b._check_diagonal_left(player, 3, 2) is False
    assert b._check_diagonal_left(player, 2, 3) is False
    assert b._check_diagonal_left(player, 1, 4) is False
    assert b._check_diagonal_left(player, 0, 5) is False
    assert b.add_disc(player, 3)
    assert b.add_disc(player, 3)
    assert b.add_disc(player, 3)
    assert b.add_disc(player, 2)
    assert b.add_disc(player, 2)
    assert b.add_disc(player, 1)
    player = 2
    assert b.add_disc(player, 3)
    assert b.add_disc(player, 2)
    assert b.add_disc(player, 1)
    assert b.add_disc(player, 0)
    assert b._check_diagonal_left(player, 3, 2)
    assert b._check_diagonal_left(player, 2, 3)
    assert b._check_diagonal_left(player, 1, 4)
    assert b._check_diagonal_left(player, 0, 5)
Exemplo n.º 18
0
def test__check_horizontal():
    b = Board()
    player = 1
    assert b._check_horizontal(player, 3, 5) is False
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 1)
    assert b._check_horizontal(player, 1, 5) is False
    assert b.add_disc(player, 2)
    assert b.add_disc(player, 3)
    assert b._check_horizontal(player, 3, 5)
    player = 2
    assert b.add_disc(player, 0)
    assert b.add_disc(player, 1)
    assert b._check_horizontal(player, 1, 4) is False
    assert b.add_disc(player, 2)
    assert b.add_disc(player, 3)
    assert b._check_horizontal(player, 3, 4)
    b1 = Board()
    assert b1._check_horizontal(player, 3, 5) is False
    assert b1.add_disc(player, 6)
    assert b1.add_disc(player, 5)
    assert b1.add_disc(player, 4)
    assert b1.add_disc(player, 3)
    assert b1._check_horizontal(player, 3, 5)
Exemplo n.º 19
0
	def on_init(self) -> Board:
		board = Board()
		board.apply_pop(get_random_pop(board.matrix))
		board.apply_pop(get_random_pop(board.matrix))
		return board
Exemplo n.º 20
0
 def on_suggest_action(self, board: Board) -> Action:
     options = board.get_options()
     index = np.random.randint(0, len(options))
     return options[index]
Exemplo n.º 21
0
	def __init__(self, board):
		if isinstance(board, Board):
			self.board = board
		else:
			self.board = Board(board)