So far we have:
import pygame
import sys
import time
from pygame import *
pygame.init()
ttt = pygame.display.set_mode((300,325))
pygame.display.set_caption('Tic-Tac-Toe')
# X will go first
XO = "X"
# Empty Grid
grid = [[ None, None, None],
[ None, None, None],
[ None, None, None,]]
def initBoard(ttt):
# Initialize the board and return it
# As a variable
# ttt : a properly initialized display variable
background = pygame.Surface(ttt.get_size())
background = background.convert()
background.fill((255,255,255))
# Draw the grid lines
# Vertical lines
pygame.draw.line(background, (0,0,0), (100,0), (100, 300), 2)
pygame.draw.line(background, (0,0,0), (200,0), (200, 300), 2)
# Horizontal lines
pygame.draw.line(background, (0,0,0), (0,100), (300, 100), 2)
pygame.draw.line(background, (0,0,0), (0,200), (300, 200), 2)
# Return the board
return background
def showBoard(ttt, board):
# Redraw the board on the screen(ttt)
drawStatus(board)
ttt.blit(board, (0,0))
pygame.display.flip()
board = initBoard()
running = True
while (running == True):
for event in pygame.event.get():
if event.type is QUIT:
running = False
and it is starting to have some meat to the program.Now we will start two new functions called: boardPos and clickBoard
boardPos:
def boardPos(mouseX, mouseY): # Determine the row if mouseY < 100: row = 0 elif mouseY < 200: row = 1 else: row = 2 # Determine column if mouseX < 100: col = 0 elif mouseX < 200: col = 1 else: col = 2 # Return the two return row, colboardPos checks the mouse position given and determines the row and column clicked on.
It then returns their values.
clickBoard:
def clickBoard(board): # Determine where clicked and draw # tell Python to acess globals grid and XO global grid global XO mouseX, mouseY = pygame.mouse.get_pos() row, col = boardPos(mouseX, mouseY) # Don't use this space if grid[row][col] == "X" or grid[row][col] == "O": return if XO == "X": XO = "O" else: XO = "X"
clickBoard finds the mouse position when clicking and checks if the space is occupied.
If occupied it leaves the function.
If it is not occupied it changes the turn, later we will make it display the "X" or "O".
Now we will finish off this section by editing our main loop.
board = initBoard(ttt) [B]mouseX, mouseY = pygame.mouse.get_pos()[/B] running = True while (running == True): for event in pygame.event.get(): if event.type is [B]pygame.QUIT[/B]: running = False [B]elif event.type is pygame.MOUSEBUTTONDOWN: clickBoard(board)[/B]pygame.mouse.get_pos() simply returns a tuple of the mouse's current coordinates.
Note:I fixed the first if in the main loop it was just QUIT should be pygame.QUIT
Now on to the next tutorial!


Sign In
Create Account


Back to top









