为什么点击鼠标后屏幕上没有出现X?

问题描述 投票:0回答:1

我想实现程序在按下鼠标的位置将“X”传送到屏幕上的功能。然而,一旦我运行该程序,什么也没有出现。 take_turn 函数将值存储在二维数组中,并将鼠标单击的位置存储在名为“positions”的列表中。然后,在主游戏循环中,应将 X 放置在通过位置列表迭代的所有位置中。我应该如何修改我的代码?

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()

我尝试将填充函数放置在游戏循环的不同位置,但没有任何变化。

python pygame game-development tic-tac-toe
1个回答
0
投票

目前,您将

text
传输到
text
,而不是将
text
传输到
WIN

所以只需更改:

text.blit(text, pos)

对此:
WIN.blit(text, pos)

WIN
是我们绘画的表面,
text
是我们绘画的来源。

如果您喜欢使用透明背景位图传输“X”,您可以在创建文本表面后为其设置颜色键:

text.set_colorkey((0, 0, 0))

© www.soinside.com 2019 - 2024. All rights reserved.