如果声明适用于一个,而不是另一个

时间:2014-03-03 09:01:50

标签: python pygame

我正在使用Pygame和Buttons Module来复制简单电梯程序的代码。我遇到的问题是没有显示某个按钮(由按钮模块创建)基于当前的地板。

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

错误产生:

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

2 个答案:

答案 0 :(得分:4)

rect属性仅在您致电Button.create_button()时初始化。

但是,您在runGame()中运行期望此属性存在的代码:在按钮1或3上调用Button.pressed()之前调用Button.create_button() 。 / p>

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

答案 1 :(得分:0)

每次更新update_display()后调用currentFloor功能。

按下up按钮后,currentFloor的值不再是0

因此,还会检查第二个if条件(runGame的while循环中的if currentFloor != startFloor),但由于update_diplay()之间没有调用,因此没有{{1}的按钮初始化。

同样在down函数中,条件为update_display(),无论如何都需要检查if
以下是您的while循环的样子:

buttons