On this page, you'll make the computer play against the human player.
The game currently allows two human players to take turns playing. But you don't really need a computer to keep track of moves for two human players. We want the human player to take turns with a computer player that will move automatically. To simplify the project, we'll assume that the human player will always move first (playing X) and that the computer is playing O.
For now, you'll create a computer player that moves to random positions on the board. (It won't be a very good player, but you'll fix that once the structure of the code for the computer's move is in place.) Once the program decides where it wants to move, you'll use broadcast
to send a message to tell the clone with the matching position number to record a move. (For the human player, when I am clicked
serves this purpose, but the computer's moves aren't prompted by the user clicking a square.)
Broadcast
sends out a message to all the sprites in the project. Any scripts that start with when I receive
and have a matching message in the input slot will run.
The message
reporter reports the most recent message sent out.
when I am clicked
script, use broadcast
with a random number...broadcast
with a random number from 1 to 9 as the message. (The computer will move in the corresponding square, once you've written the code to handle the message.)when I receive
script that will accept any message as input. If the position number for the clone matches the message
, make the computer move in the correct clone's space and check for a win or a tie.when I am clicked
to when I receive
, move that code into a custom block and call the custom block from both scripts. This is one of the ways to use abstraction in programming: don't have two copies of the same piece of code; instead, give it a name.make board
, and ensure that the parent's position number isn't 1-9 so that it doesn't conflict with a clone.Also: we have no note about removing the Player O code, which we might consider adding, and the orange box in #3 is too late; I'd already done copy and paste before I saw it. Our directions really inspire "just doing what it says without thinking" I'm not sure what to do about that... (BTW, should we have said that earlier? I can't find a good place because we build up the code slowly, but I wondered it.) --MF, 9/6/18
Instead of having the computer move at random, you will start to give the computer some strategy. Unlike people, all squares on the tic-tac-toe board are not created equal. Playing in the center (position 5) or on a corner (positions 1, 3, 7, or 9) is better than playing on an edge (positions 2, 4, 6, or 8).
broadcast
instruction in place of random
.