Reputation: 83
problem in my tic tac toe project once again, the circle isnt appearing where it should when I click a square, i tried multiple different coordinates but still cant figure it out, so if any of you know what to do then let me know, thanks.
import pygame, sys
import numpy as np
pygame.init()
screen_color = (28, 170, 156)
line_color = (23, 140, 135)
line_width = 9
screen = pygame.display.set_mode((550, 450))
pygame.display.set_caption("Tic Tac Toe")
screen.fill(screen_color)
board = np.zeros((3, 3))
def draw_lines():
#1st horizontal
pygame.draw.line(screen, line_color, (0, 135), (550, 135), line_width)
#2nd horizontal
pygame.draw.line(screen, line_color, (0, 300), (550, 300), line_width)
#1st vertical
pygame.draw.line(screen, line_color, (175, 0), (175, 450), line_width)
#2nd vertical
pygame.draw.line(screen, line_color, (370, 0), (370, 450), line_width)
def draw_figures():
for row in range(3):
for col in range(3):
if board[row][col] == 1:
pygame.draw.circle(screen, 'cyan', (int(col * 550/3), int(row * 450/3)), 60, 10)
def mark_square(row, col, player):
board[row][col] = player
def available_square(row, col):
if board[row][col] == 0:
return True
else:
return False
def is_board_full():
for row in range(3):
for col in range(3):
if board[row][col] == 0:
return False
print(is_board_full())
print(board)
draw_lines()
player = 1
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
mouseX = event.pos[0] #X coordinate
mouseY = event.pos[1] #Y coordinate
clicked_row = int(mouseY * 3 // 450)
clicked_col = int(mouseX * 3 // 550)
#print(clicked_col)
#print(clicked_row)
if available_square(clicked_row, clicked_col):
if player == 1:
mark_square(clicked_row, clicked_col, 1)
player = 2
elif player == 2:
mark_square(clicked_row, clicked_col, 2)
player = 1
draw_figures()
print(board)
pygame.display.update()
(if there any other errors let me know too) also let me know if getting the coordinates is trial and error or there is a specific way to do it, thanks!
Upvotes: 1
Views: 446
Reputation: 210968
The 3rd argument of pygame.draw.circle
is the center of the circle. Draw the circle at (col + 0.5) and (row + 0.5):
pygame.draw.circle(screen, 'cyan', (int(col * 550/3), int(row * 450/3)), 60, 10)
pygame.draw.circle(screen, 'cyan', (int((col + 0.5) * 550/3), int((row+0.5) * 450/3)), 60, 10)
Upvotes: 2
Reputation: 682
The problem is that the circle is centered on the grid and on on the middle of the squares. You need to add an offset to the center like this:
pygame.draw.circle(screen, 'cyan', (int(col * 550/3 + x_offset), int(row * 450/3 + y_offset)), 60, 10)
I would also recommend you to create a variable called grid_width so that you don't need to have numbers like 550 or 450 everywhere in your programm.
Upvotes: 2