This question already has answers here:
How do I pass a variable by reference?
                                
                                    (26个答案)
                                
                        
                                3年前关闭。
            
                    
我还是python的新手,并且已经开始使用pygame。我正在制作无尽的亚军游戏,但是我的运行周期遇到了问题。这是我的代码:

import pygame
import sys
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
clock2 = pygame.time.get_ticks()
screen = pygame.display.set_mode((640, 575))
bgx = 0
bgx2 = -800
scroll = 10
pose = 1
background = pygame.image.load("images/background2.png").convert_alpha();
player = pygame.image.load("images/character1.png").convert_alpha();
screen.blit(background, (0, 0))
def draw_screen(x):
screen.blit(background, (x, 0))
def draw_screen2(x2):
screen.blit(background, (x2, 0))
def draw_player(pose):
    if pose == 1:
        player = pygame.image.load("images/character1.png").convert_alpha();
        screen.blit(player, (0, 0))
    elif pose == 2:
        player = pygame.image.load("images/character2.png").convert_alpha();
        screen.blit(player, (0, 0))
    elif pose == 3:
        player = pygame.image.load("images/character3.png").convert_alpha();
        screen.blit(player, (0, 0))
    elif pose == 4:
        player = pygame.image.load("images/character2.png").convert_alpha();
        screen.blit(player, (0, 0))
def set_poses(pose):
    if pose == 1:
        pose = 2
    if pose == 2:
        pose = 3
    if pose == 3:
        pose = 4
    if pose == 4:
        pose = 1

while True: #Loop
    clock2 = pygame.time.get_ticks()
    #Quitting Function
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
            quit()
    clock.tick(50)
    #Screen Scrolling
    if bgx != 800:
        bgx += scroll
    else:
        bgx = 0
    if bgx2 != 0:
        bgx2 += scroll
    else:
        bgx2 = -800
    #Drawing Items
    draw_screen2(bgx2)
    draw_screen(bgx)
    draw_player(pose)
    if clock2%6 == 0:
        set_poses(pose)
    pygame.display.update()


因此屏幕在滚动,并且出现了我的角色,但他在它运行的部分停留在第一个位置(我想是帧)。set_poses(pose)我试图让它在设置姿势之前也打印一些东西,但是确实如此。它没有设定姿势。我尝试用它打印姿势,结果表明姿势没有改变。所以,是的,我找到了问题,但我终生无法找到解决方案。

最佳答案

而不是尝试通过引用传递-这是您在做什么,请尝试如下操作:

def set_pose(pose):
    if pose >= 4:
        return 1
    else:
        return pose + 1


然后,当您尝试在其他地方更新pose变量时:

pose = set_pose(pose)

您是否同意可以随意调用函数的参数?例如,set_pose可能看起来像这样,并做完全相同的事情:

def set_pose(foo):
    if foo >= 4:
        return 1
    else:
        return foo + 1


换句话说,仅仅因为在函数内部被称为pose并不意味着它将在函数外部引用姿势。

关于python - 基本运行周期不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38232059/

10-12 21:44