微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 赋值前调用的变量

如何解决Python 赋值前调用的变量

我有一个问题,我需要在多个函数调用一些变量,但无法在 game_loop() 函数中声明它们。变量在 game_loop 函数之外被调用,但变量也被调用到其他函数中。如何让变量在 game_loop 函数和所有其他调用它们的函数调用

请看下面的代码

            import math
            import random
            
            import pygame
            from pygame import mixer
            
            # Intialize the pygame
            pygame.init()
            
            # next setup the display
            display_width = 800
            display_height = 600
            screen = pygame.display.set_mode((800,600))
            
            # Background
            background = pygame.image.load('waterbackground.jpg')
            
            # game clock to time frames per second 
            clock = pygame.time.Clock()
            
            # Sound
            mixer.music.load("ocean.wav")
            mixer.music.play(-1)
            
            # setup colors needed in the game
            black = (0,0)
            white = (255,255,255)
            red = (200,0)
            bright_red = (255,0)
            block_color = (53,115,255)
            green = (0,200,0)
            bright_green = (0,0)
            
            # Caption and Icon
            pygame.display.set_caption("Pirate War")
            icon = pygame.image.load('pirateship.png')
            pygame.display.set_icon(icon)
            
            # cannon
            cannonImg = pygame.image.load('cannonball.png')
            cannonX = 0
            cannonY = 480
            cannonX_change = 0
            cannonY_change = 10
            cannon_state = "ready"
                
            
            # Player
            playerImg = pygame.image.load('cannon.png')
            playerX = 370
            playerY = 480
            playerX_change = 0
            
            # score
            score_value = 0
            
            
            # ship
            shipImg = []
            shipX = []
            shipY = []
            shipX_change = []
            shipY_change = []
            num_of_ships = 6
            
            for i in range(num_of_ships):
                shipImg.append(pygame.image.load('pirateship.png'))
                shipX.append(random.randint(0,736))
                shipY.append(random.randint(50,150))
                shipX_change.append(4)
                shipY_change.append(40)
            
            
            font = pygame.font.Font('freesansbold.ttf',32)
            
            textx = 10
            testY = 10
            
            # Game Over
            over_font = pygame.font.Font('freesansbold.ttf',64)
            
            # text object function called by message display function
            def text_objects(text,font):
                textSurface = font.render(text,True,black)
                return textSurface,textSurface.get_rect()
            
            
            def show_score(x,y):
                score = font.render("score : " + str(score_value),(255,255))
                screen.blit(score,(x,y))
            
            
            def game_over_text():
                over_text = over_font.render("GAME OVER",255))
                screen.blit(over_text,(200,250))
            
            
            def player(x,y):
                screen.blit(playerImg,y))
            
            
            def ship(x,y,i):
                screen.blit(shipImg[i],y))
            
            
            def fire_cannon(x,y):
                global cannon_state
                cannon_state = "fire"
                screen.blit(cannonImg,(x + 16,y + 10))
            
            
            def isCollision(shipX,shipY,cannonX,cannonY):
                distance = math.sqrt(math.pow(shipX - cannonX,2) + (math.pow(shipY - cannonY,2)))
                if distance < 27:
                    return True
                else:
                    return False
            
            
            def button(msg,x,w,h,ic,ac,action=None): 
                mouse = pygame.mouse.get_pos() # returns a list of [x,y]
                click = pygame.mouse.get_pressed()
                
                if x+w > mouse[0] > x and y+h > mouse[1] > y: #check is mouse over button
                    # redraw the rectange with active color when mouSEOver
                    pygame.draw.rect(screen,h))
                    #check for a click
                    if click[0] == 1 and action!=None:
                        action()
                else:
                    pygame.draw.rect(screen,h))
                # Now display text on top of button that was just redrawn
                smallText = pygame.font.Font('freesansbold.ttf',20)
                TextSurf,TextRect = text_objects(msg,smallText)
                TextRect.center = ((x+(w/2)),(y+(h/2)))
                screen.blit(TextSurf,TextRect)
                
                
            def quitgame():
                pygame.quit()
                quit() 
                
            # start screen code
            def game_intro():
                intro = True
                while intro:
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            quit()
                    screen.fill((0,0))
                    # Background Image
                    screen.blit(background,(0,0))
                    largeText = pygame.font.Font('freesansbold.ttf',115)
                    TextSurf,TextRect = text_objects("Pirate War",largeText)
                    TextRect.center = ((display_width/2),(display_height/2))
                    screen.blit(TextSurf,TextRect)
                    #add buttons to start screen
                    button("Go!",150,450,100,50,green,bright_green,game_loop)
                    button("Quit",550,red,bright_red,quitgame)
                    
                    pygame.display.update()
                    clock.tick(15)
                
            def game_loop():
             
                # Game Loop
                running = True
                while running:
                
                    # RGB = Red,Green,Blue
                    screen.fill((0,0))
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            running = False
                
                        # if keystroke is pressed check whether its right or left
                        if event.type == pygame.KEYDOWN:
                            if event.key == pygame.K_LEFT:
                                playerX_change = -5
                            if event.key == pygame.K_RIGHT:
                                playerX_change = 5
                            if event.key == pygame.K_SPACE:
                                if cannon_state == "ready":
                                    cannonSound = mixer.sound("cannon_x.wav")
                                    cannonSound.play()
                                    # Get the current x cordinate of the spaceship
                                    cannonX = playerX
                                    fire_cannon(cannonX,cannonY)
                
                        if event.type == pygame.KEYUP:
                            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                                playerX_change = 0
                
                    # 5 = 5 + -0.1 -> 5 = 5 - 0.1
                    # 5 = 5 + 0.1
                
                    playerX += playerX_change
                    if playerX <= 0:
                        playerX = 0
                    elif playerX >= 736:
                        playerX = 736
                
                    # ship Movement
                    for i in range(num_of_ships):
                
                        # Game Over
                        if shipY[i] > 440:
                            for j in range(num_of_ships):
                                shipY[j] = 2000
                            game_over_text()
                            break
                
                        shipX[i] += shipX_change[i]
                        if shipX[i] <= 0:
                            shipX_change[i] = 1               #######SHIP MOVEMENT
                            shipY[i] += shipY_change[i]
                        elif shipX[i] >= 736:
                            shipX_change[i] = -1              ######SHIP MOVEMENT
                            shipY[i] += shipY_change[i]
                
                        # Collision
                        collision = isCollision(shipX[i],shipY[i],cannonY)
                        if collision:
                            explosionSound = mixer.sound("explosion.wav")
                            explosionSound.play()
                            cannonY = 480
                            cannon_state = "ready"
                            score_value += 1
                            shipX[i] = random.randint(0,736)
                            shipY[i] = random.randint(50,150)
                
                        ship(shipX[i],i)
                
                    # cannon Movement
                    if cannonY <= 0:
                        cannonY = 480
                        cannon_state = "ready"
                
                    if cannon_state == "fire":
                        fire_cannon(cannonX,cannonY)
                        cannonY -= cannonY_change
                
                    player(playerX,playerY)
                    show_score(textx,testY)
                    pygame.display.update()
            
            game_intro()

解决方法

如果您需要的是能够在函数中使用全局变量,那么您只需要关键字 global。

x = 0
def inc() :
  global x
  x += 1
inc()
print(x)
,

您指的是在函数外声明的变量。您的函数不知道它们存在,因此它们通过错误。

要在函数中使用这些变量,您需要将它们声明为全局变量。

这是你需要做的

def game_loop():

    global playerX
    global playerX_change
    global cannonX
    global cannonY
    global cannon_state

您也可以对其他功能执行此操作

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。