Square Based Game Tutorial – Model

[et_pb_section][et_pb_row][et_pb_column type=”2_3″][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left”]

Square Based Game Tutorial – Model/View

If you haven’t finished the “Setup” part of this tutorial – do that first.

In our Tic Tac Toe game, you’re going to use variables as your model,  to represent the state of your game.  Make one variable that keeps track of where the players have placed X’s and O’s.  Call it “game”.  Initially, the game variable is a list of nine zeroes.      Also set two other variables here.  “turn” is a variable that will have the value 1 when it is X’s turn, and 2 when it is O’s turn.  Winner will be zero at the beginning and then change to ‘1’ if X wins and to ‘2’ if O wins.

Put these variables in the setup part of the run_game() function, before the while not done loop.

The view part is what the user sees.  To put X’s and O’s on the screen in the appropriate places, in the setup part of the program, load up the images (you might have already done some of this in the challenge part of the previous tutorial.

Your program will need to know where to put all these images, so you’ll make a list of squares, called squares, that holds these things.  Each square is a sequence.  For instance, the middle square is the sequence (250, 250, 200, 200).  This means that the top left corner of the middle square is at x = 250, y = 250, and is 200 pixels wide and 200 pixels tall.    You could list all the squares, but instead generate them with a series of loops.  Put this code in the setup part of the run_game() function.

Now you’ll draw the images, in the while not done loop, just before the display.flip() line.  Use a variable to iterate through the game list and blit the images into the squares.  This part might look a little magical.  Spend a little time understanding what is happening.

Just to test it, try changing the initial value of game to a different list of numbers, something like:

game = [0,1,2,2,1,0,1,0,0]

Run your program and you should see a non empty board.  Don’t forget to change it back.

NEXT>>

 

[/et_pb_text][/et_pb_column][et_pb_column type=”1_3″][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left”]

Resources

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]