I want to implement the feature where the program blits an 'X' to the screen at the position where the mouse is pressed. However, once I run the program, nothing appears. The take_turn function stores a value in a 2D array and stores the position of the mouse click in a list called "positions". Then, in the main game loop, an X should be placed in all positions that are iterated through the positions list. How should I modify my code?
import pygame
import sys
pygame.init()
HEIGHT = 800
WIDTH = 600
BOARD_COLOR = (50, 50, 50)
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game")
ROWS = 3
SIZE = 200
count = 0
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
positions = []
font = pygame.font.Font('Poppins-ExtraBold.ttf', 150)
text = font.render('X', True, (255, 255, 255))
def draw_board(screen):
pygame.draw.line(screen, (255, 255, 255), (0, SIZE), (WIDTH, SIZE), width=5)
for i in range(0, ROWS-1):
pygame.draw.line(screen, (255, 255, 255), ((i+1)*SIZE, SIZE), ((i+1)*SIZE, HEIGHT))
pygame.draw.line(screen, (255, 255, 255), (0, ((i+1) * SIZE) + SIZE), (WIDTH, ((i+1) * SIZE) + SIZE))
def take_turn(position):
global count
global positions
if position[1] > SIZE:
if count % 2 == 0:
board[int((position[1] - SIZE) / SIZE)][int((position[0]) / SIZE)] = 1
for i in range(len(board)):
print(board[i])
positions.append((position[0], position[1]))
count += 1
else:
board[int((position[1] - SIZE) / SIZE)][int((position[0]) / SIZE)] = 2
for i in range(len(board)):
print(board[i])
count += 1
running = True
while running:
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
take_turn(mouse)
WIN.fill(BOARD_COLOR)
draw_board(WIN)
for pos in positions:
text.blit(text, pos)
pygame.display.update()
I tried to place the fill function in different places of the game loop, but nothing changes.
Currently, you blit text
onto text
, instead of blitting text
onto WIN
.
So just change:
text.blit(text, pos)
to this:
WIN.blit(text, pos)
WIN
is here the surface on which we draw and text
is the source of what we draw.
If you like to blit the "X" with transparent background, you can set a colorkey for the text surface after creating it:
text.set_colorkey((0, 0, 0))