【问题标题】:Not sure why If Statement is not working. (Pygame)不知道为什么 If 语句不起作用。 (游戏)
【发布时间】:2015-07-12 13:16:12
【问题描述】:

好的,现在当我在“start.png”按 E 时,它会跳转到“cele.png”,而我希望它会转到“new.png”。我希望它从“start.png”开始,然后当您按 E 时,它应该更改为“new.png”,如果您在背景为“new.png”时再次按 E,那么它应该更改为“cele.png”谢谢!

#import library
import pygame
from pygame.locals import *
 
#initialize the game
pygame.init()
width, height = 1000, 800
screen=pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame Window")
 
#load images
bg_filename = "start.png"
background = pygame.image.load(bg_filename)

#keep looping through
while 1:

    #clear the screen before drawing it again
    screen.fill(0)
    #draw the screen elements
    screen.blit(background, (0,0))
    #update the screen
    pygame.display.flip()
    #loop through the events
    for event in pygame.event.get():

        #start to new
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                if bg_filename == "start.png":
                    bg_filename = "new.png"
                    background = pygame.image.load(bg_filename)

        #new to cele 
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                if bg_filename == "new.png":
                    bg_filename = "cele.png"
                    background = pygame.image.load(bg_filename)

        #check if the event is the X button 
        if event.type==pygame.QUIT:
            #if it is quit the game
            pygame.quit() 
            exit(0)

【问题讨论】:

  • 与其写“blah”,不如更详细地描述运行代码时会发生什么?你认为问题出在哪里?对您来说似乎不重要的细节可能对我们很重要,甚至可能是您的问题的原因,所以这就是为什么包含许多细节总是比相反的更好(但是对于代码,它有点相反,只包括相关的和仅此而已,首先,在询问时添加更多)。
  • @JoachimPileborg 这是dup
  • 您正在尝试测试字符串是否与图像对象相等。

标签: python python-2.7 if-statement pygame


【解决方案1】:

Surfaces 没有用于检索文件名的对象,但也许您可以使用另一个变量来保存文件名?

#load images
bg_filename = "start.png"
background = pygame.image.load(bg_filename)

#keep looping through
while 1:
    #clear the screen before drawing it again
    screen.fill(0)
    #draw the screen elements
    screen.blit(background, (0,0))
    #update the screen
    pygame.display.flip()
    #loop through the events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e:
                if bg_filename == "start.png":
                    bg_filename = "new.png"
                    background = pygame.image.load(bg_filename)

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 2020-12-04
    • 2019-06-20
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多