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

Pygame实现Hangman游戏时图片无法正常切换的问题求助

刽子手(Hangman)游戏图片切换故障排查与修复

问题描述

我用Pygame开发了一款刽子手游戏,所有功能均已完成,但图片无法正常循环切换。图片与main.py位于同一目录下,文件名已多次核对无误,仍未找到解决方案。

问题代码片段(图片加载部分)

# Load images.
images = []
for i in range(7):
    image_path = os.path.join(os.path.dirname(__file__), f"Hangman{i}.png")
    image = pygame.image.load("Hangman" + str(i) + ".png")  # Adjusted the filenames
    images.append(image)

完整原始代码

import sys
import os
import math
import random
import pygame
from pygame.locals import QUIT

# Sets up display.
pygame.init()
display = pygame.display.set_mode((1600, 1000))
pygame.display.set_caption("Vancouver Canucks Hangman")

# Fonts.
letterfont = pygame.font.SysFont("arial", 32)
wordfont = pygame.font.SysFont("arial", 36)

# Game variables.
status = 0
guessed = []
words = [
    "ELIAS PETTERSSON", "J.T MILLER", "QUINN HUGHES", "BROCK BOESER",
    "FILIP HRONEK", "THATCHER DEMKO", "CASEY DESMITH", "SAM LAFFERTY",
    "CONOR GARLAND", "DAKOTA JOSHUA", "ANDREI KUZMENKO", "IAN COLE", "TYLER MYERS",
    "NIKITA ZADOROV", "ROBERTO LUONGO", "HENRIK SEDIN", "DANIEL SEDIN", "ALEX BURROWS",
    "MARKUS NASLUND", "KIRK MCLEAN", "TREVOR LINDEN", "PAVEL BURE",
    "GINO ODJICK", "TODD BERTUZZI", "STAN SMYL", "ORLAND KURTENBACH",
    "THOMAS GRADIN", "BO HORVAT", "RYAN KESSLER"
]
word = random.choice(words).upper()  # Ensure the word is in uppercase.
status = 0
# Button variables.
radius = 20
gap = 15
letters = []
startx = round((1600 - (radius * 2 + gap) * 13) / 2)
starty = 650 
A = 65
for i in range(26):
    x = startx + gap * 2 + ((radius * 2 + gap) * (i % 13))
    y = starty + ((i // 13) * (gap + radius * 2))
    letters.append([x, y, chr(A + i), True])  # Puts letters on buttons.

# Colors
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
yellow = (255, 255, 0)

# Load images.
images = []
for i in range(7):
    image_path = os.path.join(os.path.dirname(__file__), f"Hangman{i}.png")
    image = pygame.image.load("Hangman" + str(i) + ".png")  # Adjusted the filenames
    images.append(image)
    


# Drawing function.
def draw():
    display.fill(white)
    display.blit(images[status], (150, 100))

    # Draw word with spaces between letters.
    spaced_word = ""
    for letter in word:
        if letter in guessed:
            spaced_word += letter + " "
        elif letter == " ":
            spaced_word += "  "
        else:
            spaced_word += "_ "
    text = wordfont.render(spaced_word, 1, black)
    display.blit(text, (470, 500))

    # Draw buttons.
    for letter in letters:
        x, y, ltr, visible = letter
        if visible:
            pygame.draw.circle(display, blue, (x, y), radius, 3) # Line of code that actually draws the buttons.
            text = letterfont.render(ltr, 1, blue) # Button visuals like colour.
            display.blit(text,
                         (x - text.get_width() / 2, y - text.get_height() / 2)) 

    pygame.display.update() # Updates display.

# Set up game loop.
incorrectguess = 0
FPS = 60
clock = pygame.time.Clock()

# Main game loop
run = True


def display_message(message, HEIGHT): # Function to display message.
    global incorrectguess
    pygame.time.delay(1000)
    display.fill(white)
    text = wordfont.render(message, 1, black)
    display.blit(text, (display.get_width()/2 - text.get_width()/2, HEIGHT/2 - text.get_height()/2))
    pygame.display.update()
    pygame.time.delay(3000)

# Main gameplay loop.
while run:
    for event in pygame.event.get():
        if event.type == QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            m_x, m_y = pygame.mouse.get_pos()
            for letter in letters: # Loop that makes sure the letter buttons work.
                x, y, ltr, visible = letter
                if visible:
                    dis = math.sqrt((x - m_x) ** 2 + (y - m_y) ** 2)
                    if dis < radius:
                        letter[3] = False  # Set button visibility to False when clicked
                        guessed.append(ltr)
                        if ltr not in word: # Keeps track of wrong guesses.
                            incorrectguess += 1
                            

    draw()
    pygame.display.update()

    if incorrectguess >= 6:
        status = 6  # Sets the right image.
        draw() # Draws the final image.
        pygame.display.update() # Updates final image.
        display_message("YOU LOSE!", 1000) # Displays lose message.
        run = False # Ends game.

    # Check win condition
    won = all(letter in guessed or letter == ' ' for letter in word)

    if won:
        # Display win screen
        display.fill(blue)
        text = wordfont.render("YOU WON!", 1, white)
        display.blit(text, (display.get_width() // 2 - text.get_width() // 2,
                            display.get_height() // 2 - text.get_height() // 2))
        pygame.display.update()

        # Delay the closing of the window after winning
        pygame.time.delay(3000)
        run = False

    clock.tick(FPS)

pygame.quit()
sys.exit()

故障原因与修复方案

核心问题

status变量未随错误猜测次数同步更新。你仅在错误次数达到6时将status设为6,但之前每次错误猜测后,status始终保持初始值0,导致图片一直显示第一张。此外,图片加载时拼接了正确路径但未实际使用,存在潜在路径风险。

修复步骤

  1. 同步status与错误次数:每次错误猜测后,将status设置为当前incorrectguess的值,确保图片索引随错误次数递增。
  2. 优化图片加载:使用拼接好的完整路径image_path加载图片,避免相对路径的潜在问题。

修复后的关键代码

图片加载部分

# Load images.
images = []
for i in range(7):
    image_path = os.path.join(os.path.dirname(__file__), f"Hangman{i}.png")
    image = pygame.image.load(image_path)  # 使用拼接好的完整路径
    images.append(image)

错误猜测处理部分

if ltr not in word: # Keeps track of wrong guesses.
    incorrectguess += 1
    status = incorrectguess  # 同步更新status,对应图片索引

修复后效果

每次错误猜测后,status会同步递增,draw()函数会自动切换到对应阶段的刽子手图片,直到错误次数达到6时显示最终图片。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:08:11