# Botpot overview

Botpot is a platform for bots to compete in games and competitions.

## Intro to Botpot

On the Botpot platform, users can build bots that can compete in games against other bots. Bots are  computer programs that calculate what actions to make in a game. We support many flavors of games, from card games to computer games to board games. We've standardized the way we represent these games in an object we call the `game state`, which bots can use to understand what is happening in the game to determine what actions to take. Botpot aims to make it simple to write bots by extracting out the complexity so our users can focus on writing the logic for the bot. With our in-browser IDE, users can create bots from our templates and immediately get started with a runnable bot that can complete a game and start their development process.


# Get action

The `Get Action` function is what a user will code up, which dictates how the bot will run.&#x20;

The function takes `game state` and `api` as inputs. The game state describes the state of the world. The API object contains helpful methods to make coding easier.

The function should return an `action object`, which is the action the bot wishes to perform on its turn.


# Get action: game state

On the bot's turn, it receives a game state, which contains all the information the bot needs to understand the state of the game in order to determine the action to take. We use [protocol buffer](https://protobuf.dev/) to document the game state schema.&#x20;

## Whose turn is it?

Each game has a list of participating bots `[player0, player1, ..., playerN]`. Which bot should make the next move is based on `player_turn_idx`. When `player_turn_idx = 0`, then the first player bot will calculate and submit its move, which is all handled automatically by the server. All game states on Botpot will contain a `player_turn_idx` that the bot can use to deduce which player it is playing.

### Examples

#### [Tic-Tac-Toe](https://botpot.ai/game/tictactoe)

The bot needs to know the values of the 9 squares, and whether the bot is playing circles or crosses. If `state.player_turn_idx` is `0`, then the bot is playing circles. Otherwise, it is playing crosses. The protocol buffer schema for the Tic-Tac-Toe game state looks like

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  /*
  Array of size 9 initialized to -1, representing an empty 3 by 3 board.
  The values of board can be -1, 0, or 1. 
  Placing a piece in index x will set the value of board[x] to the player's index.
  Array is row major order: index 0 is top left, index 2 is top right, index 6 is 
  bottom left, and index 8 is bottom right.
  */
  repeated int32 board = 2;
}
```

The Tic-Tac-Toe bot below illustrates how one can use these fields to compute the next action.

{% tabs %}
{% tab title="python" %}

```python
def get_action(state, api):
    my_piece = state['player_turn_idx']
    board = state['board']
    # check if the top row is filled with my piece
    if board[0] == my_piece and board[1] == my_piece:
        # ...place_piece on the top right
```

{% endtab %}

{% tab title="javascript" %}

```javascript
function getAction({state, api}) {
    let myPiece = state['player_turn_idx'];
    let board = state['board'];
    // check if the top row is filled with my piece
    if (board[0] === my_piece && board[1] === my_piece)
        // ...place_piece on the top right
}
```

{% endtab %}
{% endtabs %}

#### [Reversi](https://botpot.ai/game/reversi)

In Reversi, the bot needs to know the values of the 64 squares. We can use a similar schema as Tic-Tac-Toe. To make it easier to code the bot, we also pre-computed a list of all the valid moves that a bot can make. The bot can select from one of the valid moves to return as its action.&#x20;

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1    
  int32 player_turn_idx = 1;

  // An array of size 64 stored in row major order, so index 0 is top left, 
  // index 7 is top right, index 56 is bottom left, and index 63 is bottom right.
  // Values can be -1, 0, or 1, where -1 represents an empty spot, 0 is a piece
  // made by player_idx 0 and 1 is a piece made by player_idx 1.
  repeated int32 game_board = 2;

  // Precomputed array of all the valid moves. Players should select an index from
  // this list to make a move. 
  repeated ValidMove valid_moves = 3;
}
```

```protobuf
// The 8 directions to flip opponent disks.
enum direction {
  ABOVE = 0;
  BELOW = 1;
  LEFT = 2;
  RIGHT = 3;
  ABOVE_LEFT = 4;
  ABOVE_RIGHT = 5;
  BELOW_LEFT = 6;
  BELOW_RIGHT = 7;
}

/*
Each ValidMove is an index that the current player can place his piece on.
It also contains information about the all directions that will flip the 
opponent pieces. 
*/
message ValidMove {
  int32 index = 1;
  repeated direction valid_directions = 2;
}
```

## Different game perspectives

![Fig. 1: different bots see a different view of the game.](https://3691668748-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpNqFLvMdyPuc81kfsqTa%2Fuploads%2F4omnGIj4mzApJ4aCAzLW%2Fimage.png?alt=media\&token=c58a3f80-bbea-4daa-a10d-cb0d26b8c530)

Some games such as Chess, Tic-Tac-Toe, and Checkers are perfect information, where there is no hidden information so all the bots know everything about the game. On the other hand, Texas Hold'em is an example of an imperfect information game. As shown in Fig. 1, our server stores a game state from the global perspective with no hidden information. This global game state is used to derive what each bot is supposed to see. Bot 1 is only sent its cards, which is a pair of K's. Similarly, Bot 2 is sent its pair of 3's. Both bots can also see the shared cards in the middle.&#x20;

When a bot makes an action, the server can compute the new global game state and the bots' perspective game states.&#x20;

### Examples

#### [Battleship](https://botpot.ai/game/battleship)

```protobuf
message State {
  enum Phase {
    PLACE_SHIP = 0;
    FIRE_SHOT = 1;
  }

  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // This will be length 2 for the two players. The player can only see their own ships
  // but will have information on the other fields such as the shots and sunken ships.
  repeated PlayerInfo player_info = 2;

  // The game starts off with PLACE_SHIP phase. Once both players placed their ships,
  // the phase changes to FIRE_SHOT until one of the player's ships are all sunk.
  Phase phase = 3;
}
```


# Get action: API object

The API object for the `get_action` method includes:

`api.data`

This is data that users can use to store information between different get\_action calls. This can be helpful for games where history matters. For example, in a previous state, the bot may have seen the opponent in location (3, 2) but is no longer visible in this current state, one could store this coordinate in `api.data.previous = (3, 2)`

`api.log`

Use this function to log strings for easier debugging. Example usage: `api.log("Debugging")`


# Get action: action object

On its turn, the bot will need to perform an action.&#x20;

`Action Object` is the output of the bot's `Get Action` function. The `Action Object` has two fields: `action` and `params`. The `params` are the parameters needed to perform the action.&#x20;

## Examples

### Tic-Tac-Toe

A player can make only one type of action in this game: place a piece in one of the 9 squares. The action object will look something like

```json
{
    "action": "place_piece",
    "params": {
        "index": 3
    }
}
```

When the bot `Get Action` function returns the above object, the game server will attempt to place a piece at index 3 for the `player_turn_idx` that is making the move.

### Battleship

A player can make two types of actions in this game: `placing ships` and `firing shots`. During the `PLACE_SHIP` phase, the action object should look like

```json
{
    "action": "place_ships",
    "params": {
        "ships": [
            // destroyer
            {"x": 3, "y": 4}, 
            {"x": 3, "y": 5},
            // submarine
            {"x": 7, "y": 4}, 
            {"x": 8, "y": 4}, 
            {"x": 9, "y": 4},
            //...other ships
        ]
    }
}
```

During the `FIRE_SHOT` phase, the action object should look like

```
{
    "action": "fire_shot",
    "params": {
        "x": 3,
        "y": 5
    }
}
```

## Passing a turn

The bot must return an action during its turn. If the function returns `null` or fails to return an object, it will be forfeit the game. For games where it is valid to pass a turn, the action schema should include an explicit action to do so. The action object for this might look like

```
{
    "action": "pass_turn"
}
```


# Specialized game concepts

While all games have `game states` and `actions`, some games are more specialized and have additional fields or concepts that users should leverage to build the best bot.


# Get action: ref data

Reference data is data that doesn't change throughout the game, but is needed for the bot to calculate its actions.&#x20;

## Examples

### Wordle

<figure><img src="https://3691668748-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpNqFLvMdyPuc81kfsqTa%2Fuploads%2FDoqhje53sggIrW2Hn7ES%2Fimage.png?alt=media&amp;token=e22547c8-5f00-4eaa-b181-b438b1a8a670" alt="" width="186"><figcaption><p>Wordle game</p></figcaption></figure>

In a word game like Wordle where the bot needs to guess a 5 letter word, the bot needs to know a list of all 5 letter words. Here is [ref\_data.json](https://d22cv6d99w4a17.cloudfront.net/wordle/ref_data.json) for Wordle. The proto schema for it is:

```protobuf
message refData {
  repeated string words = 1;
}
```

The bot can access ref\_data by:

{% tabs %}
{% tab title="Python" %}

```python
def get_action(state, ref_data, api):
    words = ref_data["words"]
    # ... Pick from one of these words
```

{% endtab %}

{% tab title="Javascript" %}

```javascript
function getAction({state, refData, api}) {
  let words = refData["words"];
  // ... Pick from one of these words
}
```

{% endtab %}
{% endtabs %}

### Risk

<figure><img src="https://3691668748-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpNqFLvMdyPuc81kfsqTa%2Fuploads%2FT3qz4fvn5T6VOeoni92Q%2Fsmallearth.png?alt=media&amp;token=d1fdf4f7-07c3-4cba-aa77-802a06ae3681" alt=""><figcaption><p>A game involving a map</p></figcaption></figure>

This game has a more complex example of [ref\_data.json](https://d22cv6d99w4a17.cloudfront.net/risk/ref_data.json). This map does not change throughout the game. A bot needs to know which areas are connected to determine what actions it should take.&#x20;


# Game settings

Game settings change the way the game is initialized. `Player count` is a setting that all games have. Two player games such as *Tic-Tac-Toe* always have two players, while some multiple player games like *Uno* supports between two to four players.&#x20;

Some games have additional game settings. In *Dots and Boxes*, there is a `Size` setting that takes on the values `2x2`, `3x3`, `7x7`, and `Any`. Bots do not have access to the game settings field because they can be implicitly derived from the game state. In this *Dots and Boxes* example, the game setting gets converted into the `board_width` and the `board_height` fields.&#x20;

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // The array is stored in row major order, so index 0 is the top left and 
  // last index is the bottom right. In a size 2x2 board, index 1 is the 
  // top right board. 
  repeated Box board = 2;

  // Number of horizontal boxes in the grid
  int32 board_width = 3;

  // Number of vertical boxes in the grid
  int32 board_height = 4;
}
```


# Botpot architecture

<figure><img src="https://3691668748-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FpNqFLvMdyPuc81kfsqTa%2Fuploads%2F3JXR411XWAgPXpDv8rpI%2Fimage.png?alt=media&amp;token=68301ccc-a5cc-4701-97fc-797e8d42eb74" alt=""><figcaption><p>Fig 1: botpot architecture</p></figcaption></figure>

Fig. 1 shows the high level architecture of how the platform works.&#x20;

1. The server sends the game state to all the participating bots.
2. When it is Bot 1's turn to make a move, Bot 1 will calculate an action to make based on the game state that it has received.
3. Bot 1 decides to place his circle in the top left of the board. The action is sent to the server.
4. The server updates the game state based on this action.
5. The server resends the game state to all the bots, and this is repeated until the game is over.


# Creating your first bot

Select a game from [Botpot](https://botpot.ai/games).&#x20;

Select the language you want to code your bot in. We provide working bot samples to kickstart the process.&#x20;


# Understanding game logic

The game logic is code running on the backend that dictates how the game will run. Understanding the game logic is not strictly necessary for building bots, but it can be helpful for users who want to understand the nuances of how the game works when it is not adequetly described in the game description.

Game logic consists of these components

* game initialization
* what happens when an action is performed?
* when does the game end and who is the winner?

## Game initialization

The `init_game(game_settings)` method is called at the beginning of a game and returns a newly initialized game state. It determines who makes the first move, by specifying the `player_turn_idx`. Some games support different settings, such as board size or player count, and the initialization can take those settings into account.

## Performing the action

Bots return an action object on their turns. The action object is the input for these game logic methods. Given the current game state, the game logic calculates what the new game state is when the action is performed.

Games with multiple actions need to implement a method for each action.

### Example

Tictactoe has a single action: placing a piece at some index. The Tic-Tac-Toe game logic has a method `place_piece(state, index)` that returns a new state after the piece has been places in that index.

## Determining the winner

After each action, the game logic checks if the game has finished given the new game state. For multi-player games, the supported game results are&#x20;

* Someone has won
* Game ended with a draw
* Game is on-going

Single player game results also include things like the `score` of the game.&#x20;


# Explore game documentations


# Tic-Tac-Toe

## Game logic

<details>

<summary>Game Logic code</summary>

<pre class="language-python"><code class="lang-python"><strong>def init_game(game_settings):
</strong>    state = {
        "player_turn_idx": 0,
        "board": [-1, -1, -1, -1, -1, -1, -1, -1, -1]
        }
    return state

def place_piece(state, index):
    if index &#x3C; 0 or index > 8:
        raise InvalidActionError("Index out of bound")
    if state["board"][index] != -1:
        raise InvalidActionError("Someone already placed a piece here")
    state["board"][index] = state["player_turn_idx"]
    state["player_turn_idx"] = (state["player_turn_idx"] + 1) % 2

    return state

def get_game_result(state):
    if __has_line(state, 0):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if __has_line(state, 1):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    for value in state["board"]:
        if value == -1:
            return {
                "game_result": "NoWinnerYet"
            }
    return {
        "game_result": "Draw"
    }

def __has_line(state, value):
    for i in range(0, 3):
        if state["board"][i*3] == value and state["board"][i*3 + 1] == value and state["board"][i*3 + 2] == value:
            return True
        if state["board"][i] == value and state["board"][i + 3] == value and state["board"][i + 6] == value:
            return True
    if state["board"][0] == value and state["board"][4] == value and state["board"][8] == value:
        return True
    if state["board"][2] == value and state["board"][4] == value and state["board"][6] == value:
        return True
    return False
</code></pre>

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  /*
  Array of size 9 initialized to -1, representing an empty 3 by 3 board.
  The values of board can be -1, 0, or 1. 
  Placing a piece in index x will set the value of board[x] to the player's index.
  Array is row major order: index 0 is top left, index 2 is top right, index 6 is 
  bottom left, and index 8 is bottom right.
  */
  repeated int32 board = 2;
}
```

## Action schema

```javascript
place_piece(int index)
```

[Start building now](https://botpot.ai/game/tictactoe)


# Quoridor

## Game logic

<details>

<summary>Game Logic code</summary>

```python
BOARD_WIDTH = 9
BOARD_HEIGHT = 9

def init_game(game_settings):
    position1 = {
        'row': 0, 
        'column': 4
        }
    position2 = {
        'row': BOARD_HEIGHT - 1, 
        'column': 4
        }

    state = {
        'player_turn_idx': 0,
        'player_positions': [position1, position2],
        'walls': [],
        'remaining_wall_count': [10, 10]
        }
    return state

def move_up(state):
    return __move_helper(state, __can_move_up, "up")

def move_down(state):
    return __move_helper(state, __can_move_down, "down")

def move_left(state):
    return __move_helper(state, __can_move_left, "left")

def move_right(state):
    return __move_helper(state, __can_move_right, "right")

def place_horizontal_wall(state, row, column):
    new_state = __place_wall_helper(state, row, column, True)
    return new_state

def place_vertical_wall(state, row, column):
    new_state = __place_wall_helper(state, row, column, False)
    return new_state

def get_game_result(state):
    if state['player_positions'][0]['row'] == BOARD_HEIGHT - 1:
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if state['player_positions'][1]['row'] == 0:
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    return {
        "game_result": "NoWinnerYet"
    }

def __place_wall_helper(state, row, column, is_horizontal):
    player_idx = state['player_turn_idx']
    if state['remaining_wall_count'][player_idx] <= 0:
        raise InvalidActionError("no more walls to place")
    if row < 0 or row >= BOARD_HEIGHT - 1 or \
    column < 0 or column >= BOARD_WIDTH - 1:
        raise InvalidActionError("can't place wall there")
    for w in state['walls']:
        if w['row'] == row and w['column'] == column and w['is_horizontal'] != is_horizontal:
            raise InvalidActionError("overlapping with another wall")
        if w['is_horizontal'] and is_horizontal and w['row'] == row:
            if abs(w['column'] - column) <= 1:
                raise InvalidActionError("overlapping with another wall")
        if not w['is_horizontal'] and not is_horizontal and w['column'] == column:
            if abs(w['row'] - row) <= 1:
                raise InvalidActionError("overlapping with another wall")

    state['walls'].append({
        'row': row, 
        'column': column, 
        'is_horizontal': is_horizontal
        })

    if not __has_path_to(state, BOARD_HEIGHT - 1, state['player_positions'][0]):
        state['walls'].pop() # Just clean up so we don't modify the state accidentally
        raise InvalidActionError("wall seals the path to the top")
    if not __has_path_to(state, 0, state['player_positions'][1]):
        state['walls'].pop() # Just clean up so we don't modify the state accidentally
        raise InvalidActionError("wall seals the path to the bottom")

    state["player_turn_idx"] = (state["player_turn_idx"] + 1) % 2
    state['remaining_wall_count'][player_idx] -= 1
    return state

def __move_helper(state, direction_func, direction_str):
    player_idx = state['player_turn_idx']
    other_player_idx = (player_idx + 1) % 2
    player_position = state['player_positions'][player_idx]
    other_player_position = state['player_positions'][other_player_idx]
    wall_set = set([(w['row'], w['column'], w['is_horizontal']) for w in state['walls']])
    
    move_coordinate = direction_func(wall_set, player_position['row'], player_position['column'])
    if not move_coordinate:
        raise InvalidActionError("cannot move " + direction_str)
    if move_coordinate == (other_player_position['row'], other_player_position['column']):
        move_more = direction_func(wall_set, move_coordinate[0], move_coordinate[1])
        if not move_more:
            raise InvalidActionError("cannot move " + direction_str + " over other player")
        state['player_positions'][player_idx]['row'] = move_more[0]
        state['player_positions'][player_idx]['column'] = move_more[1]
    else:
        state['player_positions'][player_idx]['row'] = move_coordinate[0]
        state['player_positions'][player_idx]['column'] = move_coordinate[1]
    state['player_turn_idx'] = other_player_idx
    return state

def __can_move_up(wall_set, r, c):
    if (r, c, True) not in wall_set and \
        (r, c - 1, True) not in wall_set and \
            r + 1 < BOARD_HEIGHT:
        return (r + 1, c)
    return None

def __can_move_down(wall_set, r, c):
    if (r - 1, c, True) not in wall_set and \
            (r - 1, c - 1, True) not in wall_set and \
            r - 1 >= 0:
        return (r - 1, c)
    return None

def __can_move_left(wall_set, r, c):
    if (r, c - 1, False) not in wall_set and \
            (r - 1, c - 1, False) not in wall_set and \
            c - 1 >= 0:
        return (r, c - 1)
    return None

def __can_move_right(wall_set, r, c):
    if (r, c, False) not in wall_set and \
            (r - 1, c, False) not in wall_set and \
            c + 1 < BOARD_WIDTH:
        return (r, c + 1)
    return None

def __has_path_to(state, target_row, position):
    """
    Does a dfs search from position to target. return true if there is a path
    """
    visited = set()
    stack = [(position['row'], position['column'])]
    wall_set = set([(w['row'], w['column'], w['is_horizontal']) for w in state['walls']])
    while len(stack) > 0:
        node = stack.pop()
        if node[0] == target_row:
            return True
        if node in visited:
            continue
        r, c = node
        visited.add(node)
        neighbors = [__can_move_up(wall_set, r, c), 
            __can_move_down(wall_set, r, c), 
            __can_move_right(wall_set, r, c),
            __can_move_left(wall_set, r, c)]
        for n in neighbors:
            if n:
                stack.append(n)
    return False
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // Array of player positions, of length 2
  repeated Position player_positions = 2;

  // These are the walls that have been placed on the board.
  repeated Wall walls = 3;

  // Array of length 2, storing the number of wall pieces remaining for each player
  // that can still be placed onto the board.
  repeated int32 remaining_wall_count = 4;
}
```

```protobuf
/*
Walls have a length of 2. 
A horizontal wall in <row 0, column 0> blocks player piece at both <row 0, column 0> and <row 0, column 1> from going up.
A vertical wall in <row 0, column 0> blocks player piece at both <row 0, column 0> and <row 1, column 0> from going right.
Both horizontal and vertical walls can be placed between rows 0-7 and columns 0-7 inclusive. 
*/
message Wall {
  int32 row = 1;
  int32 column = 2;
  bool is_horizontal = 3;
}
```

```protobuf
message Position {
  int32 row = 1;
  int32 column = 2;
}
```

## Action schema

```javascript
move_up()
move_down()
move_left()
move_right()
place_horizontal_wall(int row, int column)
place_vertical_wall(int row, int column)
```

[Start building now](https://botpot.ai/game/quoridor)


# Connect Four

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'player_turn_idx': 0,
        'board': [
            -1, -1, -1, -1, -1, -1, -1,  
            -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1
        ]
    }
    return state

def __index(r, c):
    return r * 7 + c

def drop_piece(state, column):
    if column < 0 or column > 7:
        raise InvalidActionError("column out of bound")

    row_to_place_disk = None
    for r in range(6):
        if state['board'][__index(r, column)] == -1:
            row_to_place_disk = r
            break  

    if row_to_place_disk is None:          
        raise InvalidActionError("column is full") 
  
    state['board'][__index(row_to_place_disk, column)] = state['player_turn_idx']       
    state["player_turn_idx"] = (state["player_turn_idx"] + 1) % 2
    return state

def get_game_result(state):
    if __has_line_horizontal(state, 0):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if __has_line_horizontal(state, 1):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }

    if __has_line_vertical(state, 0):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if __has_line_vertical(state, 1):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }

    if __has_line_diagonal(state, 0):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if __has_line_diagonal(state, 1):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }

    for value in state['board']:
        if value == -1:
            return {
                "game_result": "NoWinnerYet"
            }
    return {
        "game_result": "Draw"
    }

def __has_line_horizontal(state, value):
    board = state['board']
    #check horizontal locations for win
    for c in range(7 - 3):
        for r in range(6):
            if board[__index(r, c)] == value and board[__index(r, c + 1)] == value and board[__index(r, c + 2)] == value and board[__index(r, c + 3)] == value:
                return True
    return False 

def __has_line_vertical(state, value):
    board = state['board']
    #check vertical locations for win 
    for c in range(7):
        for r in range(6 - 3):
            if board[__index(r, c)] == value and board[__index(1 + r, c)] == value and board[__index(2 + r, c)] == value and board[__index(3 + r, c)] == value:
                return True
    return False 

def __has_line_diagonal(state, value):
    board = state['board']
    #check negatively sloped diagonals 
    for c in range(7 - 3):
        for r in range (3, 6):
            if board[__index(r, c)] == value and board[__index(r - 1, c + 1)] == value and board[__index(r - 2, c + 2)] == value and board[__index(r - 3, c + 3)] == value:
                return True

    #check positively sloped diagonals 
    for c in range (7 - 3):
        for r in range(6 - 3):
            if board[__index(r, c)] == value and board[__index(r + 1, c + 1)] == value and board[__index(r + 2, c + 2)] == value and board[__index(r + 3, c + 3)] == value:
                return True            
    return False
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  /*
  Array of size 42 initialized to -1, representing an empty 6 by 7 board.
  The values of board can be -1, 0, or 1. 
  Placing a piece in index x will set the value of board[x] to the player's index.
  Array is row major order from the bottom up: 
  • index 0 is bottom left
  • index 6 is bottom right
  • index 35 is top left
  • index 41 is top right
  */
  repeated int32 board = 2;
}
```

## Action schema

```javascript
drop_piece(int column)
```

[Start building now](https://botpot.ai/game/connectfour)


# Battleship

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'phase': "PLACE_SHIP",
        'player_info': [
            {
                "ships": [],
                "sunken_ship_sizes": [],
                "shots_at_this_player": []
            },
            {
                "ships": [],
                "sunken_ship_sizes": [],
                "shots_at_this_player": []
            }
        ],
        'player_turn_idx': 0
        }
    return state

def place_ships(state, ships):
    """
    <ships> should be an array of 2+3+3+4+5 = 17 coordinates expressed as object {'x': x, 'y': y}. Elements 0~1 represent the first ship of size 2. Elements 2~4 represent the second ship of size 3, etc..., until elements 12~16 represent the fifth ship of size 5.
    """
    BOARD_WIDTH = 10
    BOARD_HEIGHT = 10

    ships = [(int(coord["x"]), int(coord["y"])) for coord in ships]
    player_idx = state["player_turn_idx"]
    other_player_idx = (player_idx + 1) % 2

    if len(state['player_info'][player_idx]['ships']) > 0:
        raise InvalidActionError("Ships already placed.")
    if __are_ships_valid(ships):
        __place_ships(state, player_idx, ships)

    
    if len(state['player_info'][other_player_idx]['ships']) > 0:
        state['phase'] = "FIRE_SHOT"

    state["player_turn_idx"] = other_player_idx
    return state

def fire_shot(state, x, y):
    BOARD_WIDTH = 10
    BOARD_HEIGHT = 10
    x = int(x)
    y = int(y)
    if state['phase'] == "PLACE_SHIP":
        raise InvalidActionError("Still waiting for ships to be placed.")
    if x < 0 or x >= BOARD_WIDTH or y < 0 or y >= BOARD_HEIGHT:
        raise InvalidActionError("Out of bound.")

    player_idx = state["player_turn_idx"]
    other_player_idx = (player_idx + 1) % 2

    other_player_info = state["player_info"][other_player_idx]
    
    target_positions = [(pos['x'], pos['y']) for ship in other_player_info['ships'] for pos in ship['positions']]
    shots_fired = set([(shot['x'], shot['y']) for shot in other_player_info['shots_at_this_player']])

    if (x, y) in shots_fired:
        raise InvalidActionError("Already placed a shot at this location.")
    if (x, y) in target_positions:
        did_hit = True
    else:
        did_hit = False

    state['player_info'][other_player_idx]['shots_at_this_player'].append({
        'x': x,
        'y': y, 
        'did_hit': did_hit
        })
    shots_fired.add((x, y))
    state['player_info'][other_player_idx]['sunken_ship_sizes'] = __get_sunken_ships(shots_fired, state['player_info'][other_player_idx]['ships'])
    state["player_turn_idx"] = other_player_idx
    return state

def __get_sunken_ships(shots, ships):
    sunken_ships = []
    for ship in ships:
        is_sunk = True
        for pos in ship['positions']:
            if (pos['x'], pos['y']) not in shots:
                is_sunk = False
                continue
        if is_sunk:
            sunken_ships.append(len(ship['positions']))
    return sunken_ships


def __place_ships(state, player_idx, ships):
    ship_models = [__make_ship_model(ships[0:2]), __make_ship_model(ships[2:5]), __make_ship_model(ships[5:8]
        ), __make_ship_model(ships[8:12]), __make_ship_model(ships[12:17])]
    state['player_info'][player_idx]['ships'] = ship_models

def __make_ship_model(coordinates):
    ship_positions = [{'x': coord[0], 'y': coord[1]} for coord in coordinates]
    return {'positions': ship_positions}

def __are_ships_valid(ships):
    if len(ships) != 17:
        raise InvalidActionError("Ships should be a list of 17 coordinates representing ships of sizes 2, 3, 3, 4, 5.")
    if len(set(ships)) != 17:
        raise InvalidActionError("Ships are overlapping.")
    if (__is_valid_ship(ships[0:2]) and 
        __is_valid_ship(ships[2:5]) and 
        __is_valid_ship(ships[5:8]) and 
        __is_valid_ship(ships[8:12]) and 
        __is_valid_ship(ships[12:17])):
        return True
    return False

def __is_valid_ship(ship):
    """
    Verify if <ship> is a list of adjacent tuples in a straight line that are within the bounds of the board.
    """
    BOARD_WIDTH = 10
    BOARD_HEIGHT = 10
    for x, y in ship:
        if x < 0 or x >= BOARD_WIDTH or y < 0 or y >= BOARD_HEIGHT:
            raise InvalidActionError("Out of bound.")
    xs = [coordinate[0] for coordinate in ship]
    ys = [coordinate[1] for coordinate in ship]
    diff_x = max(xs) - min(xs)
    diff_y = max(ys) - min(ys)
    if diff_x == 0: # vertical ship
        adjacent_coordinates = sorted(ys)
    elif diff_y == 0:
        adjacent_coordinates = sorted(xs)
    else:
        raise InvalidActionError("Ship has to be vertical or horizontal.")
    for i in range(len(adjacent_coordinates) - 1):
        if adjacent_coordinates[i+1] - adjacent_coordinates[i] != 1:
            raise InvalidActionError("Ship coordinates aren't consecutive.")
    return True

def get_game_result(state):
    if len(state['player_info'][0]['sunken_ship_sizes']) == 5:
        if len(state['player_info'][1]['sunken_ship_sizes']) == 5:
            return {
                "game_result": "Draw"
            }
        else:
            return {
                "game_result": "Winner",
                "winner_idx": 1
            }
    elif len(state['player_info'][1]['sunken_ship_sizes']) == 5 and state['player_turn_idx'] == 0:
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    return {
        "game_result": "NoWinnerYet"
    }

def get_player_states(state):
    player_states = []
    for i in range(2):
        player_info =  [
            {
                "ships": state['player_info'][0]["ships"] if i == 0 else [],
                "sunken_ship_sizes": state['player_info'][0]["sunken_ship_sizes"],
                "shots_at_this_player": state['player_info'][0]["shots_at_this_player"]
            },
            {
                "ships": state['player_info'][1]["ships"] if i == 1 else [],
                "sunken_ship_sizes": state['player_info'][1]["sunken_ship_sizes"],
                "shots_at_this_player": state['player_info'][1]["shots_at_this_player"]
            }
        ]
        player_states.append({
            'player_info': player_info,
            'phase': state['phase'],
            'player_turn_idx': state['player_turn_idx']
            })
    return player_states
```

</details>

## Game state schema

```protobuf
message State {
  enum Phase {
    PLACE_SHIP = 0;
    FIRE_SHOT = 1;
  }

  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // This will be length 2 for the two players. The player can only see their own ships
  // but will have information on the other fields such as the shots and sunken ships.
  repeated PlayerInfo player_info = 2;

  // The game starts off with PLACE_SHIP phase. Once both players placed their ships,
  // the phase changes to FIRE_SHOT until one of the player's ships are all sunk.
  Phase phase = 3;
}
```

```protobuf
message PlayerInfo {
  // Initially length 0. Once the ships are placed, this will be length 5.
  // The ships will have Coordinate lengths of 2, 3, 3, 4, 5.
  repeated Ship ships = 1;

  // Opponents fire shots at this player. Once a ship is sunk, it gets added
  // to this list, which stores the length of the ship that was sunk. This 
  // array will be size 0 to 5, and the game is over when all ships are sunk.
  repeated int32 sunken_ship_sizes = 2;

  // Stores all the shots at this player.
  repeated Shot shots_at_this_player = 3;
}
```

```protobuf
message Ship {
  repeated Coordinate positions = 1;
}
```

```protobuf
message Shot {
  int32 x = 1;
  int32 y = 2;
  bool did_hit = 3;
}
```

```protobuf
message Coordinate {
  int32 x = 1;
  int32 y = 2;
}
```

## Action schema

```javascript
/* 
Takes in a list of length 2+3+3+4+5 = 17 coordinates
Elements 0~1 represent the first ship of size 2. 
Elements 2~4 represent the second ship of size 3, etc..., 
until elements 12~16 represent the fifth ship of size 5.
*/
place_ships(list<coordinate> ships)

// The action needed for the second phase of the game
fire_shot(int x, int y)
```

[Start building now](https://botpot.ai/game/battleship)


# Virus War

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
MOVES_PER_TURN = 3
def init_game(game_settings):
    size = game_settings.get('Size')
    if size == 'Any':
        size = random.choice(['7x7', '11x11'])
    if size == '7x7':
        width = 7
        height = 7
        initial_virus_positions = [(1, 1), (5, 5)]
    elif size == '11x11':
        width = 11
        height = 11
        initial_virus_positions = [(2, 2), (8, 8)]

    viruses = [
        {
            'x': initial_virus_positions[0][0], 
            'y': initial_virus_positions[0][1], 
            'player_idx': 0, 
            'is_zombie': False
        },
        {
            'x': initial_virus_positions[1][0], 
            'y': initial_virus_positions[1][1], 
            'player_idx': 1, 
            'is_zombie': False
        }]

    state = {
        'player1_required_move_count': 1,
        'player2_required_move_count': 0,
        'viruses': viruses,
        'player_turn_idx': 0,
        'spots_visible_to_player1': __get_visible_spots(viruses, 0, width, height),
        'spots_visible_to_player2': __get_visible_spots(viruses, 1, width, height),
        'board_width': width,
        'board_height': height
        }
    return state

def move(state, x, y):
    if x < 0 or x >= state["board_width"] or y < 0 or y >= state["board_height"]:
        raise InvalidActionError("Input out of bound.")
    if state['player_turn_idx'] == 0:
        required_move_count = state['player1_required_move_count']
        spots_visible = state['spots_visible_to_player1']
    else:
        required_move_count = state['player2_required_move_count']
        spots_visible = state['spots_visible_to_player2']

    found = False
    for v in spots_visible:
        if x == v['x'] and y == v['y']:
            found = True
            break
    if not found:
        raise InvalidActionError("This is not a visible spot you can move to.")

    player_idx = state['player_turn_idx']
    new_viruses = []
    is_new_virus = True
    for v in state['viruses']:
        if x == v['x'] and y == v['y']:
            is_new_virus = False
            if v['is_zombie']:
                raise InvalidActionError("This is overlapping with a zombie virus.")
            if v['player_idx'] == player_idx:
                raise InvalidActionError( "This is overlapping with your own live virus.")
            else:
                new_viruses.append(
                    {
                        'x': x, 
                        'y': y, 
                        'player_idx': player_idx, 
                        'is_zombie': True
                    })
        else:
            new_viruses.append(v)
    if is_new_virus:
        new_viruses.append({
            'x': x, 
            'y': y, 
            'player_idx': player_idx, 
            'is_zombie': False
            })

    state['viruses'] = new_viruses
    state['spots_visible_to_player1'] = __get_visible_spots(
        state['viruses'], 0, state['board_width'], state['board_height'])
    state['spots_visible_to_player2'] = __get_visible_spots(
        state['viruses'], 1, state['board_width'], state['board_height'])

    if player_idx == 0:
        if state['player1_required_move_count'] == 1:
            state['player2_required_move_count'] = MOVES_PER_TURN
            state['player_turn_idx'] = 1
        state['player1_required_move_count'] = state['player1_required_move_count'] - 1
    else:
        if state['player2_required_move_count'] == 1:
            state['player1_required_move_count'] = MOVES_PER_TURN
            state['player_turn_idx'] = 0
        state['player2_required_move_count'] = state['player2_required_move_count'] - 1
    
    return state

def __get_visible_spots(viruses, player_idx, board_width, board_height):
    """
    Only spots that are adjacent to live viruses, or spots that are adjacent to zombie viruses that are connected to live viruses via other zombie viruses are visible. 
    Zombie viruses themselves are also visible, even if they aren't connected.
    Return those spots.
    """
    position_to_virus_map = {}
    positions_connected_to_live = set()
    zombie_positions = []
    for v in viruses:
        position = (v['x'], v['y'])
        position_to_virus_map[position] = v
        if v['player_idx'] == player_idx:
            if v['is_zombie']:
                zombie_positions.append(position)
            else:
                positions_connected_to_live.add(position)
    connected_zombies = __get_zombies_connected_to_live_helper(positions_connected_to_live, zombie_positions)

    for cz in connected_zombies:
        positions_connected_to_live.add(cz)

    visible_spots = set()
    for x, y in positions_connected_to_live:
        for offset_x in range(-1, 2):
            for offset_y in range(-1, 2):
                new_x = x + offset_x
                new_y = y + offset_y
                if new_x < 0 or new_x >= board_width or new_y < 0 or new_y >= board_height:
                        continue
                visible_spots.add((new_x, new_y))
    for x, y in zombie_positions:
        visible_spots.add((x, y))

    # Convert visible spots into virus model. Empty spots without a virus will be represented as a virus with player_idx = -1.
    visible_viruses = []
    for p in visible_spots:
        if p in position_to_virus_map:
            visible_viruses.append(position_to_virus_map[p])
        else:
            visible_viruses.append({
                'x': p[0], 
                'y': p[1], 
                'player_idx': -1,
                'is_zombie': False
            })
    return visible_viruses

def __get_zombies_connected_to_live_helper(positions_connected_to_live, zombie_positions):
    seen = set()
    zombies_connected = set()
    for p in zombie_positions:
        if p in seen:
            continue

        # A DFS for each zombie group to see if they are connected to live viruses at some point
        current_zombie_group = set([p])
        is_group_connected_to_live = False
        stack = [p]

        while stack:
            current = stack.pop()
            seen.add(current)
            if current in positions_connected_to_live:
                is_group_connected_to_live = True
                continue
            current_zombie_group.add(current)
            for offset_x in range(-1, 2):
                for offset_y in range(-1, 2):
                    neighbor = (current[0] + offset_x, current[1] + offset_y)
                    if neighbor in seen or (neighbor not in positions_connected_to_live and neighbor not in zombie_positions):
                        continue
                    stack.append(neighbor)
        if is_group_connected_to_live:
            for z in current_zombie_group:
                zombies_connected.add(z)
    return zombies_connected

def get_game_result(state):
    if state['player1_required_move_count'] > 0:
        for v in state['spots_visible_to_player1']:
            if v['player_idx'] == -1 or (v['player_idx'] == 1 and not v['is_zombie']):
                return {
                    "game_result": "NoWinnerYet"
                }
        return {
                "game_result": "Winner",
                "winner_idx": 1
            }
    else:
        for v in state['spots_visible_to_player2']:
            if v['player_idx'] == -1 or (v['player_idx'] == 0 and not v['is_zombie']):
                return {
                    "game_result": "NoWinnerYet"
                }
        return {
                "game_result": "Winner",
                "winner_idx": 0
            }

def get_player_states(state):
    player_states = []
    for i in range(2):
        if i == 0:
            required_move_count = state['player1_required_move_count']
            visible_viruses = state['spots_visible_to_player1']
        else:
            required_move_count = state['player2_required_move_count']
            visible_viruses = state['spots_visible_to_player2']
        
        player_states.append({
            'player_turn_idx': state['player_turn_idx'],
            'required_move_count': required_move_count,
            'visible_viruses': visible_viruses,
            'board_width': state['board_width'],
            'board_height': state['board_height']
        })
    return player_states
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // With the exception of the first move, players alternate taking 3 consecutive
  // moves. This field indicates how many moves are still required before switching
  // to the opponent. Player who cannot make the move loses.
  int32 required_move_count = 2;

  // A list of visible spots that a player can potentially take an action on.
  // Pick an empty spot to move to, or convert opponent's live virus into a zombie.
  repeated Virus visible_viruses = 3;

  // Width of board, configured by the game setting
  int32 board_width = 4;

  // Height of board, configured by the game setting
  int32 board_height = 5;
}
```

```protobuf
/*
Describes the status of a spot on the grid. A player may not see the complete
board.
*/
message Virus {
  // Coordinate on the grid
  int32 x = 1;
  int32 y = 2;

  // Can be -1, 0, or 1. If the board is empty at this coordinate, player_idx is -1. 
  int32 player_idx = 3;

  // A virus can be alive or zombie. If the coordinate is empty, this field is false.
  bool is_zombie = 4;
}
```

## Action schema

```javascript
move(int x, int y)
```

[Start building now](https://botpot.ai/game/viruswar)


# Dots and Boxes

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
def init_game(game_settings):
    size = game_settings.get('Size')
    if size == 'Any':
        size = random.choice(['2x2', '3x3', '7x7'])
    if size == '2x2':
        width = 2
        height = 2
    elif size == '3x3':
        width = 3
        height = 3
    elif size == '7x7':
        width = 7
        height = 7
    new_board = []
    for r in range(height):
        for c in range(width):
            new_board.append({
                'row': r,
                'column': c,
                'closed_box_player_idx': -1,
                'top_line': -1,
                'bottom_line': -1,
                'right_line': -1,
                'left_line': -1
                })
    state = {
        'player_turn_idx': 0,
        'board': new_board,
        'board_width': width,
        'board_height': height
    }
    return state

#User draws a line for the box in (row, column) at the loc location (i.e. top, bottom, left, right) of that box
def draw_line(state, row, column, loc):
    if row < 0 or row >= state['board_height']:
        raise InvalidActionError("invalid (row, column)")
    if column < 0 or column >= state['board_width']:
        raise InvalidActionError("invalid (row, column)")
    if loc != "top" and loc != "bottom" and loc != "left" and loc != "right":
        raise InvalidActionError("invalid location. choose top, bottom, left, or right")
    box_index = row * state['board_width'] + column
    if state['board'][box_index]['closed_box_player_idx'] != -1:
        raise InvalidActionError("this box is already closed")

    player_idx = state['player_turn_idx']
    is_this_box_closed = __update_box(state, player_idx, box_index, loc)
    is_other_box_closed = False

    #Find any neighboring boxes, and update them
    other_box_index = -1
    if loc == "top" and row - 1 > -1:
        opposite_edge = "bottom"
        other_box_index = (row - 1) * state['board_width'] + column
    elif loc == "bottom" and row + 1 < state['board_height']:
        opposite_edge = "top"
        other_box_index = (row + 1) * state['board_width'] + column
    elif loc == "left" and column - 1 > -1:
        opposite_edge = "right"
        other_box_index = row * state['board_width'] + (column - 1)
    elif loc == "right" and column + 1 < state['board_width']:
        opposite_edge = "left"
        other_box_index = row * state['board_width'] + (column + 1)
    if other_box_index != -1:
        is_other_box_closed = __update_box(state, player_idx, other_box_index, opposite_edge)

    if is_this_box_closed or is_other_box_closed:
        state['player_turn_idx'] = player_idx
    else:
        state['player_turn_idx'] = (player_idx + 1) % 2
    
    return state

def __update_box(state, player_idx, box_index, loc):
    INVALID_ACTION_LINE_DRAWN = "someone already drew a line here"
    if loc == "top":
        if state['board'][box_index]['top_line'] != -1:
            raise InvalidActionError(INVALID_ACTION_LINE_DRAWN)
        else:
            state['board'][box_index]['top_line'] = player_idx
    elif loc == "bottom":
        if state['board'][box_index]['bottom_line'] != -1:
            raise InvalidActionError(INVALID_ACTION_LINE_DRAWN)
        else:
            state['board'][box_index]['bottom_line'] = player_idx
    elif loc == "left":
        if state['board'][box_index]['left_line'] != -1:
            raise InvalidActionError(INVALID_ACTION_LINE_DRAWN)
        else:
            state['board'][box_index]['left_line'] = player_idx
    elif loc == "right":
        if state['board'][box_index]['right_line'] != -1:
            raise InvalidActionError(INVALID_ACTION_LINE_DRAWN)
        else:
            state['board'][box_index]['right_line'] = player_idx
    return __check_closed(state, player_idx, box_index)

# Return true if this box is closed
def __check_closed(state, player_idx, box_index):
    if state['board'][box_index]['top_line'] != -1 and state['board'][box_index]['bottom_line'] != -1 and state['board'][box_index]['right_line'] != -1 and state['board'][box_index]['left_line'] != -1:
        state['board'][box_index]['closed_box_player_idx'] = player_idx
        return True
    return False

def get_game_result(state):
    closed_boxes = [box['closed_box_player_idx'] for box in state['board']]
    if (-1 in closed_boxes):
        return {
            "game_result": "NoWinnerYet"
        }
    player1_score = closed_boxes.count(0)
    player2_score = closed_boxes.count(1)
    if (player1_score > player2_score):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    elif (player1_score < player2_score):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    return {
        "game_result": "Draw"
    }
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // The array is stored in row major order, so index 0 is the top left and 
  // last index is the bottom right. In a size 2x2 board, index 1 is the 
  // top right board. 
  repeated Box board = 2;

  // Number of horizontal boxes in the grid
  int32 board_width = 3;

  // Number of vertical boxes in the grid
  int32 board_height = 4;
}
```

```protobuf
/*
Represents a 1x1 box. Closing this box requires 4 lines. 
*/
message Box {
  // The row of this box in the grid of boxes
  int32 row = 1;

  // The column of this box in the grid of boxes
  int32 column = 2;

  // The player who closed this box. Values can be -1, 0, or 1.
  // -1 means the box isn't closed yet.
  int32 closed_box_player_idx = 3;

  // Values can be -1, 0, 1, representing who drew this line on this box.
  int32 top_line = 4;

  // Values can be -1, 0, 1, representing who drew this line on this box.
  int32 bottom_line = 5;

  // Values can be -1, 0, 1, representing who drew this line on this box.
  int32 right_line = 6;

  // Values can be -1, 0, 1, representing who drew this line on this box.
  int32 left_line = 7;
}
```

## Action schema

```javascript
enum Location {
  top = 0;
  bottom = 1;
  left = 2;
  right = 3;
}

draw_line(int row, int column, Location loc)
```

[Start building now](https://botpot.ai/game/dotsandboxes)


# Hex

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'player_turn_idx':  0,
        'pieces':  []
    }
    return state

def place_piece(state, row, column):
    WIDTH = 11
    HEIGHT = 11
    INVALID_ACTION_NOT_YOUR_TURN = "Not your turn."
    INVALID_ACTION_OUT_OF_BOUND = "Location is out of bound."
    INVALID_ACTION_ALREADY_PLACED = "A piece is already placed here."
    if __is_out_of_bound(row, column, WIDTH, HEIGHT):
        raise InvalidActionError(INVALID_ACTION_OUT_OF_BOUND)
    for piece in state['pieces']:
        if piece['row'] == row and piece['column'] == column:
            raise InvalidActionError(INVALID_ACTION_ALREADY_PLACED)
    player_idx = state['player_turn_idx']
    state['pieces'].append({
        'row': row, 
        'column': column, 
        'value': player_idx
        })

    state['player_turn_idx'] = (player_idx + 1) % 2
    return state

def __is_bottom(coord, board_width, board_height):
    return coord[0] == 0

def __is_top(coord, board_width, board_height):
    return coord[0] == board_height - 1

def __is_left(coord, board_width, board_height):
    return coord[1] == 0

def __is_right(coord, board_width, board_height):
    return coord[1] == board_width - 1

def __has_path_to(state, is_initial_func, is_target_func, player_idx, board_width, board_height):
    """
    Does a dfs search to see if a piece that satisfies the initial func
    is connected to a piece that satisfies sthe target func.
    <is_initial_func> is a function that returns a boolean if a piece
    satisfies the initial condition.
    """
    visited = set()
    stack = []
    has_target = False
    piece_coords = set()
    for piece in state['pieces']:
        coord = (piece['row'], piece['column'])
        if piece['value'] == player_idx:
            piece_coords.add(coord)
        else:
            continue
        if is_initial_func(coord, board_width, board_height):
            stack.append(coord)
        if is_target_func(coord, board_width, board_height):
            has_target = True
        
    if not is_initial_func or not has_target:
        return False

    while len(stack) > 0:
        this_coord = stack.pop()
        if is_target_func(this_coord, board_width, board_height):
            return True
        if this_coord in visited:
            continue
        visited.add(this_coord)
        neighbors = __get_neighbors(this_coord[0], this_coord[1], board_width, board_height)
        for n in neighbors:
            if n in piece_coords:
                stack.append(n)
    return False

def __is_out_of_bound(row, column, board_width, board_height):
    return (row < 0 or row >= board_height
        or column < 0 or column >= board_width)

def __get_neighbors(row, column, board_width, board_height):
    if __is_out_of_bound(row, column, board_width, board_height):
        return []
    neighbors = []
    if column > 0:
        neighbors.append((row, column - 1))
    if column < board_width - 1:
        neighbors.append((row, column + 1))
    if row > 0:
        neighbors.append((row - 1, column))
        if column < board_width - 1:
            neighbors.append((row - 1, column + 1))
    if row < board_height - 1:
        neighbors.append((row + 1, column))
        if column > 0:
            neighbors.append((row + 1, column - 1))
    return neighbors

def get_game_result(state):
    WIDTH = 11
    HEIGHT = 11
    player1_has_path = __has_path_to(
        state, __is_left, __is_right, 0, WIDTH, HEIGHT)
    player2_has_path = __has_path_to(
        state, __is_top, __is_bottom, 1, WIDTH, HEIGHT)
    if (player1_has_path and player2_has_path):
        return {
            "game_result": "Draw"
        }
    elif (player1_has_path and not player2_has_path):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    elif (player2_has_path and not player1_has_path):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    else:
        return {
            "game_result": "NoWinnerYet"
        }
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // All the pieces on the board that a player has put down. Player idx 0 tries
  // to connect left to right (column = 0 to column = 10). Plyaer idx 1 tries
  // to connect bottom to top (row = 0 to row = 10). 
  repeated Piece pieces = 2;
}
```

```protobuf
message Piece {
  // Row of the piece that has been placed. 
  int32 row = 1;

  // Column of the piece that has been placed.
  int32 column = 2;

  // value is the player_idx who placed this piece, can be 0 or 1.
  int32 value = 3;
}
```

## Action schema

```javascript
place_piece(int row, int column)
```

[Start building now](https://botpot.ai/game/hex)


# Reversi

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'player_turn_idx': 0,
        # Initial board has 4 pieces already placed
        'game_board': [-1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, 0, 1, -1, -1, -1,
                    -1, -1, -1, 1, 0, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1],
        # First move can be in these four places
        # key is valid index to place piece, directions are directions to modify board after placing piece
        'valid_moves': [
            {
                'index': 20, 
                'valid_directions': ['BELOW']
            },
            {
                'index': 29, 
                'valid_directions': ['LEFT']
            },
            {
                'index': 34, 
                'valid_directions': ['RIGHT']
            },
            {
                'index': 43, 
                'valid_directions': ['ABOVE']
            }]
    }
    return state

def place_piece(state, index):
    """
    Places a piece in the game state's user_board parameter.
    If an index is outside the user_boards range or its not the user's turn,
    an exception is thrown.

    state: a reversi game model state created from init_game
    index: the index in user_board that the piece will be placed
    """
    assert type(index) == int, repr(index) + " is not an integer."
    if index < 0 or index > 63:
        raise InvalidActionError("Invalid index.")
    if state['game_board'][index] != -1:
        raise InvalidActionError("A piece has already been placed here.")
    if len(state['valid_moves']) == 0:
        raise InvalidActionError("The game is done.")


    offset_dict = {
        'ABOVE': -8, 
        'BELOW': 8,
        'LEFT': -1, 
        'RIGHT': 1,
        'ABOVE_LEFT': -9, 
        'ABOVE_RIGHT': -7,
        'BELOW_LEFT': 7, 
        'BELOW_RIGHT': 9}

    player_piece = state['player_turn_idx']
    opp_piece = (player_piece + 1) % 2

    valid_move = None
    for pair in state['valid_moves']:
        if index == pair['index']:
            valid_move = pair # Use to modify board
            break
    if valid_move == None:
        raise InvalidActionError("This is not a valid place to put a piece.")
    state['game_board'][valid_move['index']] = player_piece
    state = _modify_board(state, player_piece, valid_move, offset_dict)

    state = _modify_valid_moves(state, opp_piece, player_piece, offset_dict)
    if len(state['valid_moves']) == 0: # If opponent no moves, then you go again (if possible)
        state = _modify_valid_moves(state, player_piece, opp_piece, offset_dict)
    else: # Opponent has valid move
        state['player_turn_idx'] = opp_piece
    # At this point, valid_moves will only be 0 if both users have no moves
    return state

def get_game_result(state):
    """ Returns if a the game represented by state is won, ongoing, or a tie """
    if len(state['valid_moves']) != 0:
        return {
            "game_result": "NoWinnerYet"
        }
    else:
        board = state['game_board']
        num_user1_pieces = sum([x == 0 for x in board])
        num_user2_pieces = sum([x == 1 for x in board])
        if num_user1_pieces == num_user2_pieces: # Board is filled
            return {
                "game_result": "Draw"
            }
        else:
            if num_user1_pieces > num_user2_pieces:
                return {
                    "game_result": "Winner",
                    "winner_idx": 0
                }
            else:
                return {
                    "game_result": "Winner",
                    "winner_idx": 1
                }

def _modify_board(state, player_piece, valid_move, offset_dict):
    """ Changes the color of the pieces in a certain direction for a valid move
    If this function is called, we know that placing a piece at index is valid. """
    for direction in valid_move['valid_directions']:
        increase_interval = offset_dict[direction]
        iterator = increase_interval + valid_move['index']
        while (state['game_board'][iterator] != player_piece):
            state['game_board'][iterator] = player_piece
            iterator += increase_interval
    return state

def _modify_valid_moves(state, player_piece, opp_piece, offset_dict):
    """ Modify state['valid_moves'] for the next move. """
    # TODO implement BFS starting at index's key
    del state['valid_moves'][:] # Empty valid moves list
    for board_pos in range(64):
        if state['game_board'][board_pos] == -1:
            valid_directions_for_index = []
            for direction_enum in offset_dict:
                if _validate_move_generic(state, player_piece, opp_piece, board_pos, offset_dict[direction_enum]):
                    valid_directions_for_index.append(direction_enum)

            if len(valid_directions_for_index) > 0:
                state['valid_moves'].append({
                    'index': board_pos, 
                    'valid_directions': valid_directions_for_index
                })
    return state

def _validate_move_generic(state, player_piece, opp_piece, board_pos, offset_amount):
    """ Check if placing a piece at board_pos is valid when looking at one
    of the eight directions. """
    if _is_out_of_bound(board_pos, offset_amount) or state['game_board'][board_pos + offset_amount] != opp_piece:
        return False
    iterator = board_pos + (offset_amount * 2)
    while _is_within_iterator_bound(board_pos, iterator, offset_amount):
        if state['game_board'][iterator] == player_piece:
            return True
        elif state['game_board'][iterator] == -1:
            return False # Placement of piece will not surround an opponent piece
        iterator += offset_amount
    return False

def _is_out_of_bound(board_pos, offset_amount):
    """ Determine if index is on the boundary of the board. If so, there is no
    need to validate the move in certain directions.
    Assume index is already between 0 and 63, inclusive. """
    if offset_amount == -8: return True if board_pos <= 7 else False
    if offset_amount == 8: return True if board_pos >= 56 else False
    if offset_amount == -1: return True if board_pos % 8 == 0 else False
    if offset_amount == 1: return True if (board_pos - 7) % 8 == 0 else False
    if offset_amount == -9:
        return True if board_pos % 8 == 0 or board_pos <= 7 else False
    if offset_amount == 7:
        return True if board_pos % 8 == 0 or board_pos >= 56 else False
    if offset_amount == -7:
        return True if (board_pos - 7) % 8 == 0 or board_pos <= 7 else False
    if offset_amount == 9:
        return True if (board_pos - 7) % 8 == 0 or board_pos >= 56 else False

def _is_within_iterator_bound(board_pos, iterator, offset_amount):
    if offset_amount == -8: return iterator >= 0
    if offset_amount == 8: return iterator <= 63
    if offset_amount == -1: return iterator >= (board_pos // 8) * 8
    if offset_amount == 1: return iterator <= ((board_pos // 8) * 8) + 7
    if offset_amount == -7: return iterator >= 2 and iterator % 8 != 0
    if offset_amount == -9: return iterator >= 0 and (iterator - 7) % 8 != 0
    if offset_amount == 7: return iterator <= 61 and (iterator - 7) % 8 != 0
    if offset_amount == 9: return iterator <= 63 and iterator % 8 != 0
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1    
  int32 player_turn_idx = 1;

  // An array of size 64 stored in row major order, so index 0 is top left, 
  // index 7 is top right, index 56 is bottom left, and index 63 is bottom right.
  // Values can be -1, 0, or 1, where -1 represents an empty spot, 0 is a piece
  // made by player_idx 0 and 1 is a piece made by player_idx 1.
  repeated int32 game_board = 2;

  // Precomputed array of all the valid moves. Players should select an index from
  // this list to make a move. 
  repeated ValidMove valid_moves = 3;
}
```

```protobuf
/*
Each ValidMove is an index that the current player can place his piece on.
It also contains information about the all directions that will flip the 
opponent pieces. 
*/
message ValidMove {
  int32 index = 1;
  repeated direction valid_directions = 2;
}
```

```protobuf
// The 8 directions to flip opponent disks.
enum direction {
  ABOVE = 0;
  BELOW = 1;
  LEFT = 2;
  RIGHT = 3;
  ABOVE_LEFT = 4;
  ABOVE_RIGHT = 5;
  BELOW_LEFT = 6;
  BELOW_RIGHT = 7;
}
```

## Action schema

```javascript
place_piece(int index)
```

[Start building now](https://botpot.ai/game/reversi)


# Gomoku

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'player_turn_idx': 0,
        'board': [-1] * (15*15)
    }
    return state

def place_piece(state, index):
    if index < 0 or index > 224:
        raise InvalidActionError("index out of bound")
    if state['board'][index] != -1:
        raise InvalidActionError("someone already placed a piece here")
    
    player_idx = state['player_turn_idx']
    state['player_turn_idx'] = (player_idx + 1) % 2
    state['board'][index] = player_idx
    return state

def get_game_result(state):
    if __has_line(state, 0):
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if __has_line(state, 1):
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    for item in state['board']:
        if item == -1:
            return {
                "game_result": "NoWinnerYet"
            }
    return {
        "game_result": "Draw"
    }

def __has_line(state, value):
    for i in range(0,15):
        for j in range(0, 11):
            #horizontal 5, i rows, j cols
            for k in range(0, 5):
                if state['board'][i*15+j+k] != value:
                    break
                if k == 4:
                    return True
            #vertical 5, i columns, j rows
            for m in range(0, 5):
                if state['board'][i+(j+m)*15] != value:
                    break
                if m == 4:
                    return True
    #down to left diagonal
    #4- 13
    if __diagnal_side(4, 14, state, 14, 0, value):
        return True
    #down to left bottom
    #14-164
    if __diagnal_bottom(14, 179, 15, state, 14, value):
        return True
    #down to right diagonal
    #1-10
    if __diagnal_side(1, 11, state, 16, 14, value):
        return True
    #down to right bottom
    #0-150
    if __diagnal_bottom(0, 165, 15, state, 16, value):
        return True
    return False

def __diagnal_side(s, e, state, interval, remainder, value):
    for i in range(s, e):
        k = 0
        while True:
            for j in range(k, k+5):
                if state['board'][i + interval*j] != value:
                    break
                if j-k == 4:
                    return True
            if (i+(k+4)*interval) % 15 == remainder:
                break
            k = k+1

def __diagnal_bottom(s, e, stp, state, interval, value):
    for i in range(s, e, stp):
        k = 0
        while True:
            for j in range(k, k+5):
                if state['board'][i + interval*j] != value:
                    break
                if j-k == 4:
                    return True
            if 224 - (i+(k+4)*interval) < 15:
                break
            k = k+1
```

</details>

## Game state schema

```protobuf
message State{
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

/*
  Array of size 225 initialized to -1, representing an empty 15 by 15 board.
  The values of board can be -1, 0, or 1. 
  Placing a piece in index x will set the value of board[x] to the player's index.
  Array is row major order: index 0 is top left, index 14 is top right, index 210 is 
  bottom left, and index 224 is bottom right.
*/
  repeated int32 board = 2;
}

```

## Action schema

```javascript
place_piece(int index)
```

[Start building now](https://botpot.ai/game/gomoku)


# Mancala

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        'player_turn_idx': 0,
        'board': [0, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4]
    }
    return state

"""
The last piece in Mancala has special rules. [__handle_last_piece] determines whether the piece lands in 
a Mancala or an empty pocket on the player's own side. If landing on own Mancala, the player gains a second turn. 
(state['player_turn_idx'] stays the same). If the piece lands on an empty pocket, and there are pieces in the 
corresponding pocket on the opponent's side, the player gains both the last piece and those on the opponents side. 
"""
def __handle_last_piece(state, index):
    player_idx = state['player_turn_idx']
    if player_idx == 0:
        #Gain a turn if last piece lands on that user's own Mancala
        if index == 7:
            state['player_turn_idx'] = 0
            return

        #Take over pieces from other side if landing on empty space on user's own side
        elif (1 <= index < 7) and state['board'][index] == 1 and state['board'][14 - index] != 0:
            state['board'][7] += (state['board'][14 - index] + 1)
            state['board'][14 - index] = 0
            state['board'][index] = 0

        state['player_turn_idx'] = 1

    else:
        if index == 0:
            state['player_turn_idx'] = 1
            return

        elif (8 <= index < 14) and state['board'][index] == 1 and state['board'][14 - index] != 0:
            state['board'][0] += (state['board'][14 - index] + 1)
            state['board'][14 - index] = 0
            state['board'][index] = 0

        state['player_turn_idx'] = 0
        
"""
Function that moves the pieces on the board. Given the amount of pieces at the given index, this function will 
loop around the board until the pieces run out. One piece goes into each pocket (except for the opponent's Mancala.)
"""
def __move_pieces(state, index):
    pieces_left = state['board'][index]
    state['board'][index] = 0          #Empty out chosen pocket
    player_idx = state['player_turn_idx']
    while pieces_left != 0:
        index = (index + 1) % 14
        #player 1 does not put pieces in pocket 0
        #player 2 does not put pieces in pocket 7
        if (player_idx == 0 and index == 0) or (player_idx == 1 and index == 7):
            continue
            
        state['board'][index] += 1         
        pieces_left -= 1

    __handle_last_piece(state, index)

"""
Determines if the pocket the user chose is valid. Movies pieces around board and checks whether the current
user will have an extra turn.

Returns a new state. 
"""
def choose_pocket(state, index):
    if index < 0 or index > 13:
        raise InvalidActionError("Index out of bound")

    #Invalid action if user picks either Mancala.
    if index == 0 or index == 7:
        raise InvalidActionError("You cannot choose to move pieces out of a Mancala.")

    #Invalid action if user tries to move pieces from the opponent's side
    player_idx = state['player_turn_idx']
    if (player_idx == 0 and index > 6) or (player_idx == 1 and index < 8):
        raise InvalidActionError("You cannot choose a pocket from your opponent's side.")
    
    #Invalid action if user picks pocket without pieces in it.
    if state['board'][index] == 0:
        raise InvalidActionError("There are no pieces in this pocket.")

    __move_pieces(state, index)

    return state

"""
Checks whether one of the sides is empty. If so, calculates the totals for both sides and returns
a game result. If neither side is empty, returns an ongoing result. 
"""
def get_game_result(state):
    #Detect if one of the sides is empty, otherwise, the game is ongoing
    if (__side_empty(state, 2) or __side_empty(state, 1)):
        player1_score = sum(state['board'][1:8])
        player2_score = sum(state['board'][8:14]) + state['board'][0]
        if player2_score > player1_score:
            return {
                "game_result": "Winner",
                "winner_idx": 1
            }
        elif player1_score > player2_score:
            return {
                "game_result": "Winner",
                "winner_idx": 0
            }
        else: 
            return {
                "game_result": "Draw"
            }
    else:
        return {
            "game_result": "NoWinnerYet"
        }

""" 
Checks if one of the sides of the mancala board is empty. 

Returns [True] if the side is empty, [False] otherwise. 
"""
def __side_empty(state, side):
    if side == 1:
        for i in range(1, 7):
            if state['board'][i] != 0:
                return False
        return True
    else:
        for i in range(8, 14):
            if state['board'][i] != 0:
                return False 
        return True
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  /*
    Array of size 14, indicating the 12 pockets and 2 Mancala. The indices go 
    counter-counterclockwise where indices 1-7 is player_idx 0 and the remaining 
    are player_idx 1. Index 7 is player_idx 0's Mancala. Index 0 is player_idx 1's
    Mancala. The values of the board indicate how many pieces are in them.
    *************************
    * 0 13 12 11 10 9  8    *
    *   1  2  3  4  5  6  7 *
    *************************
  */
  repeated int32 board = 4;
}

```

## Action schema

```javascript
choose_pocket(int index)
```

[Start building now](https://botpot.ai/game/mancala)


# Uno

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
def init_game(game_settings):
    player_count = int(game_settings["Player Count"])
    state = {
        'scores': [0] * player_count
    }
    state = __initialize_round(state)
    return state

def __initialize_round(state):
    deck = __initalize_deck()
            
    #Flip over first card on the deck and add to discard pile, cannot be a wild or wild draw four card
    first_card = deck.pop()

    #Set up empty hands
    hands = []
    player_count = len(state['scores']) # scores is the only thing that persists across rounds
    for i in range(player_count):
        hand = {
            'cards': []
        }
        #Deal each player 7 cards
        for x in range(7):
            hand['cards'].append(deck.pop())
        hands.append(hand)
    
    #Randomly decide who goes first/who is the "dealer"
    state['player_turn_idx'] = random.randint(0, player_count - 1)
    state['players_hands'] = hands
    state['draw_pile'] = deck
    state['discard_pile'] = [first_card]
    state['direction'] = "CLOCKWISE"

    return state

def __initalize_deck():
    def make_cards(color, type, card_number, count):
        cards = []
        for i in range(count):
            cards.append({
                'color': color, 
                'type': type, 
                'card_number': card_number
                })
        return cards
    standard_colors = ['BLUE', 'GREEN', 'RED', 'YELLOW']
    deck = []
            
    #Skip, reverse, and draw Cards, 2 of each standard color
    for card_color in standard_colors:
        deck.extend(make_cards(card_color, 'SKIP', -1, 2))
        deck.extend(make_cards(card_color, 'REVERSE', -1, 2))
        deck.extend(make_cards(card_color, 'DRAWTWO', -1, 2))
             
    #4 Wild Cards and wild draw four cards
    deck.extend(make_cards('UNDEFINED', 'WILD', -1, 4))
    deck.extend(make_cards('UNDEFINED', 'WILDDRAWFOUR', -1, 4))

    #Cards numbered 0-9 in each standard color
    for number in range(10):
        for card_color in standard_colors:
            #only one 0 of each color, all other numbers have 2 of the same card in the deck
            if number == 0:
                deck.extend(make_cards(card_color, 'NUMBERED', number, 1))
            else:
                deck.extend(make_cards(card_color, 'NUMBERED', number, 2))

    random.shuffle(deck)
    # Make sure last card is a normal card (we will use pop, so last card is drawn first)
    for i in range(len(deck)):
        if deck[i]['type'] == 'NUMBERED':
            result = deck[0:i]
            result.extend(deck[i + 1:])
            result.append(deck[i])
            return result
    # shouldn't happen
    return deck
        
def __can_be_played(state, player_idx, card):
    def can_non_wilddrawfour_be_played(top_card, card): # assumes card is not a wildDrawFour
        if card['type'] == 'WILD':
            return True
        if card['color'] == top_card['color']:
            return True
        if card['type'] == top_card['type']:
            if card['type'] == 'NUMBERED':
                return card['card_number'] == top_card['card_number']
            return True
        return False

    top_discard_card = state['discard_pile'][-1]

    if card['type'] == 'WILDDRAWFOUR':
        # For simplicity, no bluffing so you can't play this if you have another playable card
        for c in state['players_hands'][player_idx]['cards']:
            if c['type'] == 'WILDDRAWFOUR':
                continue
            if can_non_wilddrawfour_be_played(top_discard_card, c):
                raise InvalidActionError("If another card is playable, you cannot play the wild draw 4 card.")
        return True

    return can_non_wilddrawfour_be_played(top_discard_card, card)

def draw_card(state, specified_color = None):
    player_idx = state['player_turn_idx']
    __safe_draw(state, player_idx, 1)

    cards = state['players_hands'][player_idx]['cards']
    drawn_card = cards[-1]
    if (__can_be_played(state, player_idx, drawn_card)):
        state = __carry_out_action(state, player_idx, len(cards) - 1, specified_color)
    else:
        state['player_turn_idx'] = __get_next_index(state, player_idx, 1)

    state = __handle_end_of_round(state, player_idx)
        
    return state

def __safe_draw(state, player_idx, count):
    """
    The <player_idx> player tries to draw <count> number of cards from the draw_pile.
    Returns True if it can be done and False if there are not enough cards in the pile.
    """
    for i in range(count):
        if len(state['draw_pile']) > 0:
            drawn_card = state['draw_pile'].pop();
            state['players_hands'][player_idx]['cards'].append(drawn_card)
        else:
            return False
    return True
    
def __get_next_index(state, player_idx, offset):
    return (player_idx+offset) % len(state['players_hands']) if state['direction'] == "CLOCKWISE" else (player_idx - offset) % len(state['players_hands'])
    
def __carry_out_action(state, player_idx, card_index, specified_color = None):
    current_cards = state['players_hands'][__get_next_index(state, player_idx, 0)]['cards']
    card = current_cards.pop(card_index)
    #Reverse the direction
    if card['type'] == 'REVERSE':
        state['direction'] = 'COUNTERCLOCKWISE' if state['direction'] == 'CLOCKWISE' else 'CLOCKWISE'
        #update turn
        if len(state['players_hands']) != 2:
            state['player_turn_idx'] = __get_next_index(state, player_idx, 1)
    #Skips next player's turn
    elif card['type'] == 'SKIP':
        state['player_turn_idx'] = __get_next_index(state, player_idx, 2)
        
    #Gives next player 2 cards and skips the next player's turn
    elif card['type'] == 'DRAWTWO':
        next_player_index = __get_next_index(state, player_idx, 1)
        __safe_draw(state, next_player_index, 2)
        
        state['player_turn_idx'] = __get_next_index(state, player_idx, 2)
    #Changes the color to any color
    elif card['type'] == 'WILD':
        card['color'] = specified_color
        #update turn
        state['player_turn_idx'] = __get_next_index(state, player_idx, 1)
    #Changes the color to any color, gives next player 4 colors, and skips the next player's turn
    elif card['type'] == 'WILDDRAWFOUR':
        card['color'] = specified_color
        next_player_index = __get_next_index(state, player_idx, 1)
        __safe_draw(state, next_player_index, 4)
            
        state['player_turn_idx'] = __get_next_index(state, player_idx, 2)
    #Normal numbered card does nothing special
    else:
        #update turn
        state['player_turn_idx'] = __get_next_index(state, player_idx, 1)

    state['discard_pile'].append(card)  
    return state


def play_card(state, card_position_in_hand, call_uno, specified_color = None):    
    player_idx = state['player_turn_idx']
    cards = state['players_hands'][player_idx]['cards']
    
    if card_position_in_hand >= len(cards) or card_position_in_hand < 0:
        raise InvalidActionError("Not a valid card in the player's hand")
    
    selected_card = cards[card_position_in_hand]
    
    if (__can_be_played(state, player_idx, selected_card)):
        state = __carry_out_action(state, player_idx, card_position_in_hand, specified_color)
        if len(state['players_hands'][player_idx]['cards']) == 1:
            if not call_uno:
                __safe_draw(state, player_idx, 4)
    else:
        raise InvalidActionError("This card is not playable -- choose a card with the same color, word, or number as the top discarded card")

    state = __handle_end_of_round(state, player_idx)
    
    return state

def __handle_end_of_round(state, player_idx):
    # A round ends when one player has no cards left or when the draw pile is empty
    # Each player p gets a penalty <Sp> based on how many cards they have left when
    # the round ends. The player with the minimum penalty min(Sp) is the winner of the round.
    # Thus if a player has no cards, he is the winner of the round.
    # The winner(s) gets a score that is the sum of (Sp - min(Sp)) and is evenly distributed
    # across the winners if the winners have the same minimum score.
    # Then shuffle and redeal the cards
    if len(state['players_hands'][player_idx]['cards']) > 0 and len(state['draw_pile']) > 0:
        return state

    def value_of_card(card):
        if card['type'] == 'NUMBERED':
            return card['card_number']
        elif card['type'] == 'DRAWTWO' or card['type'] == 'REVERSE' or card['type'] == 'SKIP':
            return 20
        else:
            return 50

    scores = []
    for i in range(len(state['players_hands'])):
        scores.append(sum([value_of_card(card) for card in state['players_hands'][i]['cards']]))
    min_score = min(scores)

    winner_indices = []
    sum_of_penalty = 0
    for i in range(len(scores)):
        if min_score == scores[i]:
            winner_indices.append(i)
        else:
            sum_of_penalty += (scores[i] - min_score)
    winner_score = int(sum_of_penalty / len(winner_indices))

    for winner_index in winner_indices:
        state['scores'][winner_index] += winner_score
    if max(state['scores']) > 300:
        return state
    return __initialize_round(state)

def get_game_result(state):
    #determines whether a player has reached at least 300 points and if so, declare them the winner
    scores = state['scores']
    for i in range(len(scores)):
        if scores[i] >= 300:
            return {
                "game_result": "Winner",
                "winner_idx": i
            }
    return {
        "game_result": "NoWinnerYet"
    }
    
def get_player_states(state):
    hand_count = []
    for i in range(len(state['players_hands'])):
        hand_count.append(len(state['players_hands'][i]['cards']))

    player_states = []
    for i in range(len(state['players_hands'])):
        player_states.append({
            'player_turn_idx': state['player_turn_idx'],
            'player_hand': state['players_hands'][i],
            'players_hand_count': hand_count,
            'last_discarded': state['discard_pile'][-1],
            'direction': state['direction'],
            'scores': state['scores'],
            'draw_pile_count': len(state['draw_pile'])
        })
    return player_states
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // Each player can only see their own hands. They can see the number of cards
  // in the other player's hands, but not their card type.
  Hand player_hand = 2;

  // An array of the number of cards in each player's hands, including yourself.
  repeated int32 players_hand_count = 3;

  // The top of the deck. What you can play is based on this.
  Card last_discarded = 4;

  // Direction of the turns, can be "CLOCKWISE" or "COUNTERCLOCKWISE".
  // Clockwise means the player indices increment, and counterclockwise means decrement. 
  // Playing the reverse card will flip the direction.
  string direction = 5;
}
```

```protobuf
message Hand {
  repeated Card cards = 1;
}
```

```protobuf
message Card {
  enum Color {
    BLACK = 0;
    BLUE = 1;
    GREEN = 2;
    RED = 3;
    YELLOW = 4;

    // WILD cards may have this as undefined initially
    // When WILD cards are played, players specify their color
    UNDEFINED = 5;
  }

  enum Type {
    NUMBERED = 0;
    WILD = 1;
    DRAWTWO = 2;
    WILDDRAWFOUR = 3;
    REVERSE = 4;
    SKIP = 5;
  }

  Color color = 1;
  Type type = 2;
  int32 card_number = 3;
}
```

## Action schema

```javascript
play_card(int card_position_in_hand, bool call_uno, string specified_color)
draw_card(string specified_color)
```

[Start building now](https://botpot.ai/game/uno)


# Big 2

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
def init_game(game_settings):
    deck = __initalize_deck()

    # set up hands for players
    hands = []

    for player_idx in range(4):
        hand = []
        for x in range(13):
            card = deck.pop()
            # player with 3 of diamonds goes first
            if card == {
                'suit': 'DIAMOND',
                'card_rank': 3
                }:
                first_player_index = player_idx
            hand.append(card)
        hands.append({
            'cards': __sort_cards(hand)
        })

    state = {
        'player_turn_idx': first_player_index,
        'players_hands': hands,
        'passes': 0,
        'discard_pile': [],
        'last_play': {
            'type': 'NONE'
        }
    }

    return state

def __initalize_deck():
    suits = ['DIAMOND', 'CLUB', 'HEART', 'SPADE']
    deck = []

    for card_suit in suits:
        for rank in range(13):
            deck.append({
                'suit': card_suit, 
                'card_rank': rank + 1
                })

    random.shuffle(deck)
    return deck

def __can_be_played(state, play):
    PLAY_VALUE = {
        'SINGLE': 1,
        'DOUBLE': 2,
        'TRIPLE': 3,
        'STRAIGHT': 4,
        'FLUSH': 5,
        'FULLHOUSE': 6,
        'BOMB': 7,
        'STRAIGHTFLUSH': 8
    }
    if len(state['discard_pile']) == 0:
        for c in play['cards']:
            if c == {
                'suit': 'DIAMOND', 
                'card_rank': 3
            }:
                return True
        raise InvalidActionError("First player has to play down a play containing three of diamonds")
    if len(state['last_play']['cards']) == 0:
        return True

    last_play_type = state['last_play']['type']

    # 5 card hands can beat other 5 card hands, single double triple needs to be same type to play
    if PLAY_VALUE[last_play_type] <= 3:
        if last_play_type != play['type']:
            return False
        elif __compare(play['cards'][0],  state['last_play']['cards'][0]) > 0:
            return True
        else:
            return False
    else:
        if PLAY_VALUE[play['type']] < PLAY_VALUE[last_play_type]:
            return False
        elif PLAY_VALUE[play.type] > PLAY_VALUE[last_play_type]:
            return True
        elif PLAY_VALUE[play.type] == 5 and PLAY_VALUE[last_play_type] == 5:
            if __compare_suit(play['cards'][0]['suit'],  state['last_play']['cards'][0]['suit']) > 0:
                return True
            elif __compare(play['cards'][0], state['last_play']['cards'][0]) > 0:
                return True
        elif __compare(play['cards'][0],  state['last_play']['cards'][0]) > 0:
            return True
        else:
            return False

def __get_suit_value_dict():
    return {
        'DIAMOND': 1,
        'CLUB': 2,
        'HEART': 3,
        'SPADE': 4
    }

def __compare_suit(suit1, suit2):
    suit_dict = __get_suit_value_dict()
    compare = suit_dict[suit1] - suit_dict[suit2]
    return compare

def __compare_rank(rank1, rank2):
    if rank1 == rank2:
        return 0
    elif rank1 == 2:
        return 1
    elif rank2 == 2:
        return -1
    elif rank1 == 1:
        return 1
    elif rank2 == 1:
        return -1
    else:
        compare = rank1 - rank2
        return compare

def __compare(card1, card2):
    compare = __compare_rank(card1['card_rank'], card2['card_rank'])
    if compare == 0:
        return __compare_suit(card1['suit'], card2['suit'])
    else:
        return compare

# insertion sort because will be dealing with small lists (at most length 13 (rare), usually length 5)
def __sort_cards(cards):
    cards_array = [c for c in cards]
    n = len(cards_array)
    for i in range(n):
        for j in range(i, 0, -1):
            if __compare(cards_array[j], cards_array[j-1]) < 0:
                cards_array[j], cards_array[j-1] = cards_array[j-1], cards_array[j]
    return cards_array

def __straight_helper(num):
    if num == 1:
        return 14
    else:
        return num

def __determine_play(cards):
    cards = __sort_cards(cards)
    if len(cards) == 1:
        play_type = 'SINGLE'
        top_card = cards[0]
    elif len(cards) == 2 and cards[0]['card_rank'] == cards[1]['card_rank']:
        play_type = 'DOUBLE'
        top_card = cards[1]
    elif len(cards) == 3 and cards[0]['card_rank'] == cards[1]['card_rank'] and cards[0]['card_rank'] == cards[2]['card_rank']:
        play_type = 'TRIPLE'
        top_card = cards[2]
    elif len(cards) == 5:
        straight = True
        flush = True
        card1 = None
        count1 = 0
        card2 = None
        count2 = 0
        suit = cards[0]['suit']

        for i in range(5):
            if cards[i]['suit'] != suit:
                flush = False

            if (cards[i]['card_rank'] == 2) or \
                    (i < 4 and __straight_helper(cards[i+1]['card_rank']) - cards[i]['card_rank'] != 1):
                straight = False

            if card1 is None:
                card1 = cards[i]
                count1 += 1
            elif cards[i]['card_rank'] == card1['card_rank']:
                count1 += 1
            elif card2 is None:
                card2 = cards[i]
                count2 += 1
            elif cards[i]['card_rank'] == card2['card_rank']:
                count2 += 1

        if straight and flush:
            play_type = 'STRAIGHTFLUSH'
            top_card = cards[4]
        elif straight:
            play_type = 'STRAIGHT'
            top_card = cards[4]
        elif flush:
            play_type = 'FLUSH'
            top_card = cards[4]
        elif count1 == 3 and count2 == 2:
            play_type = 'FULLHOUSE'
            top_card = card1
        elif count2 == 3 and count1 == 2:
            play_type = 'FULLHOUSE'
            top_card = card2
        elif count1 == 4:
            play_type = 'BOMB'
            top_card = card1
        elif count2 == 4:
            play_type = 'BOMB'
            top_card = card2
        else:
            raise InvalidActionError("Invalid play")
    else:
        raise InvalidActionError("Invalid play")

    idx_of_top_card = cards.index(top_card)

    # ordered_cards is just cards with the top_card being the first one in the list
    ordered_cards = [cards[idx_of_top_card]]
    ordered_cards.extend(cards[0:idx_of_top_card])
    ordered_cards.extend(cards[idx_of_top_card + 1:])
    return {
        'type': play_type, 
        'cards': ordered_cards
        }


def make_play(state, card_indices):
    player_idx = state['player_turn_idx']

    if len(card_indices) != len(set(card_indices)):
        raise InvalidActionError("Invalid play")

    hand = state['players_hands'][player_idx]['cards']
    cards_played = []
    for i in card_indices:
        if i < 0 or i >= len(hand):
            raise InvalidActionError("Not a valid play in the player's hand")
        cards_played.append(hand[i])

    play = __determine_play(cards_played)

    if __can_be_played(state, play):
        state['last_play'] = play
        new_hand = []
        for i in range(len(hand)):
            if i not in card_indices:
                new_hand.append(hand[i])
        state['players_hands'][player_idx]['cards'] = new_hand
        for card in cards_played:
            state['discard_pile'].append(card)
        state['player_turn_idx'] = (player_idx + 1) % 4
        state['passes'] = 0
    else:
        raise InvalidActionError("Invalid play")

    return state

def pass_turn(state):
    player_idx = state['player_turn_idx']

    if state['passes'] < 2:
        state['player_turn_idx'] = (player_idx + 1) % 4
        state['passes'] += 1
    elif state['passes'] == 2:
        state['passes'] = 0
        state['last_play']['cards'] = []
        state['player_turn_idx'] = (player_idx + 1) % 4
    else:
        raise InvalidActionError("Everyone else has passed. You can play any card")

    return state

def get_game_result(state):
    for i in range(len(state['players_hands'])):
        if len(state['players_hands'][i]['cards']) == 0:
            return {
                "game_result": "Winner",
                "winner_idx": i
            }
    return {
        "game_result": "NoWinnerYet"
    }

def get_player_states(state):
    hand_count = [len(state['players_hands'][i]['cards']) for i in range(4)]

    player_states = []
    for i in range(4):
        player_states.append({
            'player_turn_idx': state['player_turn_idx'],
            'player_hand': state['players_hands'][i],
            'players_hand_count': hand_count,
            'passes': state['passes'],
            'discard_pile': state['discard_pile'],
            'last_play': state['last_play']
        })
    return player_states
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  // Each player can only see their own hands. They can see the number of cards
  // in the other player's hands, but not their card type.
  Hand player_hand = 2;

  // An array of the number of cards in each player's hands, including yourself.
  repeated int32 players_hand_count = 3;

  // The number of consecutive players who passed. If everyone else passed, 
  // you can make whatever Play you want next.
  int32 passes = 4;

  // All the cards that have been played goes into the discard pile.
  repeated Card discard_pile = 5;

  // The last play. What you play is based on this, and it should match normally
  // match in Play Type, but larger, or be Bomb or Straight FLush. If everyone
  // else passed, the cards in last_play will be empty, and you can play whatever.
  Play last_play = 6;
}
```

```protobuf
message Play {
  enum Type {
    SINGLE = 0;
    DOUBLE = 1;
    TRIPLE = 2;
    STRAIGHT = 3;
    FLUSH = 4;
    FULLHOUSE = 5;
    BOMB = 6;
    STRAIGHTFLUSH = 7;
  }

  // Subsequent plays must match in type except for BOMB 
  // and STRAIGHTFLUSH
  Type type = 1;

  // Array of cards in that play. 
  repeated Card cards = 2;
}
```

```protobuf
message Hand {
  repeated Card cards = 1;
}
```

```protobuf
message Card {
  enum Suit {
    DIAMOND = 0;
    CLUB = 1;
    HEART = 2;
    SPADE = 3;
  }
  Suit suit = 1;

  // Values go from 1 through 13 inclusive. J, Q, K, A have ranks of
  // 11, 12, 13, 1, respectively.
  int32 card_rank = 2;
}
```

## Action schema

```javascript
make_play(list<int> card_indices)
pass_turn()
```

[Start building now](https://botpot.ai/game/big2)


# Snake & Tetris

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
import copy

SNAKE_BOARD_WIDTH = 11
SNAKE_BOARD_HEIGHT = 20
TETRIS_BOARD_WIDTH = 10
TETRIS_BOARD_HEIGHT = 20
TETRIS_ROTATE_CENTERS = {
    "I": (1.5, -0.5),
    "J": (1, 0),
    "L": (1, 0),
    "O": (0.5, 0.5),
    "S": (1, 0),
    "T": (1, 0),
    "Z": (1, 0)
}

def init_game(game_settings):
    snake_positions = [_make_position(5, 1), _make_position(5, 0)]
    state = {
        "snake": {
            "positions": snake_positions,
            "direction": "up"
        },
        "tetris_board": {
            "next_tetrominos": [_generate_random_tetromino()],
            "pieces": []
        },
        "food": _generate_food_position(snake_positions),
        "is_dead_snake": False,
        "is_dead_tetris": False,
        "score": 0,
        "player_turn_idx": 0
    }
    return state

def _make_position(x, y):
    return {
        "x": x,
        "y": y
    }

def _generate_random_tetromino():
    tetromino_funcs = [_I_tetromino, _J_tetromino, _L_tetromino, _O_tetromino, _S_tetromino, _T_tetromino, _Z_tetromino]
    return random.choice(tetromino_funcs)()

def _I_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 2, y = 0),
            _make_position(x = 3, y = 0)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "I"
    }

def _J_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 1),
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 2, y = 0)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "J"
    }

def _L_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 2, y = 0),
            _make_position(x = 2, y = 1)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "L"
    }

def _O_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 1, y = 1),
            _make_position(x = 0, y = 1)
            ],
        "offset_x": 4,
        "offset_y": 20,
        "piece_name": "O"
    }

def _S_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 1, y = 1),
            _make_position(x = 2, y = 1)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "S"
    }

def _T_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 0),
            _make_position(x = 1, y = 0),
            _make_position(x = 1, y = 1),
            _make_position(x = 2, y = 0)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "T"
    }

def _Z_tetromino():
    return {
        "positions": [
            _make_position(x = 0, y = 1),
            _make_position(x = 1, y = 1),
            _make_position(x = 1, y = 0),
            _make_position(x = 2, y = 0)
            ],
        "offset_x": 3,
        "offset_y": 20,
        "piece_name": "Z"
    }

def _generate_food_position(snake_positions):
    snake = set([(p["x"], p["y"]) for p in snake_positions])
    valid = []
    for i in range(SNAKE_BOARD_WIDTH):
        for j in range(SNAKE_BOARD_HEIGHT):
            if (i, j) not in snake:
                valid.append((i, j))
    x, y = random.choice(valid)
    return _make_position(x = x, y = y)

def move(state, direction):
    # Change the direction of the snake but does not move it
    state = _change_snake_direction(state, direction)

    # move the tetris left, right, soft drop, or spin immediately if possible
    state = _move_tetris(state, direction)
    return state

def _change_snake_direction(state, direction):
    vector_new = __direction_to_vector(direction)
    vector_original = __direction_to_vector(state["snake"]["direction"])
    if __is_perpendicular(vector_original, vector_new):
        state["snake"]["direction"] = direction
    return state

def _move_tetris(state, direction):
    """
    Attempts to move the piece, and is a No-op if it moves against the wall or existing piece on the board. 
    """
    existing_pieces = set([(p["x"], p["y"]) for p in state["tetris_board"]["pieces"]])
    tetromino = copy.deepcopy(state["tetris_board"]["next_tetrominos"][0])
    if direction == "up":
        tetromino = _rotate_cw(tetromino)
    else:
        move_vector = __direction_to_vector(direction)
        tetromino["offset_x"] += move_vector[0]
        tetromino["offset_y"] += move_vector[1]

    if _tetromino_can_be_there(existing_pieces, tetromino):
        if _tetromino_is_bottom(existing_pieces, tetromino):
            _handle_bottom(state, tetromino)
        else:
            state["tetris_board"]["next_tetrominos"][0] = tetromino
    return state

def do_nothing(state):
    return state

def auto_update(state):
    if state["is_dead_snake"] or state["is_dead_tetris"]:
        return state
    # Every time this method is called, advance the state
    # by moving the snake forward and tetris piece down

    state = _auto_update_snake(state)
    state = _auto_update_tetris(state)
    return state

def _auto_update_snake(state):
    """
    Snake moves forward by one. 
    If the snake hits itself or the wall, the game is over and is_dead_snake is set to True
    """
    vector_move = __direction_to_vector(state["snake"]["direction"])

    previous_head = state["snake"]["positions"][0]
    new_x = previous_head["x"] + vector_move[0]
    new_y = previous_head["y"] + vector_move[1]

    # Check for collision with wall
    if (new_x < 0 or new_x >= SNAKE_BOARD_WIDTH or
        new_y < 0 or new_y >= SNAKE_BOARD_HEIGHT):
        state["is_dead_snake"] = True
        return state
    for i in range(len(state["snake"]["positions"]) - 1): # skip last one because the snake moves forward
        p = state["snake"]["positions"][i]
        if p["x"] == new_x and p["y"] == new_y:
            state["is_dead_snake"] = True
            return state

    new_snake = [_make_position(x = new_x, y = new_y)]
    if new_x == state["food"]["x"] and new_y == state["food"]["y"]:
        new_snake.extend(state["snake"]["positions"][:])
        new_food = _generate_food_position(new_snake)
        state["food"]["x"] = new_food["x"]
        state["food"]["y"] = new_food["y"]
        state["score"] += 1
    else:
        new_snake.extend(state["snake"]["positions"][0:-1])        

    state["snake"]["positions"] = new_snake
    return state

def _auto_update_tetris(state):
    """
    Attempts to drop the piece by one. If the current tetromino is above the board and cannot drop by one, the game is over and is_dead_tetris is set to True.
    """
    existing_pieces = set([(p["x"], p["y"]) for p in state["tetris_board"]["pieces"]])
    tetromino = copy.deepcopy(state["tetris_board"]["next_tetrominos"][0])
    tetromino["offset_y"] -= 1
    if _tetromino_can_be_there(existing_pieces, tetromino):
        if _tetromino_is_bottom(existing_pieces, tetromino):
            _handle_bottom(state, tetromino)
        else:
            state["tetris_board"]["next_tetrominos"][0] = tetromino
    else:
        state["is_dead_tetris"] = True

    return state

def _rotate_cw(tetromino):
    cx, cy = TETRIS_ROTATE_CENTERS[tetromino["piece_name"]]

    rotated = []
    for p in tetromino["positions"]:
        rotated.append(_make_position(
            x = round((p["y"] - cy) + cx),
            y = round((cx - p["x"]) + cy)))

    return {
        "positions": rotated,
        "offset_x": tetromino["offset_x"],
        "offset_y": tetromino["offset_y"],
        "piece_name": tetromino["piece_name"]
    }

def _handle_bottom(state, tetromino):
    for p in tetromino["positions"]:
        new_x = p["x"] + tetromino["offset_x"]
        new_y = p["y"] + tetromino["offset_y"]
        state["tetris_board"]["pieces"].append(
            {
                "x": new_x, 
                "y": new_y, 
                "piece_name": tetromino["piece_name"]
            })
    state["tetris_board"]["next_tetrominos"][0] = _generate_random_tetromino()

    _clear_lines(state)
    return

def _clear_lines(state):
    row_to_columns = {}
    for p in state["tetris_board"]["pieces"]:
        if p["y"] in row_to_columns:
            row_to_columns[p["y"]].add(p["x"])
        else:
            row_to_columns[p["y"]] = set([p["x"]])

    rows_to_clear = []
    for row, columns in row_to_columns.items():
        if len(columns) == TETRIS_BOARD_WIDTH:
            rows_to_clear.append(row)
    if len(rows_to_clear) == 0:
        return

    how_to_handle_piece = []
    for p in state["tetris_board"]["pieces"]:
        number_to_move_down = 0
        should_clear = False
        for row in rows_to_clear:
            if p["y"] == row:
                should_clear = True
            elif p["y"] > row:
                number_to_move_down += 1
        if should_clear:
            how_to_handle_piece.append(None)
        else:
            how_to_handle_piece.append(number_to_move_down)

    new_pieces = []
    for i in range(len(state["tetris_board"]["pieces"])):
        if how_to_handle_piece[i] == None:
            continue
        current_piece = state["tetris_board"]["pieces"][i]
        new_pieces.append(
            {
                "x": current_piece["x"], 
                "y": current_piece["y"] - how_to_handle_piece[i], 
                "piece_name": current_piece["piece_name"]
            })
    state["tetris_board"]["pieces"] = new_pieces

def _tetromino_can_be_there(existing_pieces, tetromino):
    for p in tetromino["positions"]:
        x = p["x"] + tetromino["offset_x"]
        y = p["y"] + tetromino["offset_y"]
        if (x, y) in existing_pieces:
            return False
        if x < 0 or x >= TETRIS_BOARD_WIDTH:
            return False
        if y < 0:
            return False
    return True

def _tetromino_is_bottom(existing_pieces, tetromino):
    for p in tetromino["positions"]:
        x = p["x"] + tetromino["offset_x"]
        y = p["y"] + tetromino["offset_y"]
        if (x, y - 1) in existing_pieces:
            return True
        if y == 0:
            return True
    return False

def __direction_to_vector(direction):
    if direction == "left":
        return (-1, 0)
    elif direction == "right":
        return (1, 0)
    elif direction == "up":
        return (0, 1)
    elif direction == "down":
        return (0, -1)
    raise InvalidActionError("Not a valid direction")

def __is_perpendicular(v1, v2):
    return (v1[0] * v2[0] + v1[1] * v2[1] == 0)

def get_game_result(state):
    if state["is_dead_snake"] or state["is_dead_tetris"]:
        return {
            "game_result": "SinglePlayerCompleted",
            "winner_idx": 0,
            "score": state["score"]
        }
    return {
        "game_result": "NoWinnerYet"
    }
```

</details>

## Game state schema

```protobuf
message State {
  string user1 = 1;
  Snake snake = 2;
  Position food = 3;
  TetrisBoard tetris_board = 4;
  int32 score = 5;
  bool is_dead_snake = 6;
  bool is_dead_tetris = 7;
  string user_turn = 8;
}
```

```protobuf
message TetrisBoard {
  repeated Position pieces = 1;
  repeated Tetromino next_tetrominos = 2;
}
```

```protobuf
message Tetromino {
  repeated Position positions = 1;
  int32 offset_x = 2;
  int32 offset_y = 3;
  string piece_name = 4;
}
```

```protobuf
message Snake {
  repeated Position positions = 1;
  string direction = 2;
}
```

```protobuf
message Position {
  int32 x = 1;
  int32 y = 2;
}
```

## Action schema

```javascript
move(string direction)
do_nothing()
```

[Start building now](https://botpot.ai/game/snaketetris)


# Checker

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    init_board = [
            -1, 1, -1, 1, -1, 1, -1, 1, 
            1, -1, 1, -1, 1, -1, 1, -1, 
            -1, 1, -1, 1, -1, 1, -1, 1, 
            -1, -1, -1, -1, -1, -1, -1, -1, 
            -1, -1, -1, -1, -1, -1, -1, -1, 
            0, -1, 0, -1, 0, -1, 0, -1, 
            -1, 0, -1, 0, -1, 0, -1, 0, 
            0, -1, 0, -1, 0, -1, 0, -1
        ]
    return {
        "player_turn_idx": 0,
        "board": init_board,
        "valid_moves": _get_all_valid_moves(init_board, 0),
        "no_piece_taken_count": 0
    }

def move(state, start, end):
    board = state['board']
    if start < 0 or start >= 64:
        raise InvalidActionError("Starting position is out of bound")
    if end < 0 or end >= 64:
        raise InvalidActionError("Ending position is out of bound")
    if not _is_empty(board, end):
        raise InvalidActionError("Ending position is not empty")
    valid_moves = state['valid_moves']
    valid_move_tuples = [(move['start'], move['end']) for move in valid_moves]
    if (start, end) not in valid_move_tuples:
        raise InvalidActionError("Not a valid move")

    player_idx = state['player_turn_idx']
    is_piece_taken = False
    if abs(end - start) > 10: # jumped over something
        state['board'][end] = state['board'][start]
        state['board'][start] = -1
        state['board'][int((start + end)/2)] = -1
        is_piece_taken = True
    else: # did not jump over something
        state['board'][end] = state['board'][start]
        state['board'][start] = -1
        state['player_turn_idx'] = (player_idx + 1) % 2
    if player_idx == 0:
        if not _is_king(state['board'], end) and end <= 7:
            state['board'][end] += 2
    else:
        if not _is_king(state['board'], end) and end >= 56:
            state['board'][end] += 2
    
    if is_piece_taken:
        moves_after_jumping = _valid_move(state['board'], end, player_idx)
        more_jump_moves = []
        for next_move_end in moves_after_jumping:
            if _is_jump_move(next_move_end, end):
                more_jump_moves.append({
                    'start': end,
                    'end': next_move_end
                    })
        if len(more_jump_moves) > 0:
            state['valid_moves'] = more_jump_moves
        else:
            state['player_turn_idx'] = (player_idx + 1) % 2
            state['valid_moves'] = _get_all_valid_moves(state['board'], state['player_turn_idx'])
        state['no_piece_taken_count'] = 0
    else:
        state['no_piece_taken_count'] += 1
        state['valid_moves'] = _get_all_valid_moves(state['board'], state['player_turn_idx'])
        
    return state

def get_game_result(state):
    if len(state['valid_moves']) == 0:
        return {
            "game_result": "Winner",
            "winner_idx": 0 if state['player_turn_idx'] == 1 else 0
        }
    if state['no_piece_taken_count'] >= 40:
        return {
            "game_result": "Draw"
        }
    return {
            "game_result": "NoWinnerYet"
        }

def _is_player1_piece(board, index):
    return board[index] == 0 or board[index] == 2

def _is_player2_piece(board, index):
    return board[index] == 1 or board[index] == 3

def _is_empty(board, index):
    return board[index] == -1

def _is_king(board, index):
    return board[index] >= 2

def _index_to_row_column(index):
    return (int(index / 8), index % 8)

def _to_index(row, column):
    return row * 8 + column

def _is_jump_move(start, end):
    return abs(start - end) > 10

def _valid_move(board, start, player_idx):
    if _is_king(board, start):
        directions = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
    elif player_idx == 0:
        directions = [(-1, 1), (-1, -1)]
    else:
        directions = [(1, 1), (1, -1)]

    def _within_bound(row, column):
        return row >= 0 and column >= 0 and row < 8 and column < 8

    def is_opponent(index):
        if player_idx == 0:
            return _is_player2_piece(board, index)
        else:
            return _is_player1_piece(board, index)

    start_r, start_c = _index_to_row_column(start)
    valid_ends = []
    for d_r, d_c in directions:
        if _within_bound(start_r + d_r, start_c + d_c):
            end = _to_index(start_r + d_r, start_c + d_c)
            if _is_empty(board, end):
                valid_ends.append(end)
        if _within_bound(start_r + d_r*2, start_c + d_c*2):
            mid = _to_index(start_r + d_r, start_c + d_c)
            end = _to_index(start_r + d_r*2, start_c + d_c*2)
            if _is_empty(board, end) and is_opponent(mid):
                valid_ends.append(end)
    return valid_ends

def _get_all_valid_moves(board, player_idx):
    is_player1 = (player_idx == 0)
    is_self_func = _is_player1_piece if is_player1 else _is_player2_piece
    moves = []
    for i in range(64):
        if is_self_func(board, i):
            valid_ends = _valid_move(board, i, player_idx)
            for end in valid_ends:
                moves.append({
                    'start': i,
                    'end': end
                    })
    jump_moves = []
    for move in moves:
        if _is_jump_move(move['start'], move['end']):
            jump_moves.append(move)
    if len(jump_moves) > 0:
        return jump_moves
    return moves
```

</details>

## Game state schema

```protobuf
message State {
  string user1 = 1;
  string user2 = 2;
  string user_turn = 3;
  repeated int32 board = 4;
  repeated ValidMove valid_moves = 5;
  int32 no_piece_taken_count = 6;
}
```

```protobuf
message ValidMove {
  int32 start = 1;
  int32 end = 2;
}
```

## Action schema

```javascript
move(int start, int end)
```

[Start building now](https://botpot.ai/game/checker)


# Generals

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random

def init_game(game_settings):
    width = 10
    height = 10
    mountain_count = 10
    tower_count = 2

    board_list = []
    for i in range(mountain_count):
        board_list.append(_build_tile('mountain', 0))
    for i in range(tower_count):
        board_list.append(_build_tile('tower', 40))
    board_list.append(_build_tile('king', 1, 0))
    board_list.append(_build_tile('king', 1, 1))
    for i in range(width*height - len(board_list)):
        board_list.append(_build_tile('regular', 0, None))

    board = _make_2d_board(board_list, width, height)
    return {
        "player_turn_idx": 0,
        "player1_total_count": 1,
        "player2_total_count": 1,
        "board": board,
        "round": 0,
        "board_width": width,
        "board_height": height
    }

def _build_tile(tile_type, count, tile_player_idx = None, is_visible = True):
    return {
        'type': tile_type,
        'tile_player_idx': tile_player_idx,
        'count': count,
        'is_visible': is_visible
    }

def _make_2d_board(board_list, width, height):
    random.shuffle(board_list)
    index = 0
    board = []
    for r in range(height):
        row = []
        for c in range(width):
            row.append(board_list[index])
            index += 1
        board.append(row)
    return board

def _is_out_of_bound(row, column, board):
    if row < 0 or row >= len(board):
        return True
    if column < 0 or column >= len(board[row]):
        return  True
    return False

def move(state, row, column, direction, move_half):
    board = state['board']
    if _is_out_of_bound(row, column, board):
        raise InvalidActionError("Start position is out of bound")
    start_piece = board[row][column]
    player_idx = state['player_turn_idx']
    if start_piece["tile_player_idx"] != player_idx:
        raise InvalidActionError("Cannot move from a tile you do not control")

    end_row = row
    end_column = column
    if direction == "UP":
        end_row -= 1
        if end_row < 0:
            raise InvalidActionError("Moving out of bound")
    elif direction == "DOWN":
        end_row += 1
        if end_row >= len(board):
            raise InvalidActionError("Moving out of bound")
    elif direction == "LEFT":
        end_column -= 1
        if end_column < 0:
            raise InvalidActionError("Moving out of bound")
    elif direction == "RIGHT":
        end_column += 1
        if end_column >= len(board[row]):
            raise InvalidActionError("Moving out of bound")
    else:
        raise InvalidActionError("Direction should be UP, DOWN, LEFT, or RIGHT")

    
    end_piece = board[end_row][end_column]
    number_to_move = int(start_piece["count"]/2) if move_half else start_piece["count"] - 1
    number_to_move = max(number_to_move, 0)

    if end_piece["type"] != "mountain":
        start_piece["count"] -= number_to_move
        if end_piece["tile_player_idx"] == None:
            end_piece["count"] -= number_to_move
        elif end_piece["tile_player_idx"] == start_piece["tile_player_idx"]:
            end_piece["count"] += number_to_move
        else:
            end_piece["count"] -= number_to_move

        if end_piece["count"] < 0:
            end_piece["count"] = -end_piece["count"]
            end_piece["tile_player_idx"] = player_idx

    state = _auto_update(state)
    state = _recompute_count(state)
    return state

def _recompute_count(state):
    player1_count = 0
    player2_count = 0
    for row in state["board"]:
        for piece in row:
            if piece["tile_player_idx"] == 0:
                player1_count += piece["count"]
            if piece["tile_player_idx"] == 1:
                player2_count += piece["count"]
    state["player1_total_count"] = player1_count
    state["player2_total_count"] = player2_count
    return state

def do_nothing(state):
    state = _auto_update(state)
    state = _recompute_count(state)
    return state

def _auto_update(state):
    player_idx = state['player_turn_idx']
    if player_idx == 0:
        state["player_turn_idx"] = 1
        return state
    state["player_turn_idx"] = 0
    

    if state["round"] % 25 == 0:
        for row in state["board"]:
            for piece in row:
                if piece["tile_player_idx"] != None:
                    piece["count"] += 1 
    else:
        for row in state["board"]:
            for piece in row:
                piece_type = piece["type"]
                if (piece_type == "tower" or piece_type == "king") and piece["tile_player_idx"] != None:
                    piece["count"] += 1 

    state["round"] += 1
    return state

def get_game_result(state):
    has_player1 = False
    has_player2 = False
    for row in state["board"]:
        for piece in row:
            if piece["tile_player_idx"] == 0:
                if piece["type"] == "king":
                    has_player1 = True
            if piece["tile_player_idx"] == 1:
                if piece["type"] == "king":
                    has_player2 = True
    if has_player1 and not has_player2:
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    if has_player2 and not has_player1:
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    if state["round"] > 500:
        if state["player1_total_count"] == state["player2_total_count"]:
            return {
                "game_result": "Draw"
            }
        elif state["player1_total_count"] > state["player2_total_count"]:
            return {
                "game_result": "Winner",
                "winner_idx": 0
            }
        else:
            return {
                "game_result": "Winner",
                "winner_idx": 1
            }
    return {
            "game_result": "NoWinnerYet"
        }

def _get_visible(state, player_idx):
    initial_visible = set()
    visible = set()
    board = state["board"]
    for row_idx, row in enumerate(board):
        for column_idx, piece in enumerate(row):
            if piece["tile_player_idx"] == player_idx:
                visible.add((row_idx, column_idx))
                initial_visible.add((row_idx, column_idx))
    for r, c in initial_visible:
        for i in [-1, 0, 1]:
            for j in [-1, 0, 1]:
                if not _is_out_of_bound(r + i, c + j, board):
                    visible.add((r + i, c + j))
    return visible


def get_player_states(state):
    player_states = []
    for i in range(2):
        visible_coordinates = _get_visible(state, i)
        player_board = []
        for row_idx, row in enumerate(state["board"]):
            player_board.append([])
            for column_idx, piece in enumerate(row):
                if (row_idx, column_idx) in visible_coordinates:
                    player_board[row_idx].append(piece)
                elif piece["type"] == "mountain":
                    player_board[row_idx].append(piece)
                else:
                    player_board[row_idx].append(_build_tile('regular', 0, None, False))
        
        player_states.append({
            "player_turn_idx": state["player_turn_idx"],
            "board": player_board,
            "round": state["round"],
            "board_width": state["board_width"],
            "board_height": state["board_height"],
            "player1_total_count": state["player1_total_count"],
            "player2_total_count": state["player2_total_count"]
        })
    return player_states
```

</details>

## Game state schema

```protobuf
message State {
  int32 player_turn_idx = 1;
  int32 player1_total_count = 2;
  int32 player2_total_count = 3;
  repeated Tile board = 4 [packed = true];
  int32 round = 5;
  int32 board_width = 6;
  int32 board_height = 7;
}
```

```protobuf
message Tile {
    string tile_type = 1;
    int32 tile_player_idx = 2;
    int32 count = 3;
    bool is_visible = 4;
}
```

## Action schema

```javascript
move(int row, int column, string direction, bool move_half)
do_nothing()
```

[Start building now](https://botpot.ai/game/generals)


# Blokus

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings, ref_data):
    player_count = int(game_settings["Player Count"])
    required_positions = [
        {
            "positions": [{"x": 0, "y": 0}]
        },
        {
            "positions": [{"x": 19, "y": 0}]
        }, 
        {
            "positions": [{"x": 19, "y": 19}]
        },
        {
            "positions": [{"x": 0, "y": 19}]
        }
    ]
    
    return {
        "player_hands": [list(range(len(ref_data["piece_templates"]))) for i in range(4)],
        "game_board": [-1]*(20*20),
        "players_unavailable_spots": [{
            "unavailable_spots": [0]*(20*20)
        } for i in range(4)],
        "scores": [0]*player_count,
        "skips": 0,
        "required_positions": required_positions,
        "player_turn_idx": 0,
        "player_idx_to_play": 0,
        "player_idx_to_play_fourth_color": 0 if player_count == 3 else None
    }

def place_piece(state, ref_data, piece_idx, orientation_idx, offset_x, offset_y):
    player_idx = state["player_idx_to_play"]
    if piece_idx not in state["player_hands"][player_idx]:
        raise InvalidActionError("piece_idx not in the player's hand")

    if orientation_idx < 0 or orientation_idx >= len(ref_data["piece_templates"][piece_idx]["all_orientations"]):
        raise InvalidActionError("orientation_idx out of bound")
    piece = ref_data["piece_templates"][piece_idx]["all_orientations"][orientation_idx]

    board = state["game_board"]
    positions, sides, corners = _convert_pos_to_coordinate_tuples(piece, offset_x, offset_y)
    required_positions = state["required_positions"][player_idx]["positions"]
    required_positions = set([(pos["x"], pos["y"]) for pos in required_positions])

    is_required_position_met = False
    for x, y in positions:
        if x < 0 or y < 0 or x >= 20 or y >= 20:
            raise InvalidActionError("Placing this piece here goes out of the board")
        if board[_coordinate_to_index(x, y)] != -1:
            raise InvalidActionError("Piece overlaps with another on the board")
        if (x, y) in required_positions:
            is_required_position_met = True
    if not is_required_position_met:
        raise InvalidActionError("Piece must be placed in one of the required positions (check if it touches the corner of another one of your piece)")

    for x, y in sides:
        if x < 0 or y < 0 or x >= 20 or y >= 20:
            continue
        if board[_coordinate_to_index(x, y)] == player_idx:
            raise InvalidActionError("The side of this piece touches another one of your own pieces")

    # Place the piece and update all the other helper fields
    for x, y in positions:
        index = _coordinate_to_index(x, y)
        board[index] = player_idx
        for unavailable_spots in state["players_unavailable_spots"]:
            unavailable_spots["unavailable_spots"][index] = 1

    for x, y in sides:
        if x < 0 or y < 0 or x >= 20 or y >= 20:
            continue
        state["players_unavailable_spots"][player_idx]["unavailable_spots"][_coordinate_to_index(x, y)] = 1

    for x, y in corners:
        if x >= 0 and y >= 0 and x < 20 and y < 20:
            state["required_positions"][player_idx]["positions"].append({"x": x, "y": y})

    state["player_hands"][player_idx].remove(piece_idx)
    state = _sanitize_required_positions(state, player_idx)
    state["game_board"] = board
    state["skips"] = 0
    state = _update_score(state, len(positions))
    state = _update_player_turns(state)
    return state

def pass_turn(state, ref_data):
    state["skips"] += 1
    state = _update_player_turns(state)
    return state

def get_game_result(state, ref_data):
    if state["skips"] == len(state["scores"]):
        reversed_scores = state["scores"][::-1] # if scores are equal, last player to move wins
        return {
            "game_result": "Winner",
            "winner_idx": len(reversed_scores) - 1 - reversed_scores.index(max(reversed_scores))
        }
    return {
            "game_result": "NoWinnerYet"
        }

def _convert_pos_to_coordinate_tuples(piece, offset_x, offset_y):
    positions = [(pos["x"] + offset_x, pos["y"] + offset_y) for pos in piece["pos"]]
    sides = [(side["x"] + offset_x, side["y"] + offset_y) for side in piece["side"]]
    corners = [(corner["x"] + offset_x, corner["y"] + offset_y) for corner in piece["corner"]]
    return positions, sides, corners

def _coordinate_to_index(x, y):
    return x + y*20

def _sanitize_required_positions(state, player_idx):
    required_positions = state["required_positions"]
    players_unavailable_spots = state["players_unavailable_spots"]
    board = state["game_board"]

    new_required_positions = []
    for i in range(4):
        required = required_positions[i]
        unavailable_spots = players_unavailable_spots[i]["unavailable_spots"]
        new_required = []
        for pos in required["positions"]:
            index = _coordinate_to_index(pos["x"], pos["y"])
            if unavailable_spots[index] == 1:
                continue # this spot is no longer available, so it is not required
            
            if board[index] == -1:
                new_required.append(pos)
        new_required_positions.append({
            "positions": new_required
            })
    state["required_positions"] = new_required_positions
    return state

def _update_score(state, score):
    num_of_players = len(state["scores"])
    if num_of_players == 2 or num_of_players == 4:
        state["scores"][state["player_idx_to_play"] % num_of_players] += score
    elif num_of_players == 3:
        if state["player_idx_to_play"] != 3:
            state["scores"][state["player_idx_to_play"]] += score
    
    return state

def _update_player_turns(state):
    state["player_idx_to_play"] = (state["player_idx_to_play"] + 1) % 4 # colors always increment

    num_of_players = len(state["scores"])
    if num_of_players == 2 or num_of_players == 4:
        state["player_turn_idx"] = state["player_idx_to_play"] % num_of_players
    elif num_of_players == 3:
        if state["player_idx_to_play"] == 3:
            state["player_turn_idx"] = state["player_idx_to_play_fourth_color"]
            state["player_idx_to_play_fourth_color"] = (state["player_idx_to_play_fourth_color"] + 1) % 3
        else:
            state["player_turn_idx"] = state["player_idx_to_play"]
    
    return state
```

</details>

## Game state schema

```protobuf
message State {
  repeated int32 player_hands = 1;
  repeated int32 game_board = 2;
  repeated UnavailableSpots players_unavailable_spots = 3;
  int32 player_turn_idx = 4;
  repeated int32 scores = 5;
  int32 skips = 6;
  repeated RequiredPositions required_positions = 7;
  int32 player_idx_to_play = 8;
  int32 player_idx_to_play_fourth_color = 9;
}
```

```protobuf
message Orientation {
  repeated Position pos = 1;
  repeated Position side = 2;
  repeated Position corner = 3;
}
```

```protobuf
message PieceTemplate {
  repeated Orientation all_orientations = 1;
}
```

```protobuf
message RefData {
  repeated PieceTemplate piece_templates = 1;
}
```

```protobuf
message RequiredPositions {
  repeated Position positions = 1;
}
```

```protobuf
message Position {
  int32 x = 1;
  int32 y = 1;
}
```

```protobuf
message UnavailableSpots {
  repeated int32 unavailable_spots = 1;
}
```

## Action schema

```javascript
place_piece(int piece_idx, int orientation_idx, int offset_x, int offset_y)
pass_turn()
```

[Start building now](https://botpot.ai/game/blokus)


# Wordle

## Game logic

<details>

<summary>Game Logic code</summary>

```python
import random
round_count = 20
def init_game(game_settings, ref_data):
    return {
        "player_turn_idx": 0,
        "answers": [random.choice(ref_data["words"]).upper() for i in range(round_count)],
        "round_index": 0,
        "guesses_each_round": [{
            "guesses": []
        } for i in range(round_count)],
        "scores": []
    }

def guess(state, ref_data, word):
    if len(word) != 5:
        raise InvalidActionError("Guesses should be 5 letters long")
    word = word.upper()
    round_index = state["round_index"]
    target = state["answers"][round_index]
    letter_bag = list(target)
    result = ['', '', '', '', '']

    for i in range(len(word)):
        if word[i] == target[i]:
            result[i] = 'G'
            letter_bag.remove(word[i])
    for i in range(len(word)):
        if result[i] == 'G':
            continue
        if word[i] in letter_bag:
            result[i] = 'Y'
            letter_bag.remove(word[i])
        else:
            result[i] = 'B'
    guesses_this_round = state["guesses_each_round"][round_index]["guesses"]
    guesses_this_round.append({
            "guess": word,
            "result": "".join(result)
        })

    if word == target or len(guesses_this_round) == 6:
        if round_index < round_count - 1:
            state["round_index"] += 1
        if word == target:
            if len(guesses_this_round) == 1:
                state["scores"].append(10)
            elif len(guesses_this_round) == 2:
                state["scores"].append(10)
            elif len(guesses_this_round) == 3:
                state["scores"].append(6)
            elif len(guesses_this_round) == 4:
                state["scores"].append(3)
            elif len(guesses_this_round) == 5:
                state["scores"].append(2)
            elif len(guesses_this_round) == 6:
                state["scores"].append(1)
        else:
            state["scores"].append(-5)

    return state

def get_game_result(state, ref_data):
    round_index = state["round_index"]
    target = state["answers"][round_index]
    guesses_this_round = state["guesses_each_round"][round_index]["guesses"]
    if (round_index == round_count - 1 and 
        len(guesses_this_round) > 0 and 
        (len(guesses_this_round) == 6 or guesses_this_round[-1]["guess"] == target)):
        return {
            "game_result": "SinglePlayerCompleted",
            "winner_idx": 0,
            "score": sum(state["scores"])
        }

    return {
        "game_result": "NoWinnerYet",
    }


def get_player_states(state, ref_data):
    player_states = []
    round_index = state["round_index"]
    target = state["answers"][round_index]
    guesses_this_round = state["guesses_each_round"][round_index]["guesses"]
    for i in range(1):
        obfuscated_answers = []
        for i in range(len(state["answers"])):
            if round_index > i:
                obfuscated_answers.append(state["answers"][i])
            elif round_index == i and len(state["guesses_each_round"][round_index]["guesses"]) == 6:
                obfuscated_answers.append(state["answers"][i])
            elif round_index == i and len(guesses_this_round) > 0 and guesses_this_round[-1]["guess"] == target:
                obfuscated_answers.append(state["answers"][i])
            else:
                obfuscated_answers.append("*****")
        player_states.append({
            "player_turn_idx": state["player_turn_idx"],
            "round_index": state["round_index"],
            "guesses_each_round": state["guesses_each_round"],
            "scores": state["scores"],
            "answers": obfuscated_answers
        })
    return player_states

```

</details>

## Game state schema

```protobuf
message State {
  int32 player_turn_idx = 1;
  int32 round_index = 2;
  repeated GuessesEachRound = 3;
  repeated int32 scores = 4;
  repeated string answers = 5;
}
```

```protobuf
message GuessesEachRound {
  repeated Guess guesses = 1;
}
```

```protobuf
message Guess {
  string guess = 1;
  string result = 2;
}
```

```protobuf
message refData {
  repeated string words = 1;
}
```

## Action schema

```javascript
guess(string word)
```

[Start building now](https://botpot.ai/game/wordle)


# Chinese Checker

## Game logic

<details>

<summary>Game Logic code</summary>

```python
def init_game(game_settings):
    state = {
        "player_turn_idx": 0,
        "board": [[-1]*9 for i in range(9)],
        "players": [[None]*10, [None]*10],
        "last_jumped": None,
        "turn": 0
    }
    count = 0
    for i in range(4):
        for j in range(i+1):
            _set_piece(state, 0, count, 3 - i, j)
            _set_piece(state, 1, count, 5 + i, 8 - j)
            count += 1
    return state

def move(state, piece_idx, x, y):
    if not _within_bound(x, y):
        raise InvalidActionError("Coordinte out of bound. Should be between 0 and 8.")
    if piece_idx < 0 or piece_idx >= 10:
        raise InvalidActionError("piece_idx out of bound. Should be between 0 and 9.")
    board = state['board']
    if board[x][y] != -1:
        raise InvalidActionError("There is already a piece at this target coordinate.")
    player_turn_idx = state['player_turn_idx']
    start = state['players'][player_turn_idx][piece_idx]
    start_x = start['x']
    start_y = start['y']

    if _is_adjacent(start_x, start_y, x, y):
        if state['last_jumped'] is not None:
            raise InvalidActionError("This piece must be used to jump over another piece.")
        board[start_x][start_y] = -1
        _set_piece(state, player_turn_idx, piece_idx, x, y)
        state['player_turn_idx'] = (player_turn_idx + 1)%2
        state['turn'] += 1
        return state
    skipped = _is_skip_adjacent(start_x, start_y, x, y)
    if skipped and board[skipped[0]][skipped[1]] != -1:
        if state['last_jumped'] is not None:
            last_jumped = state['last_jumped']
            if last_jumped['piece_idx'] != piece_idx:
                raise InvalidActionError(f"Must use piece {piece_idx} to jump or make a done_move.")
            if last_jumped['last_x'] == x and last_jumped['last_y'] == y:
                raise InvalidActionError(f"Cannot jump back to a previous location.")
        state['board'][start_x][start_y] = -1
        _set_piece(state, player_turn_idx, piece_idx, x, y)
        state['last_jumped'] = {
            'piece_idx': piece_idx,
            'last_x': start_x,
            'last_y': start_y
        }
        return state
    raise InvalidActionError("Cannot move this piece to the target position.")

def done_move(state):
    if state['last_jumped'] is None:
        raise InvalidActionError(f"Cannot make a done_move when you haven't jumped previously.")
    state['player_turn_idx'] = (state['player_turn_idx'] + 1)%2
    state['last_jumped'] = None
    state['turn'] += 1
    return state

def get_game_result(state):
    board = state['board']
    count_player_1 = 0
    count_player_2 = 0
    for i in range(4):
        for j in range(i+1):
            if board[3-i][j] == 1:
                count_player_2 += 1
            if board[5+i][8-j] == 0:
                count_player_1 += 1
    if count_player_1 == 10:
        return {
            "game_result": "Winner",
            "winner_idx": 0
        }
    elif count_player_2 == 10:
        return {
            "game_result": "Winner",
            "winner_idx": 1
        }
    if state['turn'] >= 300:
        if count_player_1 == 0 and count_player_2 == 0:
            return {
                "game_result": "Draw",
            }
        return {
            "game_result": "Winner",
            "winner_idx": 0 if count_player_1 > count_player_2 else 1
        }
    return {
        "game_result": "NoWinnerYet",
    }


def _within_bound(x, y):
    if x < 0 or y < 0 or x >= 9 or y >= 9:
        return False
    return True

def _set_piece(state, player_idx, piece_idx, x, y):
    state["board"][x][y] = player_idx
    state["players"][player_idx][piece_idx] = {
        "x": x,
        "y": y
    }

def _is_adjacent(start_x, start_y, target_x, target_y):
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, -1), (-1, 1)]
    for dir_x, dir_y in directions:
        if target_x - start_x == dir_x and target_y - start_y == dir_y:
            return True
    return False

def _is_skip_adjacent(start_x, start_y, target_x, target_y):
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, -1), (-1, 1)]
    for dir_x, dir_y in directions:
        if target_x - start_x == dir_x*2 and target_y - start_y == dir_y*2:
            return (start_x + dir_x, start_y + dir_y)
    return None
```

</details>

## Game state schema

```protobuf
message State {
  // Required field to indicate the player who should be making the next move
  // Values = 0 or 1
  int32 player_turn_idx = 1;

  repeated int32 board = 2;
}
```

## Action schema

```javascript
move(int piece_idx, int x, int y)
done_move()
```

[Start building now](https://botpot.ai/game/chinesechecker)


