definit_game(game_settings): state ={"player_turn_idx":0,"board": [-1,-1,-1,-1,-1,-1,-1,-1,-1]}return statedefplace_piece(state,index):if index <0or index >8:raiseInvalidActionError("Index out of bound")if state["board"][index] !=-1:raiseInvalidActionError("Someone already placed a piece here") state["board"][index] = state["player_turn_idx"] state["player_turn_idx"]= (state["player_turn_idx"]+1) %2return statedefget_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 inrange(0, 3):if state["board"][i*3] == value and state["board"][i*3+1] == value and state["board"][i*3+2] == value:returnTrueif state["board"][i] == value and state["board"][i +3] == value and state["board"][i +6] == value:returnTrueif state["board"][0] == value and state["board"][4] == value and state["board"][8] == value:returnTrueif state["board"][2] == value and state["board"][4] == value and state["board"][6] == value:returnTruereturnFalse
Game state schema
message State {// Required field to indicate the player who should be making the next move// Values = 0 or 1int32 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. */repeatedint32 board =2;}