Jump to content

Learning Pygame(simple 2d), part 5 Checking for Winners and finishing up

- - - - -

  • Please log in to reply
10 replies to this topic

#1
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
You now have an almost complete pygame game, but you still can't win!
Here is what you have now.
# tic-tac-toe.py

# Tic-Tac-Toe

# Created by Mr.Yergler

# Typed by Jimmy

# March 24, 2010


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()




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, col


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

	drawMove(board, row, col, XO)

	if XO == "X":

		XO = "O"

	else:

		XO = "X"


def drawMove (board, boardRow, boardCol, Piece):

	# Draw an X or O on the board at the place

	# Find center of space

	global grid

	centerX = boardCol * 100 + 50

	centerY = boardRow * 100 + 50

	if Piece == "O":

		pygame.draw.circle(board, (0,0,0), (centerX, centerY), 44, 2)

	else:

		pygame.draw.line(board, (0,0,0), (centerX - 22, centerY - 22), (centerX + 22, centerY + 22), 2)

		pygame.draw.line(board, (0,0,0), (centerX + 22, centerY - 22), (centerX - 22, centerY + 22), 2)

	grid[boardRow][boardCol] = Piece

def drawStatus(board):

	global XO, winner, grid

	if winner is None and checkGrid(grid) == False:

		message = XO + "'s turn."

		

	elif winner is not None:

		message = winner + " won!"

	

	else:

		message = "Cat's game!"


	# Render the message

	font = pygame.font.Font(None, 24)

	text = font.render(message, 1, (0,0,0))

	# Copy it onto the board

	board.fill ((255,255,255), (0, 300, 300, 25))

	board.blit(text, (10,300))


winner = None

mouseX, mouseY = pygame.mouse.get_pos()

board = initBoard()

running = True

while (running == True):

	for event in pygame.event.get():

		if event.type is pygame.QUIT:

			running = False

		elif event.type is pygame.MOUSEBUTTONDOWN:

			clickBoard(board)

[INDENT]showBoard(ttt, board)[/INDENT]

So now we add the winners.
We need a function to check the Grid and a function to check for a winner.
checkGrid:
def checkGrid(grid):

	for row in range(0,3):

		for col in range(0,3):

			if grid[row][col] == None:

				return False

				break

	return True
checkGrid simply checks our list of squares(or our grid) and returns True if it is full otherwise it returns False.
Now we need to check for a winner.

gameWon:
def gameWon(board):

	# Determine if won

	global grid, winner

	

	# check for winning row

	for row in range(0,3):

			if grid[row][0] == grid[row][1] == grid[row][2] and grid[row][0] is not None:

				winner = grid[row][0]

				pygame.draw.line(board, (250,0,0), (0, (row + 1) * 100 - 50), (300, (row + 1) * 100 - 50), 2)

				return True

				break

	for col in range(0,3):

			if grid[0][col] == grid[1][col] == grid[2][col] and grid[0][col] is not None:

				winner = grid[0][col]

				pygame.draw.line(board, (250,0,0), ((col+1)* 100 - 50, 0), ((col+1) * 100 -50, 300), 2)

				return True

				break

	if grid[0][0] == grid[1][1] == grid[2][2] and grid[0][0] is not None:

		winner = grid[0][0]

		pygame.draw.line(board, (250,0,0), (50, 50), (250,250), 2)

		return True

	if grid[0][2] == grid[1][1] == grid[2][0] and grid[0][2] is not None:

		winner = grid[0][2]

		pygame.draw.line(board, (250,0,0), (250,50), (50, 250), 2)

		return True
This funciton is long, but fairly self-explainatory.
It simply checks the columns for a winner, the rows, and the two diagonals.
Congrats you have finished the program.

If you need to reference a problem just ask.
I C!(and Python, and C++, and ...)

#2
dave007

dave007

    Newbie

  • Members
  • Pip
  • 4 posts
hi spyder i tryed to do your program and something wrong is going on , the program doesnt let me introdiuce anything, looks like doent work , can you tell me why?, runnning pytho3.1. maybe something is missing, when i run the program from the shell, doesnt have any error message,,,. andthrow it right away, but it keeps thinking...please let me know whats de solution. email.( davidsotobariloche@hotmail.com)

#3
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
Wow, ummm. . . Could you try being a bit more specific? I don't get your exact problem. Try attaching the exact code you typed, and I can try and figure it out and let you know. What operating system are you using? I think I wrote this one using Windows.
I C!(and Python, and C++, and ...)

#4
dave007

dave007

    Newbie

  • Members
  • Pip
  • 4 posts
hi spyder, the real thing is that i already cpoy exactly the same code you have and i am a litel bit desperate, i not a very beginer, neither and expert, the thing is i ´m runninw win Xp. I wrote the code in the iddle, i run buy f5, the program keeps thinking, the board appear but it doesnt work,

#5
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
Okay. Ummm. . . Just to make sure, you do have pygame installed right? Let me make sure it still works, I may have written this for Python 2.6 or 2.7. It was a while back. And I dropped off the programming map for a while cause I was doing some 3d art.
I C!(and Python, and C++, and ...)

#6
dave007

dave007

    Newbie

  • Members
  • Pip
  • 4 posts
some problems with initboard funcion, says is not define,ok,,,looks like it work, but the scrren is on black,and it doest let me see the lines, maybe i did something worg, looks like i something is missed,like when I click the mouse it doesnt let me see the scrren

#7
dave007

dave007

    Newbie

  • Members
  • Pip
  • 4 posts
3d art, thas cool. let me know how you do it, i´m adesigner and I love to draw in 3d by computer, with autocad and solid works

#8
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
Okay, I see. In the first area with code in it, I don't have the full thing.
That is just what you have done so far.
You need to add in the checkGrid and gameWon functions before the main loop.
That should fix it.
I C!(and Python, and C++, and ...)

#9
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
I didn't see your second comment.
I actually use Blender, a free, open-source 3d art program.
It is really cool, and there is actually a built-in game engine that can use python for scripting.
I actually just really started working on it in probably January.
I C!(and Python, and C++, and ...)

#10
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
spyder,

when you return from function or whatever, the break statement following is useless because return "kills" the function (sort of :P ).
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#11
spyder

spyder

    Programmer

  • Members
  • PipPipPipPip
  • 120 posts
Thanks, I wrote this tutorial a while ago, and I hadn't noticed that.
It was in my beginning stages of Python.
I C!(and Python, and C++, and ...)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users