Tic-Tac-Toe
Game logic
Game Logic code
def init_game(game_settings):
state = {
"player_turn_idx": 0,
"board": [-1, -1, -1, -1, -1, -1, -1, -1, -1]
}
return state
def place_piece(state, index):
if index < 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
Game state schema
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
place_piece(int index)
Last updated