Tic-Tac-Python?

Below is the final code for implementing a game of “Tic-Tac-Toe” utilizing PyGame and Python Code.

import pygame, sys
from pygame.locals import *
import random

def optionsmenu(cpu):
  DISPLAYSURF = pygame.display.set_mode((600,800)) #This line establishes the size of the playing window.
  BLACK = (0,0,0)
  DISPLAYSURF.fill(BLACK)
  running = True
  optionstitle = pygame.image.load('images/optionstitle.gif')
  titlecoord = (0,0)
  if cpu == 1:
    playcpu = pygame.image.load('images/playcpuselected.gif')
    playplay = pygame.image.load('images/playplayer.gif')
  else:
    playcpu = pygame.image.load('images/playcpu.gif')
    playplay = pygame.image.load('images/playplayerselected.gif')  
    #These lines dictate the images utilized within the program, dependent upon the mode of gameplay (P v. P, or P v. AI)
  playcpucoord = (100,600)
  playcpurect = playcpu.get_rect()
  playcpurect.center = (175,675)
  back = pygame.image.load('images/back.gif')
  backcoord = (200,400)
  backrect = back.get_rect()
  backrect.center = (275,475)
  playplaycoord = (300,600)
  playplayrect = playplay.get_rect()
  playplayrect.center = (375,675)
  DISPLAYSURF.blit(playplay,playplaycoord)
  DISPLAYSURF.blit(playcpu,playcpucoord)
  DISPLAYSURF.blit(optionstitle,titlecoord)
  DISPLAYSURF.blit(back,backcoord)
  buttonsRect = [backrect, playplayrect, playcpurect]
  #These lines establish the appearance of the options menu, and allow for the creation of the "collision rectangles" that control the actions of buttons.
  while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
          running = False
    if event.type == MOUSEBUTTONDOWN:
      if event.button == 1:
        for i in buttonsRect:
          if i.collidepoint(event.pos):
            if i == buttonsRect[0]:
              running = False
            elif i == buttonsRect[1]:              
              cpu = 0
              playcpu = pygame.image.load('images/playcpu.gif')
              playplay = pygame.image.load('images/playplayerselected.gif')
            else:
              cpu = 1
              playcpu = pygame.image.load('images/playcpuselected.gif')
              playplay = pygame.image.load('images/playplayer.gif')
            DISPLAYSURF.blit(playplay,playplaycoord)
            DISPLAYSURF.blit(playcpu,playcpucoord)
# These lines control the actions of the "options menu", when a button is "clicked". Again, "collision rectangles" are utilized, and the image loaded within the options menu to represent a choice
# is dependent upon the option selected. For instance, when the option to play with AI is selected, a different picture for that "options rectangle" than the other option ("Play with a Partner").
   
    pygame.display.flip() #This line updates the surface.
  return cpu #This line determines the mode of gameplay: either with computer AI, or with a friend.  
 
 
def playerWin(DISPLAYSURF, player): #takes game surface and player as input
  BLACK = (0,0,0)
  DISPLAYSURF.fill(BLACK)
  running = True
  win1 = pygame.image.load('images/Player1Win.gif') #Player 1 win image
  win2 = pygame.image.load('images/Player2Win.gif') #Player 2 win image
  draw = pygame.image.load('images/draw.gif') #Draw image
#########################################################################
#Coordinates and rectangles and stuff:
  wincoord = (0,0)
  back = pygame.image.load('images/backtomenu.gif')
  backcoord = (200,600)
  backrect = back.get_rect()
  backrect.center = (275,675)
  buttonsRect = [backrect]
 
  if player == 2: #if player = 2, then player 1 is the winner
    DISPLAYSURF.blit(win1,wincoord)
  if player == 3: #if player = 3, there was no winner/it was a draw
    DISPLAYSURF.blit(draw,wincoord)  
  if player == 1: #if player = 1, player 2 is the winner
  #I know it's weird that player = 2 means player 1 wins but that's just kind of how it turned out
    DISPLAYSURF.blit(win2,wincoord)    
  DISPLAYSURF.blit(back,backcoord)
  while running:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
          running = False
      if event.type == MOUSEBUTTONDOWN: #if user clicks
        if event.button == 1:
          for i in buttonsRect:
            if i.collidepoint(event.pos): #if click is on back button rectangle
              if i == buttonsRect[0]:
                running = False #quit the function and display menu function (goes back to main menu)
    pygame.display.flip() #updates display          

    

def ticTacToe(cpu): #if cpu == 1 then it's a player vs. cpu game
 
  WHITE =    (255, 255, 255) #background color
  DISPLAYSURF = pygame.display.set_mode((600,800))
  pygame.display.set_caption('Tic-Tac-Toe')
  DISPLAYSURF.fill(WHITE)
  running = True
  player = 1 #Determines which player's turn it is
#########################################################################
#The following determines the grid coordinates of the board and their rectangles which will determine when an X and O should be placed if they are clicked on:
  buttonOne = pygame.image.load('images/Button.gif')
  buttonOnecoord = (0,0)
  b1 = buttonOne.get_rect()
  b1.center = (100,100)
  buttonTwo = pygame.image.load('images/Button.gif')
  buttonTwocoord = (200,0)
  b2 = buttonTwo.get_rect()
  b2.center = (300,100)
  buttonThree = pygame.image.load('images/Button.gif')
  buttonThreecoord = (400,0)
  b3 = buttonThree.get_rect()
  b3.center = (500,100)
  buttonFour = pygame.image.load('images/Button.gif')
  buttonFourcoord = (0,200)
  b4 = buttonFour.get_rect()
  b4.center = (100,300)
  buttonFive = pygame.image.load('images/Button.gif')
  buttonFivecoord = (200,200)
  b5 = buttonFive.get_rect()
  b5.center = (300,300)
  buttonSix = pygame.image.load('images/Button.gif')
  buttonSixcoord = (400,200)
  b6 = buttonSix.get_rect()
  b6.center = (500,300)
  buttonSeven = pygame.image.load('images/Button.gif')
  buttonSevencoord = (0,400)
  b7 = buttonSeven.get_rect()
  b7.center = (100,500)
  buttonEight = pygame.image.load('images/Button.gif')
  buttonEightcoord = (200,400)
  b8 = buttonEight.get_rect()
  b8.center = (300,500)
  buttonNine = pygame.image.load('images/Button.gif')
  buttonNinecoord = (400,400)
  b9 = buttonNine.get_rect()
  b9.center = (500,500)
 
  playerDisplay = pygame.image.load('images/Player1.gif') #Displays who's turn it is
  playercoord = (0,600)
 

 
  board = pygame.image.load('images/board.gif') #The board ohhhhh boyyyyy
  boardcoord = (0,0)
 
  countDisplay = 0
  ######################################################################
  #Below are lists of the buttons and a list of their rectangles
  buttons = [buttonOne,buttonTwo,buttonThree,buttonFour,buttonFive,buttonSix,buttonSeven,buttonEight,buttonNine]
  buttonscoord = [buttonOnecoord, buttonTwocoord,buttonThreecoord,buttonFourcoord,buttonFivecoord,buttonSixcoord,buttonSevencoord,buttonEightcoord,buttonNinecoord]
  buttonsRect = [b1,b2,b3,b4,b5,b6,b7,b8,b9]
  charPlace = [0,0,0,0,0,0,0,0,0] #each element in this list corresponds to a place on the board
 
  playerTrack = 0
  diceRoll = 0 #Initialize for CPU AI below
 
 
  while running: #condition for the game to continue running; if running = false either a winner has been determined or the player has quit the program
 
    DISPLAYSURF.fill(WHITE)
    
    for b in buttons: #displays the grid squares and "gets" the rectangles for click detection
      DISPLAYSURF.blit(b,buttonscoord[countDisplay])
      countDisplay+=1
      if countDisplay > 8:
        countDisplay = 0  
    DISPLAYSURF.blit(board,boardcoord)
    DISPLAYSURF.blit(playerDisplay,playercoord)    
    
    for event in pygame.event.get():
      if event.type == QUIT: #Player quits program
        pygame.quit()
        sys.exit()  
    if cpu == 0:  #if cpu == 0 then it is a player vs. player game  
      if event.type == MOUSEBUTTONDOWN:
        if event.button == 1:
          for i in buttonsRect:
            if i.collidepoint(event.pos): #if player clicked on a grid square
              place = buttonsRect.index(i)
              if charPlace[place] == 1 or charPlace[place] == 2: #if grid square already contains an X or an O
                break #do not change image
              if player == 1:             
                buttons[place] = pygame.image.load('images/ButtonX.gif') #replace image with an X if player 1 clicks a grid square
                charPlace[place] = 1
                place = 0
                playerTrack += 1
                break
              if player == 2:
                buttons[place] = pygame.image.load('images/ButtonO.gif')#replace image with an O if player 2 clicks a grid square
                charPlace[place] = 2
                playerTrack += 1
                break
        for b in buttons:
          DISPLAYSURF.blit(b,buttonscoord[countDisplay])
          countDisplay+=1
          if countDisplay > 8:
            countDisplay = 0  
        DISPLAYSURF.blit(board,boardcoord)
    if cpu == 1: #if cpu == 1 it's a player vs. cpu game
      if player == 1:
        if event.type == MOUSEBUTTONDOWN: #same as above: if player clicks on gridsquare replace gridsquare with an X
          if event.button == 1:
            for i in buttonsRect:
              if i.collidepoint(event.pos):
                place = buttonsRect.index(i)
                if charPlace[place] == 1 or charPlace[place] == 2:
                  break
                if player == 1:             
                  buttons[place] = pygame.image.load('images/ButtonX.gif')
                  charPlace[place] = 1
                  place = 0
                  playerTrack += 1
                  break
          for b in buttons:
            DISPLAYSURF.blit(b,buttonscoord[countDisplay])
            countDisplay+=1
            if countDisplay > 8:
              countDisplay = 0  
          DISPLAYSURF.blit(board,boardcoord)
      if player == 2: #cpu AI
        diceRoll = random.randint(0,8) #randomly select gridsquare
        while charPlace[diceRoll] != 0: #if randomly selected gridsquare already contains X or O, randomly select another gridsquare until an empty one is selected
          diceRoll = random.randint(0,8)
        buttons[diceRoll] = pygame.image.load('images/ButtonO.gif')
        playerTrack += 1
        charPlace[diceRoll] = 2
              
             
    if playerTrack == 1 or playerTrack == 3 or playerTrack == 5 or playerTrack == 7: #playerTrack tracks who's turn it is
      player = 2
      playerDisplay = pygame.image.load('images/Player2.gif')
      DISPLAYSURF.blit(playerDisplay,playercoord)
      
    else:
      player = 1  
      playerDisplay = pygame.image.load('images/Player1.gif')
      DISPLAYSURF.blit(playerDisplay,playercoord)
##############################################################################
#Below are winning conditions:    
    
    if charPlace[0] == 1 and charPlace[1] == 1 and charPlace[2] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)
    elif charPlace[3] == 1 and charPlace[4] == 1 and charPlace[5] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)
    elif charPlace[6] == 1 and charPlace[7] == 1 and charPlace[8] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)       
    elif charPlace[0] == 1 and charPlace[3] == 1 and charPlace[6] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)       
    elif charPlace[1] == 1 and charPlace[4] == 1 and charPlace[7] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)                   
    elif charPlace[2] == 1 and charPlace[5] == 1 and charPlace[8] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)       
    elif charPlace[0] == 1 and charPlace[4] == 1 and charPlace[8] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)        
    elif charPlace[2] == 1 and charPlace[4] == 1 and charPlace[6] == 1:
      player = 2
      running = False
      playerWin(DISPLAYSURF, player)  
      
    elif charPlace[0] == 2 and charPlace[1] == 2 and charPlace[2] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)      
    elif charPlace[3] == 2 and charPlace[4] == 2 and charPlace[5] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)      
    elif charPlace[6] == 2 and charPlace[7] == 2 and charPlace[8] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)       
    elif charPlace[0] == 2 and charPlace[3] == 2 and charPlace[6] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)      
    elif charPlace[1] == 2 and charPlace[4] == 2 and charPlace[7] == 2:
      player = 1
      running = False   
      playerWin(DISPLAYSURF, player)                 
    elif charPlace[2] == 2 and charPlace[5] == 2 and charPlace[8] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)
    elif charPlace[0] == 2 and charPlace[4] == 2 and charPlace[8] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)   
    elif charPlace[2] == 2 and charPlace[4] == 2 and charPlace[6] == 2:
      player = 1
      running = False
      playerWin(DISPLAYSURF, player)   
    elif 0 not in charPlace:
      running = False
      player = 3
      playerWin(DISPLAYSURF, player)
       
    pygame.display.flip() #updates the surface of the program
       
def menu():
  cpu = 0 #initialize whether cpu option is selected or not
  running = True
  while running: #while running is true the program will continue to run
    DISPLAYSURF = pygame.display.set_mode((600,800)) #sets window size
    BLACK = (0,0,0) #background color
    DISPLAYSURF.fill(BLACK)
###########################################################################
#Below are loaded images, their coordinates, and retrieving/placing their rectangles for click detection if the image is a button:    
    title = pygame.image.load('images/title.gif')
    titlecoord = (0,0)
    options = pygame.image.load('images/options.gif')
    optionscoord = (100,600)
    optionsrect = options.get_rect()
    optionsrect.center = (175,675)
    playgame = pygame.image.load('images/playgame.gif')
    playgamecoord = (300,600)
    playgamerect = playgame.get_rect()
    playgamerect.center = (375,675)
#Displays images:    
    DISPLAYSURF.blit(playgame,playgamecoord)
    DISPLAYSURF.blit(options,optionscoord)
    DISPLAYSURF.blit(title,titlecoord)
#list of the buttons on the menu    
    buttonsRect = [playgamerect, optionsrect]  
    for event in pygame.event.get():
        if event.type == pygame.QUIT: #if user clicks the 'x' in top right corner
          running = False #quit the program
    if event.type == MOUSEBUTTONDOWN: #if user clicks
      if event.button == 1:
        for i in buttonsRect:
          if i.collidepoint(event.pos): #detect if click is within a predefined rectangle
            if i == buttonsRect[0]: #if user clicks "play game"
              ticTacToe(cpu) #run tic tac toe function
            else:
              cpu = optionsmenu(cpu) #if user clicks options button, display options menu
    pygame.display.flip() #updates surface               
if __name__ == "__main__":
  menu()           
Advertisements