Editing the Code
Once you are ready to start improving your bot you should draw your attention to the calculate_move() function, this is where all the action happens. This function is called every time the server wants you to make a move. It receives a dictionary of information containing the state of the game, namely the gamestate. For greater detail on the contents of the gamestate check out the Understanding The Gamestate section of our Noughts And Crosses Quick Reference Guide.
From this information it is your task to determine where you want to move next.
You can specify your move by returning a valid dictionary of the form specified in the Making A Valid Move section of our Quick Reference Guide from the calculate_move() function.
For example:
def calculate_move(gamestate): move = {"Position": 4} return move
Case Study
Let’s say we would like to implement the following strategy:
- Prioritise moving into the centre first.
- If we can't, try moving into one of the corners.
- If we still can't, move into one of the edges.
The code looks like the following:
from random import choice def calculate_move(gamestate): if(gamestate["Board"][4] == " "): # If the middle is available move = {"Position": 4} # Move in the middle elif(gamestate["Board"][0] == " " or gamestate["Board"][2] == " " or gamestate["Board"][6] == " " or gamestate["Board"][8] == " "): # If one of the corners is available options = [0,2,6,8] move = {"Position": choice(options)} while(gamestate["Board"][move] != " "): # Keep randomly choosing a corner until an empty one is chosen move = {"Position": choice(options)} # Move to that empty corner else: # Otherwise guess edges options = [1,3,5,7] move = {"Position": choice(options)} while(gamestate["Board"][move] != " "): # Keep randomly choosing an edge until an empty one is chosen move = {"Position": choice(options)} # Move to that empty edge return move
Suggested reading…
Quick Reference Guide
