Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # pip install pygame and pip install numpy
- import pygame
- from pygame import *
- from pygame.font import Font
- from pygame import gfxdraw
- import numpy as np
- pygame.init()
- size = 300
- screen = pygame.display.set_mode([size] * 2)
- pygame.display.set_caption("Tic Tac Toe")
- font = Font('./Fonts/Roboto-Light.ttf', 30)
- class TicTacToe():
- field = []
- field_rect = []
- text = font.render("", True, Color("black"))
- padding = 10
- turn = 1 # X - first
- end = False
- def __init__(self):
- padding = self.padding
- fSize = size / 3 - padding / 2
- self.field = np.zeros([3, 3])
- self.field_rect = np.zeros([3, 3, 4])
- for i in range(3):
- for j in range(3):
- # j, i - because i will be column, and j will be row
- self.field_rect[j, i] = np.array(
- [i * fSize + padding, j * fSize + padding, fSize - padding, fSize - padding])
- def Event(self, event):
- pos = pygame.mouse.get_pos()
- for i in range(3):
- for j in range(3):
- if Rect(self.field_rect[i, j]).collidepoint(pos) and not self.field[i][j]:
- self.field[i][j] = self.turn
- self.turn *= -1
- self.CheckAndDoWin()
- def CheckAndDoWin(self):
- check_array = [*self.field.sum(axis=1), *self.field.T.sum(axis=1),
- self.field.trace(), np.trace(self.field[:][::-1])]
- self.end = True
- str = ""
- if 3 in check_array:
- str = "Win X"
- elif -3 in check_array:
- str = "Win O"
- elif 0 not in self.field:
- str = "Standoff"
- self.end = bool(str) #or len(str)
- self.text = font.render(str, True, Color("black"))
- def DrawO(self, x, y, r, color, width=1):
- for i in range(0, width):
- gfxdraw.aacircle(screen, x, y, r + i - width // 2, color)
- def DrawX(self, x1, x2, y1, y2, color, width=1):
- pygame.draw.line(screen, color, [x1, y1], [x2, y2], width)
- pygame.draw.line(screen, color, [x2, y1], [x1, y2], width)
- def Draw(self):
- if self.end:
- screen.blit(self.text, (np.array([size, size]) - np.array(self.text.get_size())) / 2)
- return
- for rect in self.field_rect.reshape(3 * 3, 4):
- gfxdraw.rectangle(screen, rect, Color("black"))
- line_width = 2
- for i in range(0, 3):
- for j in range(0, 3):
- rect = Rect(self.field_rect[i, j])
- if self.field[i][j] == 1:
- x1, y1 = rect.topleft
- x2, y2 = rect.bottomright
- self.DrawX(x1, x2, y1, y2, Color("black"), line_width)
- if self.field[i][j] == -1:
- self.DrawO(*rect.center, rect.width // 2, Color("black"), line_width)
- Running = True
- Clock = pygame.time.Clock()
- game = TicTacToe()
- while Running:
- screen.fill(Color("white"))
- for event in pygame.event.get():
- if event.type == QUIT:
- Running = False
- if event.type == MOUSEBUTTONDOWN and game.end:
- game = TicTacToe()
- elif event.type == MOUSEBUTTONDOWN:
- game.Event(event)
- game.Draw()
- Clock.tick(60)
- pygame.display.flip()
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement