0

My tic-tac-toe pygame code allows for clicks. I don't know how to enter the clicks into my board array so I can check for wins. Also, how do I get the computer to move?

import sys, pygame
from pygame.locals import *
import random
import time
import re
def setup_board(width=860,height=640):
    """A function for setting up a tic-tac-toe board, note that you have to call this multiple times if you draw over it"""
    size = width, height
    screen = pygame.display.set_mode(size) #sets up the screen to the size we want
    screen.fill('white')
    pygame.draw.line(screen, 'black', (width/3, 0), (width/3,height), 3)
    pygame.draw.line(screen, 'black', (2*width/3, 0), (2*width/3,height), 3)
    pygame.draw.line(screen, 'black', (0, height/3), (860,height/3), 3)
    pygame.draw.line(screen, 'black', (0, 2*height/3), (860,2*height/3), 3)
    return screen, width, height

def get_board_index(x, y):
    return x // (860 /3), y // (640 / 3)

def get_board_position(x, y):
    dw, dl = 860//3, 640//3
    return x//dw, y//dl, dw, dl

def get_draw_position(x, y):
    nx, ny, dw, dl = get_board_position(x, y)
    return nx*dw + dw/2, ny*dl + dl/2

def toss_coin():
    coin_states = ['heads', 'tails']
    return random.choice(coin_states)

def get_computer_move(board):
    for row in range(3):
        for col in range(3):
            if board[row][col] == '':
                return row, col

def get_player_move():
    """Returns the player move as a row and column"""
    valid_input = False
    while not valid_input:
        placement = input("Where would you like to play (enter as row,column e.g. 1,3)")
        match = re.search('[1,2,3],[1,2,3]', placement)
        valid_input = match is not None
        if valid_input:
            row, col = placement.split(',')
            row, col = int(row)-1, int(col)-1
            return row, col

def check_win(board):
    """Checks to see if there is a winner"""
    for row in range(3):
        if board[row][0] == board[row][1] == board[row][2] != '':
            return True
    for column in range(3):
        if board[0][column] == board[1][column] == board[2][column] != '':
            return True
    if board[0][0] == board[1][1] == board[2][2] != '':
        return True
    elif board[2][0] == board[1][1] == board[0][2] != '':
        return True

def print_board(board):
    """This function will print a tic-tac-toe board to the console"""
    for index, row in enumerate(board):
        print('|'.join(row))
        if index < 2:
            print('-----')

pygame.init()
font = pygame.font.SysFont('arial', 110)
small_font = pygame.font.SysFont('arial', 30)
screen, width, height = setup_board()
clock=pygame.time.Clock()#gets the game clock, we are using this to ensure that we only run at 60fps
rx = font.render("X", False, "black")
quit_text = small_font.render("Quit!", False, "red")
active_game = True
board = [['' ,'', ''], ['', '', ''],['', '', '']]
while active_game:
    quit_rect = pygame.draw.rect(screen, 'gray', (50, 50, 60, 40), 1)
    screen.blit(quit_text, quit_rect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == MOUSEBUTTONUP:
            ex, ey = event.pos
            if quit_rect[0] <= ex <= quit_rect[0] + quit_rect[2] and quit_rect[1] <= ey <= quit_rect[1] + quit_rect[3]:
                sys.exit()
            else:
                screen.blit(rx, get_draw_position(ex, ey))
    if check_win(board):
            active_game = False
            # replace with drawing winner to the screen
            print("You win!")
            time.sleep(5)
    pygame.display.flip()
    clock.tick_busy_loop( 60 )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 1
    Your `screen.blit` is drawing the X in the right position. You can figure out from that which cell was clicked so you can add it to your board. And as soon as you know a new X has been added to the board, that's where you let the computer play. – Tim Roberts Mar 20 '21 at 23:44
  • `get_board_position` returns the column and row of the click. – Rabbid76 Mar 21 '21 at 07:16

0 Answers0