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

Pygame潜艇游戏菜单文字鼠标悬停无法变色问题求助

问题分析与修复方案

我帮你找出了几个导致菜单文字悬停无法变色的核心问题,咱们一步步来解决:

关键问题点

  • 鼠标位置未实时更新:你仅在程序初始化时获取了一次鼠标位置location = pygame.mouse.get_pos(),但主循环中没有重新获取,导致这个变量始终是启动时的固定值,无法响应鼠标移动。
  • 变量名拼写错误:
    • 你定义的颜色变量是colour1/colour2/colour3,但渲染文本时误用了barva1/barva2/barva3(推测是拼写失误);
    • 主循环里的polozaj是未定义的变量,应该是location的笔误。
  • 悬停检测逻辑错误:用location == (100, 200)判断鼠标悬停,要求鼠标精准落在单个像素点上,这几乎不可能触发,正确的做法是检测鼠标是否在文本的矩形区域内。
  • 文本未重新渲染:你只在初始化时渲染了一次文本,之后即使颜色变量改变,也没有重新生成带新颜色的文本对象,所以屏幕上的文字颜色不会更新。

修复后的完整代码

import pygame
pygame.init()

screen = pygame.display.set_mode((600, 500), pygame.FULLSCREEN)
pygame.display.set_caption('Podmornca')
run = True

black = (0,0,0)
red = (255,0,0)
colour1 = black
colour2 = black
colour3 = black

background = pygame.image.load('meni.png')
clock = pygame.time.Clock()
font = pygame.font.SysFont('bauhaus93', 20)

def grafika():
    clock.tick(60)
    screen.blit(background, (0,0))
    # 每次绘制前重新渲染文本,确保颜色生效
    text1 = font.render('SINGLE PLAYER', 1, colour1)
    text2 = font.render('MULTIPLAYER', 1, colour2)
    text3 = font.render('QUIT', 1, colour3)
    
    screen.blit(text1, (100, 200))
    screen.blit(text2, (100, 250))
    screen.blit(text3, (100, 300))
    
    # 获取文本的矩形区域,用于悬停检测
    text1_rect = text1.get_rect(topleft=(100, 200))
    text2_rect = text2.get_rect(topleft=(100, 250))
    text3_rect = text3.get_rect(topleft=(100, 300))
    
    pygame.display.update()
    return text1_rect, text2_rect, text3_rect

while run:
    # 实时获取鼠标位置
    location = pygame.mouse.get_pos()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        # 处理全屏退出(比如按ESC键)
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                run = False
    
    # 获取文本矩形,用于检测悬停
    text1_rect, text2_rect, text3_rect = grafika()
    
    # 重置颜色为默认值
    colour1 = black
    colour2 = black
    colour3 = black
    
    # 检测鼠标是否在文本矩形内,修改对应颜色
    if text1_rect.collidepoint(location):
        colour1 = red
    if text2_rect.collidepoint(location):
        colour2 = red
    if text3_rect.collidepoint(location):
        colour3 = red

pygame.quit()

修复说明

  1. 实时更新鼠标位置:在主循环的每次迭代中都调用pygame.mouse.get_pos(),保证location始终是当前鼠标位置。
  2. 修正变量名:统一使用colour1/colour2/colour3作为颜色变量,移除未定义的polozaj。
  3. 区域检测悬停:通过get_rect()获取文本的矩形区域,用collidepoint()检测鼠标是否在区域内,这是UI交互的标准做法。
  4. 动态渲染文本:将文本渲染逻辑放到grafika()函数中,每次绘制前都重新生成带当前颜色的文本对象,确保颜色变化能立即显示。
  5. 新增全屏退出逻辑:添加了ESC键退出全屏的处理,方便测试操作。

内容的提问来源于stack exchange,提问作者Jonatan Jurkovnik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:17:42