You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击鼠标后屏幕不显示X?PyGame代码修改求助

问题解决:点击鼠标绘制X无显示的修复方案

核心错误分析

你代码里绘制X的逻辑完全错误:text.blit(text, pos)是让渲染好的X文本Surface自己绘制自己,这不会在游戏窗口上产生任何效果。正确的做法是在游戏窗口(WIN)上调用blit方法,把X文本绘制到窗口上。

具体修改点

  1. 修正绘制逻辑:将循环里的text.blit(text, pos)替换为WIN.blit(text, pos)
  2. 优化X的显示位置:直接存储鼠标点击坐标会让X偏在格子角落,建议计算格子的中心坐标后再存入positions,让X居中显示
  3. 兼容字体缺失情况:如果本地没有Poppins-ExtraBold.ttf字体,改用pygame默认字体避免崩溃
  4. 新增格子占用检查:避免重复点击同一个格子导致无效操作

修改后的完整代码

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(None, 150)
text = font.render('X', True, (255, 255, 255))
# 计算X文本的尺寸,用于居中
text_rect = text.get_rect()


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), width=5)
        pygame.draw.line(screen, (255, 255, 255), (0, ((i+1) * SIZE) + SIZE), (WIDTH, ((i+1) * SIZE) + SIZE), width=5)


def take_turn(position):
    global count
    global positions

    if position[1] > SIZE:
        # 计算点击所在的格子行列
        row = int((position[1] - SIZE) / SIZE)
        col = int(position[0] / SIZE)
        # 检查格子是否未被占用
        if board[row][col] == 0:
            if count % 2 == 0:
                board[row][col] = 1
                # 计算格子中心坐标,让X居中显示
                center_x = col * SIZE + SIZE // 2 - text_rect.centerx
                center_y = SIZE + row * SIZE + SIZE // 2 - text_rect.centery
                positions.append((center_x, center_y))
                count += 1
            else:
                board[row][col] = 2
                count += 1
        # 打印棋盘状态
        for i in range(len(board)):
            print(board[i])


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)
    # 正确在窗口上绘制X
    for pos in positions:
        WIN.blit(text, pos)
    pygame.display.update()

内容的提问来源于stack exchange,提问作者thomas beller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 00:26:13