2016-10-28 4 views
0

사촌의 파이 게임 코드에 문제가 있는지 묻습니다. 저는 파이썬에서 다른 언어를 많이 사용하지 않고 인터넷 검색이나 디버깅으로 문제를 찾을 수 없었습니다. 기본적으로 그는 을 얻고 있습니다. "playGame은 정의되지 않았습니다." 오류, playGame이 기능입니다. 이것에 대해 다른 질문 때문에 일반적으로 다음과 같습니다이 함수가 호출되는 다른 범위 내에서 선언 파이썬 파이 게임 기능이 정의되지 않았습니다.

  • 를 선언하기 전에

    1. 함수가 호출

    이 중 어느 것도 것 같다 문제는 파이썬에 정통한 누군가가 그것을 발견 할 수 있기를 바라고 있습니다. 아래에 자신의 코드를 복사 한 결과, 단순화하기 위해 제거한 질문과 관련이없는 내용이 많이 있습니다.

    playGame 함수가 작동하지 않고 def button(msg, x, y, action = None): 아래의 버튼 클릭으로 호출됩니다. 흥미롭게도 exit 함수는 잘 작동하고 있으며 정확히 내가 말할 수있는 한 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() 
    

    희망 실수 누군가에게 여기에 분명 내가 문제를 일으키는 어떤 키 코드를 제거하지 않은 나는 사람들의 경우 전체 코드를 제공 할 수 있습니다 (I 변수 선언과 함수 코드의 내용을 시작 제거) 필요해.

  • +1

    버튼을 클릭 할 때 호출됩니다. def 버튼 (msg, x, y, 동작 = 없음) : 다른 모든 것보다 위에 정의한 게임은 이미 시도했지만 작동하지 않았습니다. – Sparks

    +0

    그래, 방금 찾았 어. 그래서'button '은 어디에 사용됩니까? 콜백으로 사용되어야하는 것처럼 보이지만 대신 전화를 겁니다. 코드의 어딘가에'command = button '대신에'command = button()'이 있습니다. –

    +0

    'exit()'는 파이썬에서 내장 함수이므로,'exit'가 발견된다는 사실은 아무것도 말하지 않습니다. 그것은 아마도 내장 된 것을 사용했을 것입니다. –

    답변

    0

    예, 분명 themistake - 당신이 그것을 넣어 : - 메뉴 화면을 그리고 버튼을 그리는 while menu 코드가 앞에 위치

    대구 전자가 정의되기 전에 함수를 호출하려고 playGame 함수 - 그 시점에서 이름이 선언되지 않습니다.

    파이썬은 모듈 최상위 레벨에서 코드를 실행하지만 가장 좋은 방법은 최상위 레벨에 상수 및 변수 선언 만 남기고 블록 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() 전화를 걸.

    관련 문제