Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s...

31
Kids Coding Club East Tic Tac Toe Project - Student Version Tyler Bounds Last Updated: July 28, 2017 1

Transcript of Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s...

Page 1: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Kids Coding Club East Tic Tac Toe Project - Student Version

Tyler Bounds

Last Updated: July 28, 2017

1

Page 2: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Introduction

This document is to help guide you through a Tic Tac Toe game for Scratch. These instructions are intentionallyincomplete in order to provide you with an opportunity to challenge yourself. Do not worry! If you get stuck, trytaking a break for a bit. If you come back later and are still stuck, you can always look at the completed project onmy Scratch account: TBounds42 or ask your parents for help.

What You Will Learn

By the end of this project, not only will you have learned one way to make a Tic Tac Toe game but also some othervaluable skills and information:

• How to use Scratch’s pen tools to create adjustable game elements.

• The importance of math and logic for creating particular game behaviors.

• How to break down problems into codeable solutions.

• How to communicate between sprites.

• How to use lists to represent game cells.

• How to incorporate someone else’s Scratch project/tool into your own project.

This is just one way to make a Tic Tac Toe game! And even others like this one will be different! Don’t worry ifyour solution is different or if you have a different idea, try it out!

First Step - Drawing the X Token

Because we want things to be highly adjustable we want to use Scratch’s pen tools to draw as much of the game’selements as possible. In this case, this includes: the game board, the game tokens (X and O), and the line that isdrawn over the winning tokens. There is no particular order of importance here, we could pick any to start with.Let’s start with the X Token.

In order to draw things in Scratch, we need a sprite. You can use the default cat sprite that is included in a newproject or delete that one and use another. In this case, I deleted the cat sprite and made my own. Either way,right-click your chosen sprite and select info. Change the sprites name to painter or something that indicates thatthis sprite is used for drawing.

Your painter sprite should now be visible in your stage. Eventually, we will hide it but for now it is fine as it is. Goto the scripts tab of your painter sprite.

We will now define our own block for drawing the X token. Remember, it is good practice to keep things separatedin their own blocks if you can. This makes things compartmentalized and easier to debug and use.

2

Page 3: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Make a block that looks something like this:

In the block options, make sure that Run without screen refresh is NOT checked. No block in this project willhave that checked unless you want to use it.

These input parameters are what we are going to use to draw an X token at a particular location, with a certainheight, thickness, and angle. These parameters are also what make it adjustable.

To go into more detail, the inputs x and y make the point (x, y) where we want the center of our X token to be.The height is how tall in pixels we want our X token to be. Thickness is how thick the lines are drawn. The inputangle theta will be used to change the angle of our pen strokes. Look at the following diagram for a better idea:

As you can see, if we do this correctly, we can draw an X token with two strokes. However, with how we haveset it up currently, that will be impossible because the painter will start at the center. The first step should beto move the painter to the top of the stroke first using a go to x: y: block. Because height is given to us asan input, it’s fairly simple to move the painter to the correct y position. Moving the painter to the correct x po-sition requires us to know the width of the X token but width is not an input. We will have to calculate this ourselves.

In the data tab, create a new variable that is for this sprite only and name it something like xTokenWidth.Connect a set xTokenWidth to block to our Draw X Token block. We want to set this variable to the widththe X token needs to be. A hint is that you will need to use trigonometry, specifically the equation for solving sidesof a right triangle.

3

Page 4: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Your Draw X Token block should look like this:

Now that we have calculated the width, moving the painter to the correct point is fairly simple. Just remember thatwe are moving from the center to the top-left, meaning that we only need to move half of the height and width.Connect a go to x: y: block with the appropriate operations to move the painter to the top-left of the X token.

Next make sure to place a pen down block before moving the painter to the bottom-right of the X token. If youwant the X token to just kind of appear, use the regular go to x: y: block. Otherwise, if you want it to look likethe token was drawn, use the glide motion block. Moving the painter to the bottom-right of the X token is basicallythe same thing as moving it to the top-left.

Follow this kind of thinking for the other stroke and make sure to finish with a pen up block. This prevents drawinglines by mistake. For redundant safety, you could also always start with a pen up block before moving. Also, donot forget to use your thickness input to set the pen size.

This finishes the the Draw X Token block, which should look like this:

4

Page 5: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

It’s always a good idea to test things when you can. Because this is a guide, I’m only going to remind you to testthings after they are complete. I highly recommend that, as you code, you come up with ways to test your code tomake sure things are behaving as expected.

Here is what I used to test my Draw X Token:

It’s okay if you don’t fully get what’s going on here. I will explain this later on. You can either just use this or writeyour own way to test your code.

5

Page 6: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Drawing the O Token

This process is going to be fairly similar to making the Draw X Token block. To begin, make a new block that lookslike this:

Let’s go over the intention for each of the inputs.

• (x,y) - specify where the center of the O token should be.

• radius - specifies how large the radius of the O token should be.

• thickness - specifies the thickness of the lines that make up the O token.

• edges - specifies how many edges to make the O token with.

Because of limitations with Scratch, we’re going to limit the number of edges so that we get a roughly circular shapethat still draws relatively quickly while also maintaining simple code. Look at the following diagram for a betteridea:

The general idea for this circle drawing method is to draw an edge by stepping forward, turning, stepping forward,turning, etc. until the circle is complete. Because we are given the number of edges we can calculate the angle we

need to turn in order to complete the circle. This is simply:360

# of edges

To adhere to the specified radius in the inputs, we have to find out the necessary length for each edge. A hinton how to solve this is to use the equation for the circumference of a circle and then substitute (# of edges * edgelength) for C (circumference) and then solve the equation for edge length.

To store the result of this calculation, create a new variable for this sprite only named circleEdgeLength. Makesure to use the set circleEdgeLength to block to set the value of circleEdgeLength.

6

Page 7: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Your Draw O Token block should look like this:

The next step is to adjust the position of the painter so that it begins drawing at the top of the circle and centeredaround (x,y). Because radius is given to us, adjusting the y position is simple. All we need to do is add the radiusto the painter’s starting position.

Adjusting the x position is simple as well but the tricky part is knowing what you have to do and why. Because weare using straight edges we actually need the painter to start off center in order to compensate. Look at the followingdiagram for clarification:

Connect a go to x: y: block and add the necessary operator blocks to adjust the painter’s position. Also, be-cause we are going to use the move steps block, we need to make sure the painter is facing the correct direction,which is to the right. Connect a point in direction block and set its value to 90 if it is not already. We’re goingto start moving the painter next so now is the time to add the pen down block.

7

Page 8: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Your Draw O Token block should look like this:

From here, we need to use the repeat block for the number of edges. And this is what we need to repeat:

• move circleEdgeLength steps

• turn degrees - which is something we calculated earlier in this document.

Make sure to add the set pen size to block and finish with a pen up block. This finishes the Draw O Tokenblock which should look like:

Remember to test this code to make sure this is working as you would expect. You can modify the previous testcode or add to it.

8

Page 9: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Drawing the Game Board

Drawing the game board is a little simpler, as it is just four lines. However, the board is square and the stage isrectangular. Also, we want to be able to adjust the size of the board to make it larger or smaller. The solution Icame up with was to add some horizontal offset to make the stage, at the largest, 360px by 360px. Look at thefollowing diagram for clarification:

The idea is that now the stage is square, we can just add a border within that square and draw the board withinthat border. To make the board larger, the border would need to be smaller. To make the board smaller, the bor-der needs to be larger. Hopefully this will make more sense as you code and play with it but here’s a visual of the idea:

9

Page 10: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

For now, make a new block that looks like this:

Now let’s tackle creating that offset for our stage. The way I did that was by first creating a variable horizontal-BoardOffset for the painter and then set it’s value to 180 after the flag is pressed, like so:

The offset I actually want is 60px from the left edge. However, because the origin is in the center of the stage whatI decided to do was limit how far I can draw to 180px horizontally from the origin. This works because half of thestage’s horizontal space is 240px. 240px - 180px = 60px, which creates the desired 60px offset. This does meanhowever that the variable name is kind of misleading. A better name perhaps could be, horizontalHalfStage-DrawDistance but we will stick with horizontalBoardOffset. Descriptive variable names can be difficult butthey are important!

To make drawing certain things easier, we should calculate the size of half of a cell of the game board. A cell is

one square of the game board. There’s a few ways to do this. The simplest way is probably:StageWidth− border

6

Remember to make a variable for this sprite only for this data and set its value. The variable name I usedwas cellHalfSize. As there is no way to change the stage size, StageWidth at this point can safely be 360.Remember, border is an input so do not worry what its value is. However, we will need its value in a differentscript (still in the painter sprite) so make a variable for this sprite only to save its value, I called mine stageBorder

Let’s begin with the upper-most horizontal game board line. The idea is to move the painter sprite as far left thatis still within the border and then the appropriate distance up from the origin. First, horizontal: we want to moveto x = (-horizontalBoardOffset + border). This will start the line at the edge of the border. Now because wewant to center everything around the origin, we only need to move to y = cellHalfSize.

10

Page 11: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Make sure to put the pen down and then move or glide to x = horizontalBorderOffset - border. The y positionneeds to stay the same. Also, do not forget to lift the pen up before continuing. You could also add your set pensize to block now if you wanted. Your Draw Board block should look like this:

My cellHalfSize value may look different than yours but it is equivalent, so don’t worry about that too much. Therest of the board line drawing is very similar so continue along this path and remember to test your code.

11

Page 12: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Clicking Inside the Game Board

The next thing we want to do is to be able to distinguish which cells we click so that we can place a game token inthe center of them.

The way were are going to do this is to transform the stage’s coordinate system into something more useful tous. Ideally, what we want to transform it into is something that maps to a 3x3 matrix. Currently, say if youwere to click into the upper-left cell of the game board and printed out the mouse coordinates, what would bedisplayed? The x-coordinate would probably be some negative number and the y-coordinate would be positive. Butyou could get different coordinate pairs (a point) that were still in the same cell. What we want is when we clickthat cell we get x = 1 and y = 1 no matter where you click in that cell. Look at the following diagram for a better idea:

So what exactly is it that we want to transform? It’s not like we can actually change Scratch’s stage coordinatesystem, and we probably wouldn’t want to anyway. What we need to transform is the mouse’s x and y positionvalues when the mouse is clicked.

12

Page 13: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Something that becomes a problem again is that Scratch’s coordinate system has its origin in the center of the stage.This means that we have negative and positive coordinates. To simplify things, I want to transform the coordinatesystem to be entirely positive. This can be achieved by adding the half of the stage’s height to the mouse’s y positionand half of the stage’s width to the mouse’s x position. Which would look like this:

Now there is another problem; the game board is in the middle of the stage, which means we have to account forthe horizontalBoardOffset and the stageBorder. The way around this is to transform the position of the gameboard so that the horizontal lines begin right next to the y-axis. This would look like this:

Now the board is in the simplest position for us to work with. From the origin, we only need to move at most threecell spaces horizontally and/or vertically to get to every cell.

13

Page 14: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Let’s work on the equation to get us to this point. First, we’ll need some variables for this sprite only to store theresults of our equations. I named mine cellX and cellY. To do the transformation up to this point, we did:

cellX = mouseX + stageHalfWidth - (horizontalBoardOffset + stageBorder)

Remember that horizontalBoardOffset is not actually what you need as its value is 180 and we need a value of60. Here is how we can get that:

stageHalfWidth - horizontalBoardOffset

All together would give us this equation:

cellX = mouseX + stageHalfWidth - (stageHalfWidth - horizontalBoardOffset + stageBorder)

You may have noticed that this equation is not reduced completely. The reduced form of this equation is:

cellX = mouseX + horizontalBoardOffset - stageBorder

At the moment, if you set up a script to display the value of cellX as your dragged your mouse across from theleft most edge of the game board to the right most edge, it would display 0 at the left most edge, cellWidth at thefirst vertical line, cellWidth * 2 at the second vertical line, and cellWidth * 3 at the right most edge. We need totransform those numbers into integers.

The first step to doing that is to notice that every vertical division is divisible by the cellWidth, which would changeour previous report to 0 at the left edge, 1, 2, and then 3 at the right edge. If you were to click in the center of thefirst column however, the value of cellX would be 0.5. What we need to do then is to round up. Adding these twoideas to our previous equation gives us:

cellX = ceil(mouseX + horizontalBoardOffset - stageBorder

cellHalfWidth*2)

The calculation for cellY is the same aside from two distinctions. First, we need to use stageHalfHeight insteadof horizontalBoardOffset. The other is that we actually need to subtract the result from 4. This is because wewant our indices to increase as we go down but Scratch’s coordinate system increases as you go up. The resultingequation is:

cellY = 4 - ceil(mouseY + stageHalfHeight - stageBorder

cellHalfWidth*2)

Try to code up these equations and keep them on the side for now. Make sure to make variables and set their valuesfor those you don’t have yet. You will attach these to the previous code I showed you to make when testing if yourtokens were drawing correctly.

• stageHalfHeight = 180

• stageHalfWidth = 240

• horizontalBoardOffset = 180

14

Page 15: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Your When flag clicked block should look like this now:

Now seems like a good time to finally explain the mouseClickFlag component of this script. The purpose of thisvariable is to create, what some call, a latch. Without mouseClickFlag, the code within the if statement wouldcontinue to execute as long as the mouse button was held. Because of this latch, the code only executes once permouse click and can only be executed again after the mouse button is released and clicked again.

The next thing we’re going to work on is replacing the Draw X Token block that is in our when flag clickedblock. This is because we obviously want to be able alternate between drawing an X token and a O token. Makea new block which takes no input and has Draw Token for its text. Nest two if statements and then an if-elsestatement inside of the other two. Connect them to your Draw Token block. It should not look like this:

15

Page 16: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

What we are going to do now is limit where we can click to just the game board. Look at the following diagram fora better idea:

An easy way to do this is check if mouseX is within the vertical green lines and mouseY is within the horizontalgreen lines. Fortunately we already have all the variables necessary to accomplish this. Here is the logic for makingsure mouseX is within the desired area:

mouseX > -horizontalBoardOffset + stageBorder AND mouseX < horizontalBoardOffset - stageBorder

After you have coded this logical expression, make sure to place it as the condition for one of the two outer ifstatements. Try to come up with the appropriate logical expression for mouseY and place it as the condition forthe other outer if statement. Here’s how it should look when you are done:

Make a new variable for all sprites called playerTurn and create the logical expression playerTurn = 1 and usethat for the condition of the last if statement. Go to the More Blocks tab and drag your Draw O Token andDraw X Token and place one of them under the if statement and the other under the else.

16

Page 17: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

You can play with the inputs to these scripts but here are mine:

• Draw X Token - height = 50, thickness = 5, angle = 40

• Draw O Token - radius = 25, thickness = 5, number of edges = 20

Now we need to come up with the logic for placing the tokens in the center of a clicked cell. The way we will do thisis to use the information we calculated earlier, cellX and cellY, and base new calculations off of those to calculatethe center of the cell.

Let’s limit our thinking to only placing the token in the correct x position. Recall that the possible values for cellXare 1, 2, or 3. Also recall that our game board is centered at the origin. This means that when a cell in the middlecolumn is clicked, the x position for that token needs be 0. Given that cellX = 2 and the x position of the tokenneeds to be 0, how would we solve this? At first glance, it appears that we can just use: cellX - 2 for the x position.This works for tokens in the middle column, but does it hold up for the other columns?

If a cell in the first column is clicked, cellX will equal 1. If we subtract 2 from that, we get -1. This is obviouslyvery wrong, but can we use this? The x position we actually want for a token in the first column is -cellWidth. Itlooks like if we do: (cellX - 2) * (cellWidth) we actually get the correct equation for placing a token in its correctx position based on the cell that is clicked.

Let’s make sure that it works for the third column. If a cell in the third column was clicked, cellX would equal 3. Ifwe subtract 2 from that we get 1. Using our previous equation, we would get 1 * cellWidth which is exactly whatwe want. If it doesn’t make sense why we want -cellWidth and cellWidth, think about how the board is centeredaround the origin and how all the cells are the same size.

The y position equation is almost the same but we actually have to do 2 - cellY instead. If you used the exact sameequation, the tokens would get placed in the opposite cell, mirrored over the x axis, from which cell you clicked. Thisis because our vertical coordinates are the opposite of Scratch’s.

Your Draw Token block should now look like:

Go back to your when flag clicked block. Replace the Draw X Token block with your new Draw Token block.Drag your cellX and cellY blocks into the when flag clicked block, right above the set mouseClickFlag to 1block. This could have been done earlier but we will do it now, connect your Draw Board block to your whenflag clicked block, right above the forever block. The values I used for the inputs were:

• border = 70

• thickness = 5

17

Page 18: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

If you would like to test your Draw Token block, you will have to set the value of playerTurn to either a 1 or a2, depending on which token you want to test. Your when flag clicked block should look like this:

18

Page 19: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Game Logic

We’re going to take a very short break from working on the painter sprite to create a new sprite called controller.Again, the sprite image doesn’t matter, it can be anything, just remember to change its name to controller. Thisisn’t necessary for the game to work but its good practice to try and separate things when you can. The paintersprite handles drawing things on the stage while the controller sprite will control how the game is played such assetting up our list for use and checking who won if anyone has won.

Place a when flag clicked block in the script area and create a new list called board or something similar. Listsin scratch are basically 1-dimensional arrays. Unfortunately, a 2-dimensional array would represent our game boardmuch better but Scratch has no built in way to do that. You can work around this and make your own 2D array butit’s more work than it’s worth for us. Instead we will just use a single list and use math creatively to get the desiredresults.

Create a new variable for this sprite only called boardDefaultValues. Set its value to -1 in the when flag isclicked block. While we’re at it, let’s put our set playerTurn to 1 here in the controller sprite instead of in thepainter sprite. Next, connect a delete all of board block to our when flag clicked block.

Now we’re going to create a finite loop to set the initial values of our list. Connect a repeat block to the end of thewhen flag clicked block and set it’s value to 9. This is because there are 9 cells in our game board. Next, place aadd to board block inside of the repeat block. Place a boardDefaultValues as the value for the add toboard block. Finally, add a change boardDefualtValues by -1 to the end of the add block. If you were to havethe board list checked in the data tab and then hit the green flag, you would see the list populate with values thatare the indices negated. The reason for why we did it this way will be explained later on. Your when flag clickedscript should look like this now:

While we’re in the controller sprite, let’s set up the logic for alternating the player turns. Drag a when I receiveblock into the script area and create a new message called NextTurn. Connect an if else block to the when Ireceive NextTurn block. Set set condition for the if else statement to be playerTurn = 1. Then connect a setplayerTurn to 2 block to the if portion and a set playerTurn to 1 block to the else portion. It should now look like:

19

Page 20: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

We’re going to go back to our painter sprite now and modify some of our previous scripts.

First I’ll explain what it is that we are trying to do. We need to make a correlation between which cell is clicked andwhich list index we access. We’re going to do it similar to how we transformed Scratch’s coordinate system. Theidea looks like this:

What we are going to do is create an equation that uses the cellX and cellY variables as input and transform theminto an integer between 1 and 9 to use as an index for our board list.

If we look just at the x-coordinates of the top row we can observe that it maps to our new coordinate system perfectly.However, our second row doesn’t map well at all. Let’s look back at the top row and see how we can incorporatethe y-coordinate into our transformation. Since the x-coordinate is all we need from this row, if we were to add thex and y-coordinate values together we would need to figure out how to make the y-coordinate zero.

We could do this by multiplying the y-coordinate by 0 but we can pretty quickly see that this won’t work for thenext row. What if we subtracted 1 from the y-coordinate? That would work for the first row but doesn’t quite workfor the other rows. Let’s look at the first cell of the second row, cell (1,2). From this position we can see that therewere 3 cells before this one. Maybe if we multiplied our previous equation by 3 it will work? 1 + 3 ∗ (2 − 1) doesequal 4. This is indeed the equation that maps our coordinate system to our list indices:

cellX + 3 * (cellY - 1)

We are now going to modify our Draw Token script in our painter sprite to utilize this new equation. Connecta replace item of board with block right above the if playerTurn = 1 statement. The first value of thereplace item block will be our equation, but what do we want to replace the values with? The intention is somevalue that indicates which player has placed a token in that cell. We can use our playerTurn variable for this. Tofinish our Draw Token script, place a broadcast NextTurn block right below the if else statement.

20

Page 21: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Your finished Draw Token script should look like this:

If you’ve been playing around with this while you have been working on it, you may have noticed that there isnothing stopping us from placing a token in a cell that already has a token. Let’s prevent that from happening.

In your when flag clicked script, encase set mouseClickFlag to 1 and Draw Token within an if statement. Thecondition for this statement is to make sure that the value of the list at the index of the clicked cell is less than 0.Only then can we place a token. You’ll need to use the item of board block to retrieve the value of the list andthen our equation from earlier as the input. Then make sure that the value is less than 0. It should look like this now:

21

Page 22: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

The game is mostly functional at this point. What we need to add now is the logic for detecting who wins. Wewill do this in the controller sprite and will start first by creating four global variables (for all sprites): winning-Player, winningRow, winningColumn, and winningCellForDiagonal and one local variable (for this spriteonly) called numberOfFilledCells. This variable is so we know that if all the cells are filled and no one has one,it is a cat’s game or a tie. Set all of these variables values to 0 in the when flag is clicked script. It should looklike this now:

Create a new block with no inputs and its text as Check Winner. Add to the bottom of your when I receiveNextTurn script a change numberOfFilledCells by 1 block and then a Check Winner block. It should looklike this now:

22

Page 23: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Game Logic - Detecting Winner

Now let’s discuss how to check the board list for a winner. There is probably some algorithmic way to check fora winner but because we want to know not only who won but how they won, what we’re going to do is just checkevery possible winning line with a series of if statements.

I’ll give you just the first if statement of the series, as the rest are basically copies:

What this is basically doing is checking to see if the values of cell 1 = cell 2 = cell 3. If they are all equal thenwhichever player has their tokens there is the winner. There are eight of these checks in total. Three horizontal,three vertical, and two diagonal.

Make sure you specify the winningRow and winningColumn correctly. From top to bottom, it goes 1, 2, and 3 forrows. From left to right, it goes 1, 2, and 3 for columns. Lastly, winningCellForDiagonal can only be a 1 or a 3 tocorrespond with cell 1 or cell 3. These are important for later when we draw the winning line based on these numbers.

At the end of your eight if statements, you will need to attach an if else statement with another if statement nestedinside the else. The condition for the first if statement is winningPlayer > 0 and the condition for the second ifstatement is numberOfFilledCells = 9.

In the first if statement, attach a new broadcast message named DrawWinnerLine. In the second if statement,the one nested in the else, attach a winningPlayer = -1. This is for when we want to display ”Cat Game” later.It should look like this:

23

Page 24: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Drawing the Winning Line

Head back to your painter sprite and make a when I receive DrawWinnerLine block in the script area. Goahead an attach a set pen size to block and set it to whatever you desire, I used a value of 7.

Next, attach a series of three if statements right below the set pen size block. The conditions for each of these iswhether each of the winning variables from before are greater than 0. If one of them is we will call the appropriatescript (which we haven’t made yet) to draw the line.

Next, make three new blocks.

• Draw Winner’s Line Vertical at Column: ColNum - where ColNum is an input variable.

• Draw Winner’s Line Horizontal at Row: RowNum - where RowNum is an input variable.

• Draw Winner’s Line Diagonal Starting at Cell: CellNum - where CellNum is an input variable.

Place the appropriate Draw Winner’s Line block in the appropriate if statement and place the correspondingwinning variables as input to the Draw Winner’s Line blocks.

It should look like this when you are done:

Next we will code the logic for the Draw Winner’s Line blocks. Let’s start with the horizontal one. First, weknow we want the starting x position of the painter to begin at the left edge of the game board. That position willbe -3 * cellHalfWidth from the origin.

The y position is a little different. We know that, from the origin, the y position will be -cellWidth, 0, or cellWidth.The question at hand is how to get those values from RowNum. We know that RowNum will be 1, 2, or 3. If wesubtract 2 from it, that will give us -1, 0, 1. So if we multiply that by cellWidth we get the desired results, almost.A winner line at the first row should have the value cellWidth, but following our previous thinking we would get:

1 - 2 = -1 → -1 * cellWidth = -cellWidththe opposite of what we want. The solution here is just to multiply either our result by -1 or cellWidth by -1, butnot both.

Something worth mentioning is the construction of our if statements. We have done it in a series which means eachstatement gets checked regardless if one above it evaluated to true. Normally, if we want only one if statement toexecute, we would need to use an if-else if statement which does not exist in scratch. We could however make itourselves by nesting an if statement inside of the else portion of an if else statement. The reason we did not isbecause if our code is sound then only one of those winning variables will be greater than 0 and it avoids bloatingour code.

24

Page 25: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Attach a go to x: y: block to our Draw Winner’s Line Horizontal block and place the equations wecalculated earlier into their respective places. Attach a pen down block, the necessary glide block, and a pen upblock. The glide is fairly easy so I’ll let you think about that one. Your finished Draw Winner’s Line Horizontalblock should look like:

The other two Draw Winner’s Lines scripts are similar. Challenge yourself to try and solve them. They shouldlook like this when you are done:

At this point, you should be able to play through a game and a line will draw when a winning combination is made.However, there are two problems. The first is that you can continue to place tokens down if there is room, even ifthe game is over. The other is that there is no HUD (heads up display) indicating what is going on, whose turn isit and who won?

Let’s fix the first problem quickly. Go to your painter sprite and to your when flag clicked script. What we needto do is add a condition to only be able to place tokens if there is no winning player. Modify your if statement tomatch this one:

25

Page 26: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Heads Up Display

We now need a HUD to display relevant information to the players. We could do this by making sprites of the textwe want but that’s not easily adjustable. Instead it would be better to render text to the screen.

One way we could do this is to use the say or think blocks in the Looks tab. There are a couple problems withusing these however. The first problem is that the sprite that uses those blocks needs to be visible in order for themessage to appear. The other problem is the messages don’t appear in an aesthetically pleasing manner. This is ofcourse just an opinion and if you would like to use them, go for it!

We could make our own text render sprite and script but we will use someone else’s this time around. In anotherbrowser tab, go to the following link: https://scratch.mit.edu/projects/13535321/#editor

In the Sprites section you will see this sprite:

Open up your backpack by clicking on the arrow in the bottom-center of your screen. If you do not see an arrowthere, you are probably not logged in. Drag the sprite segoeui from the Sprites section into your backpack and goback to your project browser tab.

IMPORTANT - make sure to credit the author of this script. Here is a link to the proper ways to credit a Scratchauthor: https://wiki.scratch.mit.edu/wiki/Giving_Credit

Open up your backpack if it is not already. If you do not see the segoeui sprite in your backpack you may needto refresh your browser tab. Make sure your project is saved before doing so. Draw the segoeui sprite from yourbackpack into your Sprites area. Next we are going to add some scripts to it.

First create a new variable for all sprites called message. Next you’ll create two new broadcast receivers calledrenderPlayerTurn and renderPlayerWins. If the sprite’s scripts are too messy for you to work around, you canright-click the script area and select clean up.

26

Page 27: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Code the scripts so that they look like this:

Next go to the controller sprite and to the when flag is clicked script. Add a set message to Player 1’s Turnbelow sset playerTurn to 1.

Go to the when I receive NextTurn script and add the appropriate set messages and then add broadcastrenderPlayerTurn to the end of the script. They should look like this now:

27

Page 28: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Next, go to the bottom of your Check Winner script. Add to the bottom two if statements a broadcastrenderPlayerWins block and a new broadcast showReplayButton. It should look like this now:

Next, go to your painter sprite and to the when flag clicked script. Add a broadcast renderPlayerTurn blockright above the Draw Board block. It will look like:

This finishes the HUD.

28

Page 29: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Replay

We could always click the green flag if we want to play again, but we can also add that element into our game itself.

First we’ll need a new sprite for the replay button. You can either make your own or take mine from: https:

//scratch.mit.edu/projects/168718680/ just like we took the text renderer.

If you made your own, make sure it has two costumes, one appearing to be highlighted and then add these scriptsto it:

Next go to your controller sprite and create a receiver for the resetGame broadcast. You can duplicate yourcode from your when flag clicked script and attach that to your resetGame broadcast.

29

Page 30: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Next go to your painter sprite and do basically the same thing. We only want to take the portion that sets theinitial values for things. We don’t want our infinite loop checking for mouse input:

This finishes the replay feature.

Color Coding

As of right now, everything is the same color, let’s change that! Unfortunately, Scratch only let’s us specify the pencolor with a single number. Let’s write a script that converts RGB values into Scratch’s single number identifier.This will let us pick colors more easily.

Create a variable for this sprite only called penColor. Next, create a Set Pen Color block and code it so thatit looks like this:

This code was based on of this Scratch wiki page: https://wiki.scratch.mit.edu/wiki/Computer_Colors.

Finally, place your set pen color blocks in your scripts to draw your X token, Y token, and board and set thevalues to whatever color you desire.

If you have not done so already, make sure to hide the sprites! You can do this by right-clicking on the sprite andselecting info and then checking hide, which is the bottom option.

30

Page 31: Kids Coding Club East Tic Tac Toe Project - Student Version · How to incorporate someone else’s Scratch project/tool into your own project. This is just one way to make a Tic Tac

Finishing Touches and Ideas

If you have played around with this game, you may have noticed at least one bug! If you play through one game, hitthe replay button, and then try to place a token while the board is drawing it gets confused and goes pretty crazy!It’s actually fairly easy to fix and easily avoided so I will leave it there for you to tackle if that’s something thatinterests you! If that’s not something you want to fix, we’ll just call it a feature and leave it be for now.

Here are some ideas that you can implement to take this project to the next level:

• Score board for keeping track of the results of multiple rounds.

• A time that pressures the players into making decisions quicker.

• Implement the option to play against an AI.

This completes the Tic Tac Toe bonus project!

Congratulations!

31