我编写了一个代码,旨在按右箭头键移动马,但是当我按时,它不会移动。我似乎无法注意到问题所在。我在print(a.locx)中键入了def char()来查看a.locx是否在增加,但是当我按下向右箭头键class Horse()在增加然后立即减小时,在def location()的方法self.locx中也是如此。

import pygame
from pygame import locals
def main():
    global window,width,height
    pygame.init()
    width ,height = 500,500
    window = pygame.display.set_mode((width,height))

    while True:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if pygame.event == pygame.QUIT:
                pygame.quit()
        char()

        pygame.display.update()


def char():
    a = Horse()
    window.blit(a.horse1,(a.locx,a.locy))
    print(a.locx)
    a.location()

class Horse():
    def __init__(self):
        self.horse1 = pygame.image.load("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk3.png")

        self.horse2 = []

        for horse in range(0,8):
            self.horse2.append(pygame.image.load(("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk{}.png").format(horse+1)))

        self.horse3 = []

        for horse in self.horse2:
            self.horse3.append(pygame.transform.flip(horse,True,False))

        self.locx = 0
        self.locy = width - self.horse1.get_size()[1]

    def location(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_RIGHT]:
            print(self.locx,"1")
            self.locx += 200
            print(self.locx,"2")

main()

最佳答案

问题是您在每个帧中创建了一个新的Horse对象,因此该匹马在其初始位置连续“开始”。


  

def char():
   a = Horse() # <--- creates new Hors object with "self.locx = 0"
   # [...]



在全局名称空间中创建一个Horse并使用此对象:

def main():
    global window, width, height, a

    pygame.init()
    width, height = 500,500
    window = pygame.display.set_mode((width,height))
    a = Horse()

    while True:
        window.fill((0,0,0))

        for event in pygame.event.get():
            if pygame.event == pygame.QUIT:
                pygame.quit()
        char()

        pygame.display.update()

def char():
    window.blit(a.horse1,(a.locx,a.locy))
    print(a.locx)
    a.location()

关于python - PyGame:字符不动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57843778/

10-12 22:03