Advertisement
JangoBingoBango

TicTacToe.py

Apr 23rd, 2020
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.57 KB | None | 0 0
  1. import pygame, sys, time, math
  2. from pygame.locals import *
  3.  
  4. # Create gameloop, and prompt players for their turn
  5. def StartGame():
  6.     global PlayerTurn
  7.     global GameOver
  8.     Display()
  9.     while ~GameOver: # While game is not over
  10.         for event in pygame.event.get():
  11.             # handle MOUSEBUTTONUP
  12.             if (event.type == pygame.MOUSEBUTTONUP):
  13.                 position = pygame.mouse.get_pos()
  14.                 gameboardSpot = findSpotPosition(position)
  15.                 try:
  16.                     # if gameboardSpot already taken, ignore action and return
  17.                     index = findGameboardIndex(gameboardSpot)
  18.                     if (board[index[0]][index[1]] != 0):
  19.                         break
  20.                     claimSpot(PlayerTurn, gameboardSpot)
  21.                 except Exception as error:
  22.                     print(error)
  23.             if (event.type == QUIT):
  24.                 pygame.quit()
  25.                 sys.exit()
  26.         pygame.display.update()
  27.  
  28.  # display text game board
  29. def Display():
  30.     print("\n")
  31.     for group in board:
  32.         word = ""
  33.         for state in group:
  34.             word += str(state) + " "
  35.         print(word)
  36.  
  37. def Move(x, y, s): # int, int, State(int)
  38.     global MoveCount
  39.     if (board[x][y] == 0): # if state is empty
  40.         board[x][y] = s
  41.     MoveCount += 1
  42.     CheckWinner(x, y, s)
  43.  
  44. # Return the spot position of the mouse click
  45. def findSpotPosition(pos_XY):
  46.     spotWidth   = 100
  47.     spotHeight  = 100
  48.     index = 0
  49.     # find which range the mouse click landed in, and return the spot position
  50.     for array in spotsPosition:
  51.         if (array[0] <= pos_XY[0] <= array[0] + spotWidth) and (array[1] <= pos_XY[1] <= array[1] + spotHeight):
  52.                 return index + 1
  53.         index += 1
  54.     return 0
  55.  
  56. # Claim a spot on the gameboard for a player
  57. def claimSpot(playerNumber, gameboardSpot):
  58.     global PlayerTurn
  59.     global MoveCount
  60.     global GameOver
  61.     # index holds the x, y values of the spot that is trying to be claimed on the gameboard
  62.     index = findGameboardIndex(gameboardSpot)
  63.     # After we know what spot we want claimed, we check to see if it is valid
  64.     # If the spot is not valid, prompt for a new gameboardSpot
  65.     # If the spot is valid, claim and redisplay the gameboard
  66.     if (board[index[0]][index[1]] != 0):
  67.         #gameboardSpot = int(input("\r\nSpot taken, choose a new one: "))
  68.         claimSpot(playerNumber, gameboardSpot)
  69.     else: # SPOT CLAIM SUCESSFUL
  70.         board[index[0]][index[1]] = playerNumber
  71.         drawLetter(gameboardSpot)
  72.         CheckWinner(index[0], index[1], PlayerTurn)
  73.         if (PlayerTurn == 1):
  74.             PlayerTurn = 2
  75.         elif (PlayerTurn == 2):
  76.             PlayerTurn = 3
  77.         elif (PlayerTurn == 3):
  78.             PlayerTurn = 1
  79.  
  80.         font = pygame.font.Font('freesansbold.ttf', 24)
  81.         text2 = font.render('Player #' + str(PlayerTurn) +'\'s turn', True, WHITE, GREY)
  82.         DISPLAY.blit(text2, textRect2)
  83.         Display()
  84.  
  85.         if (MoveCount == (math.pow(BoardLength, 2) - 1)):
  86.             print("\nDRAWWWWW \n\n\n\n\n\n\n\n")
  87.             text2 = font.render("Game Over! It's a draw!", True, WHITE, GREY)
  88.             DISPLAY.blit(text2, textRect2)
  89.  
  90.         if (GameOver == True):
  91.             print("win row #" + str(PlayerTurn) + "WINNER WINNNER \n\n\n\n\n\n\n\n")
  92.             text2 = font.render("Game Over! Player #" + str(PlayerTurn) + " has won!", True, WHITE, GREY)
  93.  
  94.         MoveCount += 1
  95.  
  96. # index1, and index2 uses position to determine which spot is trying to be claimed from gameboard
  97. def findGameboardIndex(position):
  98.     if   (1 <= position <= 5):
  99.         index1 = 0
  100.         index2 = position - 1
  101.     elif (6 <= position <= 10):
  102.         index1 = 1
  103.         index2 = position - 1 - 5
  104.     elif (11 <= position <= 15):
  105.         index1 = 2
  106.         index2 = position - 1 - 5 - 5
  107.     elif (16 <= position <= 20):
  108.         index1 = 3
  109.         index2 = position - 1 - 5 - 5 - 5
  110.     elif (21 <= position <= 25):
  111.         index1 = 4
  112.         index2 = position - 1 - 5 - 5 - 5 - 5
  113.     return [index1, index2]
  114.  
  115. def drawLetter(position):
  116.     global PlayerTurn
  117.  
  118.     letter  = 'Oops'
  119.     color   = BLACK
  120.     if   (PlayerTurn == 1):
  121.         letter  = 'X'
  122.         color   = RED
  123.     elif (PlayerTurn == 2):
  124.         letter = 'O'
  125.         color   = BLUE
  126.     elif (PlayerTurn == 3):
  127.         letter = 'Y'
  128.         color   = GREEN
  129.  
  130.     # Find the coordinates for the X or O we are drawing for
  131.     placement = spotsPosition[position - 1]
  132.  
  133.     # Render, and position the two text objects
  134.     font = pygame.font.Font('freesansbold.ttf', 80)
  135.     placement       = (placement[0], placement[1])
  136.  
  137.     text            = font.render(letter, True, color, GREY)
  138.     textRect        = text.get_rect()
  139.     textRect.center = (placement[0] + 50, placement[1] + 55)
  140.     DISPLAY.blit(text, textRect)
  141.  
  142. def CheckWinner(x, y, s):
  143.     global Winlength
  144.     global MoveCount
  145.     global GameOver
  146.     #check end conditions
  147.     #check row
  148.     for i in range (BoardLength):
  149.         if(board[x][i] != s):
  150.             break
  151.         if(i == Winlength):
  152.             print("win row #" + str(s) + "WINNER WINNNER \n\n\n\n\n\n\n\n")
  153.             text2 = font.render("Game Over! Player #" + str(PlayerTurn) + " has won!", True, WHITE, GREY)
  154.             GameOver = True
  155.             #report win for s
  156.  
  157.     #check rocolw
  158.     for i in range (BoardLength):
  159.         if(board[i][y] != s):
  160.             break
  161.         if(i == Winlength):
  162.             print("win col #" + str(s) + "WINNER WINNNER \n\n\n\n\n\n\n\n")
  163.             text2 = font.render("Game Over! Player #" + str(PlayerTurn) + " has won!", True, WHITE, GREY)
  164.             GameOver = True
  165.             #report win for s
  166.        
  167.     #check diag
  168.     if (x == y):
  169.         #we're on a diagonal
  170.         for i in range (BoardLength):
  171.             if (board[i][i] != s):
  172.                 break
  173.             if (i == Winlength):
  174.                 print("win diag #" + str(s) + "WINNER WINNNER \n\n\n\n\n\n\n\n")
  175.                 text2 = font.render("Game Over! Player #" + str(PlayerTurn) + " has won!", True, WHITE, GREY)
  176.                 GameOver = True
  177.                 #report win for s
  178.            
  179.     #check anti diag
  180.     if (x + y == BoardLength - 1):
  181.         for i in range (BoardLength):
  182.             if (board[i][(BoardLength - 1) - i] != s):
  183.                 break
  184.             if (i == Winlength):
  185.                 print("win anti-diag #" + str(s) + "WINNER WINNNER \n\n\n\n\n\n\n\n")
  186.                 text2 = font.render("Game Over! Player #" + str(PlayerTurn) + " has won!", True, WHITE, GREY)
  187.                 GameOver = True
  188.                 #report win for s
  189.            
  190.     #check draw
  191.     if (MoveCount == (math.pow(BoardLength, 2) - 1)):
  192.         print("\nDRAWWWWW \n\n\n\n\n\n\n\n")
  193.         text2 = font.render("Game Over! It's a draw!", True, WHITE, GREY)
  194.         DISPLAY.blit(text2, textRect2)
  195.         GameOver = True
  196.         #report draw
  197.  
  198. # Main
  199. # Start PyGame
  200. pygame.init()
  201. DISPLAY = pygame.display.set_mode((500, 550), 0, 32)
  202. pygame.display.set_caption('Tic Tac Toe')
  203.  
  204. # Colors
  205. RED      = (255,   0,   0)
  206. GREEN    = (  0, 255,   0)
  207. BLUE     = (  0,   0, 255)
  208. BLACK    = (  0,   0,   0)
  209. BROWN    = (180, 150, 110)
  210. GREY     = (80, 80, 80)
  211. WHITE    = (255, 255, 255)
  212.  
  213. # Draw TicTacToe lines, and background
  214. DISPLAY.fill(GREY)
  215. xPos    = 0
  216. yPos    = 50
  217. height  = 3
  218. length  = 500
  219. for x in range(6): # Draw Horrizontal Lines
  220.     pygame.draw.rect(DISPLAY, BLACK, (xPos,  yPos,  length, height))
  221.     yPos += 100
  222.  
  223. xPos    = 0
  224. yPos    = 50
  225. height  = 500
  226. length  = 3
  227. for x in range(6): # Draw Vertical Lines
  228.     pygame.draw.rect(DISPLAY, BLACK, (xPos,  yPos,  length, height))
  229.     xPos += 100
  230.  
  231. # Render, and position the two text objects
  232. X1, X2, Y = 150, 600, 50
  233. font = pygame.font.Font('freesansbold.ttf', 24)
  234. text1 = font.render('', True, BLACK, GREY)
  235. text2 = font.render('Player #' + "1" +'\'s turn', True, WHITE, GREY)
  236. textRect1, textRect2 = text1.get_rect(), text2.get_rect()
  237. textRect1.center = (X1 // 2, Y // 2)
  238. textRect2.center = (X2 // 2, Y // 2)
  239. DISPLAY.blit(text1, textRect1)
  240. DISPLAY.blit(text2, textRect2)
  241.  
  242. # Variables to handle mouse click detection for positions
  243. BoardLength = 5
  244. xPos        = 0
  245. yPos        = 50
  246. spotsPosition = []
  247. for i in range(BoardLength):
  248.     for j in range(BoardLength):
  249.         spotsPosition.append([xPos, yPos])
  250.         xPos += 100
  251.     yPos += 100
  252.     xPos = 0
  253.  
  254. # Game creation
  255. GameOver = False
  256. Winlength = 3   - 1
  257. MoveCount = 0 # int
  258. PlayerTurn = 1
  259. board = [[0] * BoardLength for _ in range(BoardLength)] # [[int]]
  260. StartGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement