If语句只适用于一个,而不适用于另一个

2024-10-04 05:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Pygame和一个按钮模块来复制一个简单电梯程序的代码。我遇到了一个问题,没有显示某个按钮(由按钮模块创建)的基础上,什么是当前楼层。你知道吗

if currentFloor != maxFloor:#Checks if the currentFloor is not equal to the maxFloor
            self.Button3.create_button(self.setDisplay, colcyan, 550, 100, 200, 100,0,"Up",colblack)#Button to add one to currentLevel

提供的这个代码可以使按钮上升。不过,当我尝试使用类似的代码行为down按钮重新创建它时,它会出错。你知道吗

elif currentFloor != startFloor:#Checks if the currentFloor is not equal to the startFloor
            self.Button1.create_button(self.setDisplay, colred, 550, 400, 200, 100,0,"Down",colblack)#Button to subtract one to currentLevel

产生的错误:

Traceback (most recent call last):
  File "G:\Python APCSP\Elevator\Example.py", line 72, in <module>
    obj = Elevator()
  File "G:\Python APCSP\Elevator\Example.py", line 24, in __init__
    self.runGame()
  File "G:\Python APCSP\Elevator\Example.py", line 66, in runGame
    if self.Button1.pressed(pygame.mouse.get_pos()):
  File "G:\Python APCSP\Elevator\Buttons.py", line 29, in pressed
    if mouse[0] > self.rect.topleft[0]:
AttributeError: Button instance has no attribute 'rect'

我不确定为什么与第一个非常相似的if语句会提供这样的错误。你知道吗

下面将提供完整的源代码。你知道吗

电梯程序源代码:

import pygame, Buttons, sys
from pygame.locals import *

#Color Options
colwhite = (255,255,255)
colblack = (0,0,0)
colgray = (33,33,33)
colblue = (0,61,103)
colred = (103,0,9)
colyellow = (255,229,9)
colgreen = (0,103,42)
colcyan = (0,118,118)
colpurple = (103,0,103)

#Initialize pygame
pygame.init()

currentFloor = 0
maxFloor = 5
startFloor = 0

class Elevator:
    def __init__(self):
        self.runGame()

    #Create a display
    def display(self):
        width = 800
        height = 600
        self.setDisplay = pygame.display.set_mode((width,height),0,32)
        pygame.display.set_caption("Elevator Program")

    #Update the display and show the button
    def update_display(self):
        global currentFloor
        self.setDisplay.fill(colblue)
        #Parameters:                     surface,   color,   x,   y,   length, height, width,    text,      text_color
        self.Button2.create_button(self.setDisplay, colblue, 525, 225, 250, 150,0,"Current Floor: "+str(currentFloor),colwhite)#Not a used button, just to display currentFloor
        if currentFloor != maxFloor:#Checks if the currentFloor is not equal to the maxFloor
            self.Button3.create_button(self.setDisplay, colcyan, 550, 100, 200, 100,0,"Up",colblack)#Button to add one to currentLevel
        elif currentFloor != startFloor:#Checks if the currentFloor is not equal to the startFloor
            self.Button1.create_button(self.setDisplay, colred, 550, 400, 200, 100,0,"Down",colblack)#Button to subtract one to currentLevel
        pygame.display.flip()


    #Run the loop
    def runGame(self):
        global currentFloor
        self.Button2 = Buttons.Button()
        self.Button1 = Buttons.Button()
        self.Button3 = Buttons.Button()
        self.display()
        while True:
            self.update_display()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == MOUSEBUTTONDOWN:
                    if currentFloor != maxFloor:
                        if self.Button3.pressed(pygame.mouse.get_pos()):
                            print "Going Up"
                            currentFloor += 1
                            print currentFloor
                    if currentFloor != startFloor:
                        if self.Button1.pressed(pygame.mouse.get_pos()):
                            print "Going Down"
                            currentFloor -= 1
                            print currentFloor

if __name__ == '__main__':
    obj = Elevator()

按钮模块源代码:

import pygame
from pygame.locals import *
pygame.init()
class Button:
    def create_button(self, surface, color, x, y, length, height, width, text, text_color):
        surface = self.draw_button(surface, color, length, height, x, y, width)
        surface = self.write_text(surface, text, text_color, length, height, x, y)
        self.rect = pygame.Rect(x,y, length, height)
        return surface

    def write_text(self, surface, text, text_color, length, height, x, y):
        font_size = int(length//len(text))
        myFont = pygame.font.SysFont("Calibri", font_size)
        myText = myFont.render(text, 1, text_color)
        surface.blit(myText, ((x+length/2) - myText.get_width()/2, (y+height/2) - myText.get_height()/2))
        return surface

    def draw_button(self, surface, color, length, height, x, y, width):           
        for i in range(1,10):
            s = pygame.Surface((length,height))
            s.fill(color)
            pygame.draw.rect(s, color, (x-i,y-i,length+i,height+i), width)
            surface.blit(s, (x,y))

        pygame.draw.rect(surface, (190,190,190), (x,y,length,height), 1)  
        return surface

    def pressed(self, mouse):
        if mouse[0] > self.rect.topleft[0]:
            if mouse[1] > self.rect.topleft[1]:
                if mouse[0] < self.rect.bottomright[0]:
                    if mouse[1] < self.rect.bottomright[1]:
                        return True
                    else: return False
                else: return False
            else: return False
        else: return False

Tags: thetotextselfifdisplaybuttonsurface
2条回答

每次更新update_display()后调用currentFloor函数。

一旦按下up按钮,currentFloor的值就不再是0。你知道吗

因此,第二个if条件(if currentFloor != startFloor在runGame的while循环中)也将被检查,但是由于update_diplay()没有在中间被调用,因此没有初始化down的按钮。

同样在update_display()函数中,将这两个条件都设置为if,因为无论发生什么情况,都需要检查这两个条件。
下面是while循环的样子:

self.update_display()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN:
            if currentFloor != maxFloor:
                if self.Button3.pressed(pygame.mouse.get_pos()):
                    print "Going Up"
                    currentFloor += 1
                    print currentFloor
                    self.update_display()
            if currentFloor != startFloor:
                if self.Button1.pressed(pygame.mouse.get_pos()):
                    print "Going Down"
                    currentFloor -= 1
                    print currentFloor
                    self.update_display()

rect属性仅在调用Button.create_button()时初始化。你知道吗

但是,在runGame()中运行的代码期望此属性存在:在按钮1或3上调用Button.pressed()之前调用Button.pressed()。你知道吗

在尝试使用或查询按钮之前,您需要确保这些按钮已正确初始化。或者您的pressed()方法需要检查按钮是否已初始化,如果未初始化,则返回False。你知道吗

相关问题 更多 >