Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

tic-tac toe in pygame

import pygame, sys
import numpy as np
pygame.init()

WIDTH = 600
HEIGHT = 600
LINE_WIDTH = 15
WIN_LINE_WIDTH = 15
BOARD_ROWS = 3
BOARD_COLS = 3
SQUARE_SIZE = 200
CIRCLE_RADIUS = 60
CIRCLE_WIDTH = 15
CROSS_WIDTH = 25
SPACE = 55

RED = (255, 0, 0)
BG_COLOR = (20, 200, 160)
LINE_COLOR = (23, 145, 135)
CIRCLE_COLOR = (239, 231, 200)
CROSS_COLOR = (66, 66, 66)

screen = pygame.display.set_mode( (WIDTH, HEIGHT) )
pygame.display.set_caption( 'TIC TAC TOE' )
screen.fill( BG_COLOR )

board = np.zeros( (BOARD_ROWS, BOARD_COLS) )

def draw_lines():
	
	pygame.draw.line( screen, LINE_COLOR, (0, SQUARE_SIZE), (WIDTH, SQUARE_SIZE), LINE_WIDTH )
	
	pygame.draw.line( screen, LINE_COLOR, (0, 2 * SQUARE_SIZE), (WIDTH, 2 * SQUARE_SIZE), LINE_WIDTH )

	pygame.draw.line( screen, LINE_COLOR, (SQUARE_SIZE, 0), (SQUARE_SIZE, HEIGHT), LINE_WIDTH )

	pygame.draw.line( screen, LINE_COLOR, (2 * SQUARE_SIZE, 0), (2 * SQUARE_SIZE, HEIGHT), LINE_WIDTH )

def draw_figures():
	for row in range(BOARD_ROWS):
		for col in range(BOARD_COLS):
			if board[row][col] == 1:
				pygame.draw.circle( screen, CIRCLE_COLOR, (int( col * SQUARE_SIZE + SQUARE_SIZE//2 ), int( row * SQUARE_SIZE + SQUARE_SIZE//2 )), CIRCLE_RADIUS, CIRCLE_WIDTH )
			elif board[row][col] == 2:
				pygame.draw.line( screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SPACE), CROSS_WIDTH )	
				pygame.draw.line( screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), CROSS_WIDTH )

def mark_square(row, col, player):
	board[row][col] = player

def available_square(row, col):
	return board[row][col] == 0

def is_board_full():
	for row in range(BOARD_ROWS):
		for col in range(BOARD_COLS):
			if board[row][col] == 0:
				return False

	return True

def check_win(player):
	for col in range(BOARD_COLS):
		if board[0][col] == player and board[1][col] == player and board[2][col] == player:
			draw_vertical_winning_line(col, player)
			return True

	for row in range(BOARD_ROWS):
		if board[row][0] == player and board[row][1] == player and board[row][2] == player:
			draw_horizontal_winning_line(row, player)
			return True

	if board[2][0] == player and board[1][1] == player and board[0][2] == player:
		draw_asc_diagonal(player)
		return True

	if board[0][0] == player and board[1][1] == player and board[2][2] == player:
		draw_desc_diagonal(player)
		return True

	return False

def draw_vertical_winning_line(col, player):
	posX = col * SQUARE_SIZE + SQUARE_SIZE//2

	if player == 1:
		color = CIRCLE_COLOR
	elif player == 2:
		color = CROSS_COLOR

	pygame.draw.line( screen, color, (posX, 15), (posX, HEIGHT - 15), LINE_WIDTH )

def draw_horizontal_winning_line(row, player):
	posY = row * SQUARE_SIZE + SQUARE_SIZE//2

	if player == 1:
		color = CIRCLE_COLOR
	elif player == 2:
		color = CROSS_COLOR

	pygame.draw.line( screen, color, (15, posY), (WIDTH - 15, posY), WIN_LINE_WIDTH )

def draw_asc_diagonal(player):
	if player == 1:
		color = CIRCLE_COLOR
	elif player == 2:
		color = CROSS_COLOR

	pygame.draw.line( screen, color, (15, HEIGHT - 15), (WIDTH - 15, 15), WIN_LINE_WIDTH )

def draw_desc_diagonal(player):
	if player == 1:
		color = CIRCLE_COLOR
	elif player == 2:
		color = CROSS_COLOR

	pygame.draw.line( screen, color, (15, 15), (WIDTH - 15, HEIGHT - 15), WIN_LINE_WIDTH )

def restart():
	screen.fill( BG_COLOR )
	draw_lines()
	for row in range(BOARD_ROWS):
		for col in range(BOARD_COLS):
			board[row][col] = 0

draw_lines()

player = 1
game_over = False

while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()

		if event.type == pygame.MOUSEBUTTONDOWN and not game_over:

			mouseX = event.pos[0] 
			mouseY = event.pos[1] 

			clicked_row = int(mouseY // SQUARE_SIZE)
			clicked_col = int(mouseX // SQUARE_SIZE)

			if available_square( clicked_row, clicked_col ):

				mark_square( clicked_row, clicked_col, player )
				if check_win( player ):
					game_over = True
				player = player % 2 + 1

				draw_figures()

		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_r:
				restart()
				player = 1
				game_over = False

	pygame.display.update()
Comment

tic-tac toe in pygame

import pygame
black = (0, 0, 0)
white = (255, 255, 255)

red = (255, 0, 0)
WIDTH = 20
HEIGHT = 20
MARGIN = 5
grid = []
for row in range(10):
    grid.append([])
    for column in range(10):
        grid[row].append(0) 
grid[1][5] = 1
pygame.init()
window_size = [255, 255]
scr = pygame.display.set_mode(window_size)
pygame.display.set_caption("Grid")
done = False
clock = pygame.time.Clock()
while not done:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True 
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            column = pos[0] // (WIDTH + MARGIN)
            row = pos[1] // (HEIGHT + MARGIN)
            grid[row][column] = 1
            print("Click ", pos, "Grid coordinates: ", row, column)
    scr.fill(black)
    for row in range(10):
        for column in range(10):
            color = white
            if grid[row][column] == 1:
                color = red
            pygame.draw.rect(scr,
                             color,
                             [(MARGIN + WIDTH) * column + MARGIN,
                              (MARGIN + HEIGHT) * row + MARGIN,
                              WIDTH,
                              HEIGHT])
    clock.tick(50)
    pygame.display.flip()
pygame.quit()
Comment

tic tac toe pygame

#you need three pictures: 
#line.png (600 X 10): line (with rounded corners)
#x.png (200 X 200): an X
#o.png (200 X 200): an O

import pygame as pg
import numpy as np
import time as t
import random as r
import pdb

pg.init()
pg.font.init()

screen = pg.display.set_mode((600,600),pg.DOUBLEBUF)
pg.display.set_caption("...?")
playing = True

line_picture_vert = pg.image.load("line.png").convert_alpha()
line_picture_horiz = pg.transform.rotate(line_picture_vert, 90)

x_picture = pg.image.load("x.png").convert_alpha()
o_picture = pg.image.load("o.png").convert_alpha()

grid = np.zeros((3,3), dtype="int")

#0 = nothing
#1 = x
#2 = o

#functions and classes
def draw_grid(screen):
    screen.blit(line_picture_vert,(195, 0))
    screen.blit(line_picture_horiz,(0, 195))
    screen.blit(line_picture_vert,(395, 0))
    screen.blit(line_picture_horiz,(0, 395))
    for x in range(3):
        for y in range(3):
            if grid[y, x] == 1: #x
                screen.blit(x_picture,(x*200, y*200))
            elif grid[y, x] == 2: #o
                screen.blit(o_picture,(x*200, y*200))

def draw_win_lines(screen, grid_win_line, line_animation):
    for line in grid_win_line:
        posx = line[0][0] + (line[1][0] - line[0][0]) * line_animation
        posy = line[0][1] + (line[1][1] - line[0][1]) * line_animation
        pg.draw.line(screen, (200,200,200), line[0], (posx,posy), width=10)



def calculate_mouse_pos(mx, my):
    mrx = int(mx/200)
    mry = int(my/200)
    return mrx, mry

def calculate_if_row(grid):
    win = 0 #if win 1: x has won, if win 2: o has won
    grid_win_line = []
    line_width = 10
    half_l_w = int(line_width/2)
    
    #check horizontal
    for y in range(3): #x = 0, 1, 2
        if grid[y, 0] == grid[y, 1] and grid[y, 1] == grid[y, 2] and grid[y, 0] != 0:
            win = grid[y, 0]
            grid_win_line.append([[100-half_l_w,y*200+100-half_l_w],[500-half_l_w,y*200+100-half_l_w]])

    #check vertical
    for x in range(3): #x = 0, 1, 2
        if grid[0, x] == grid[1, x] and grid[1, x] == grid[2, x] and grid[2, x] != 0:
            win = grid[0, x]
            grid_win_line.append([[x*200+100-half_l_w, 100-half_l_w],[x*200+100-half_l_w, 500-half_l_w]])

    #check diagonals
    if grid[0, 0] == grid[1, 1] and grid[1, 1] == grid[2, 2] and grid[1, 1] != 0:
        win = grid[1, 1]
        grid_win_line.append([[100-half_l_w,100-half_l_w],[500-half_l_w,500-half_l_w]])

    if grid[2, 0] == grid[1, 1] and grid[1, 1] == grid[0, 2] and grid[1, 1] != 0:
        win = grid[1, 1]
        grid_win_line.append([[100-half_l_w,500-half_l_w],[500-half_l_w,100-half_l_w]])

    return win, grid_win_line
        


#game variables
turn = 1 #turn 1 = x, turn 2 = o
win = 0 #when one of player wins
grid_win_line = [] #line to be drawn when someone wins
grid_change = True #when grid changes (for 1 frame)
line_animation = 0 #from 0.0 to 1.0 animation of line
deltaTime = 0 #deltaTime

#menu variables

clock = pg.time.Clock()

while playing:

    #events

    for e in pg.event.get():
        if e.type == pg.QUIT:
            playing = False
            
        if e.type == pg.KEYDOWN:
            if e.key == pg.K_ESCAPE:
                playing = False

        if e.type == pg.MOUSEBUTTONDOWN:
            mousebtn = pg.mouse.get_pressed()
            mx, my = pg.mouse.get_pos()

            if mousebtn[0]: #left mouse btn
                mrx, mry = calculate_mouse_pos(mx, my)
                if grid[mry, mrx] == 0 and win == 0:
                    grid[mry,mrx] = turn
                    turn = turn % 2 + 1
                    grid_change = True

    #calculate stuff
    if grid_change:
        win, grid_win_line = calculate_if_row(grid)

    #update screen

    screen.fill((40,40,40))


    draw_grid(screen)
    draw_win_lines(screen, grid_win_line, line_animation)
    if win != 0 and line_animation < 1:
        line_animation += 0.01
    pg.event.pump()
    pg.display.flip()
    grid_change = False

    deltaTime = clock.tick(60) #max of 60 fps

pg.font.quit()
pg.quit()
Comment

PREVIOUS NEXT
Code Example
Python :: change column names pandas 
Python :: python Sort the dictionary based on values 
Python :: while true loop python 
Python :: how to use coordinates in python 
Python :: rearrange columns pandas 
Python :: recursive factorial python 
Python :: sorting decimal numbers in python 
Python :: stop flask server 
Python :: pandas dataframe caption 
Python :: how to add value in array django 
Python :: get data from kaggle to colab 
Python :: cropping image google colab 
Python :: how to sort the order in multiple index pandas 
Python :: add elements to list python 
Python :: python string: .join() 
Python :: codechef solution 
Python :: iterrrows 
Python :: count element in set python 
Python :: pygame keys keep pressing 
Python :: python machine learning 
Python :: python keyboard input arrow keys 
Python :: sort lexo python 
Python :: if df[col].unique()==2 
Python :: adding two strings together in python 
Python :: python type annotations list of specific values 
Python :: Insert list element at specific index 
Python :: strip() 
Python :: dict to tuple 
Python :: python break 
Python :: pandas read csv specify column dtype 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =