Python pygame函数未定义

时间:2016-10-28 11:01:08

标签: python pygame

我被要求找到我堂兄的Pygame代码的问题。我在Python上并不大,更多地使用其他语言,我无法通过谷歌搜索或调试找到问题。基本上他得到" playGame未定义" 错误,playGame是一个函数。关于此的其他问题通常是因为:

  1. 在声明
  2. 之前调用该函数
  3. 该函数在与其称为
  4. 的不同范围内声明

    这些似乎都不是问题,所以我希望有些精通Python的人能够发现它。我已经在下面复制了他的代码,其中很多(我希望)与为简化而删除的问题无关。

    函数playGame无法正常工作,只需按一下按钮即可调用 def button(msg, x, y, action = None): 。有趣的是,退出函数工作正常,据我所知,它被调用并声明与playGame完全相同。

    # --------------- SETUP ---------------
    # Importing necessary modules
    import pygame
    import math
    import random
    # --------------- DISPLAY ---------------
    # Setting up the display
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption(title)
    # --------------- GLOBALS ---------------
    #removed globals from stackoverflow version
    
    
    # --------------- FUNCTIONS ---------------
    
    
    # Blitting the text
    def blitText(angle, power):
        #code
    
    
    # Drawing the tank model
    def drawTank():
        #code
    
    
    # Creating the buttons
    def button(msg, x, y, action = None):
        mousePos = pygame.mouse.get_pos()                                                                           # Gets the mouse position
        mouseClick = pygame.mouse.get_pressed()
    
        (buttonWidth, buttonHeight) = (175, 45)                                                                     # Sets the button width and height
        if x + (buttonWidth / 2) > mousePos[0] > x - (buttonWidth / 2) and y + buttonHeight > mousePos[1] > y:      # Checks if the mouse is over the button
            pygame.draw.rect(screen, darkGrey, [x - (buttonWidth / 2), y, buttonWidth, buttonHeight])                   # Draws a dark grey button
            if mouseClick[0] == 1 and action != None:                                                                   # Checks if the button is clicked
                if action == "play":
                    playGame()
                elif action == "exit":
                    exit()
        else:
            pygame.draw.rect(screen, grey, [x - (buttonWidth / 2), y, buttonWidth, buttonHeight])                       # Draws a light grey button if not
    
        screen.blit(msg, [x - (buttonWidth / 2), y])                                                                # Writes the text over the button
    
    
    # Defining the shell
    class shell(pygame.sprite.Sprite):              # Creates the shell() class
        def __init__(self):                             # Defines an initiation fuction for this class
            super().__init__()                              # Call the parent class constructor
            self.image = pygame.Surface([2, 2])             # Defines the bullet as a 2x4 surface
            self.image.fill(black)                          # Paints the bullet black
            self.rect = self.image.get_rect()               # Gets the area size of the bullet
    
        def update(self):                                                                                                                               # Defines a function as update for this class
            (bulletChangeX, bulletChangeY) = (((maxAngle - angle) / maxAngle) * (bulletSpeed * power), (angle / maxAngle) * (bulletSpeed * power))          # Ccalculates the changes in x and y
            bulletChangeY -= vert                                                                                                                           # Changes the trajectory of the bullet
            self.rect.y -= bulletChangeY                                                                                                                    # Moves the bullet in the y axis
            self.rect.x += bulletChangeX                                                                                                                    # Moves the bullet in the x axis
    
    
    # --------------- TITLE SCREEN ---------------
    # Creating the main menu
    menu = True
    while menu:                                                     # Starts the loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:                                   # Checks if pygame has been closed
                exit()                                                          # Exits python
        screen.fill(white)                                              # Fills the screen white
        screen.blit(titleText, [0, 0])                                  # Writes the title text
    
        button(startButton, width / 2, (height / 3) * 2, "play")      # Calls the button function for the start button
        button(exitButton, width / 2, ((height / 3) * 2) + 70, "exit")    # Calls the button function for the exit button
    
        # Updating the display
        pygame.display.update()                                         # Updates the display
        clock.tick(fps)
    # --------------- MAIN LOOP ---------------
    
    
    # Running the program
    def playGame():
        #code. This function has no return value.
    
    
    # --------------- EXIT ---------------
    
    
    # Exits PyGame and Python
    def exit():
        pygame.quit()
        quit()
    

    希望这里的错误显而易见,并且我没有删除导致问题的任何关键代码(我删除了启动变量声明和功能代码的内容)如果人们需要它我可以提供完整的代码

1 个答案:

答案 0 :(得分:0)

是的,非常明显 - 就像你说的那样:

鳕鱼e试图在定义之前调用该函数 - 绘制菜单屏幕并绘制按钮的while menu代码放在playGame函数之前 - 此时该名称未声明。

虽然Python确实在模块顶层运行代码,但最好的做法是在顶层只留下一些常量和变量声明,并将类似块while menu: ...的代码放在函数中。 (可以称之为main - 但其名称没有最高语言要求)

然后,在文件的最底部,通过调用来调用该函数 - 这次是正确的,在模块体上 -

所以 - 沿途:

def main():
    # Creating the main menu
    menu = True
    while menu:                                                     # Starts the loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:                                   # Checks if pygame has been closed
                exit()                                                          # Exits python
        screen.fill(white)                                              # Fills the screen white
        screen.blit(titleText, [0, 0])                                  # Writes the title text

        button(startButton, width / 2, (height / 3) * 2, "play")      # Calls the button function for the start button
        button(exitButton, width / 2, ((height / 3) * 2) + 70, "exit")    # Calls the button function for the exit button

        # Updating the display
        pygame.display.update()                                         # Updates the display
        clock.tick(fps)

在最底部,单个main()电话会使该特定错误消失。