【问题标题】:pygame - moving graphic (Actor)pygame - 移动图形(演员)
【发布时间】:2020-03-24 08:56:47
【问题描述】:

我只是在用 Pygame 做一个小游戏。对象应该在屏幕上移动。当我尝试这样做时,总是拖着一条“轨道”(见图)。如何在不绘制运动“路线”的情况下移动苹果?

from random import randint
import pygame

WIDTH   = 800
HEIGHT  = 800

apple = Actor("apple")
apple.pos = randint(0, 800), randint(800, 1600)

score = 0

def draw():
    apple.draw()
    screen.draw.text("Punkte: " + str(score), (700, 5), color = "white")

def update():
    if apple.y > 0:
        apple.y = apple.y - 4
    else: 
        apple.x = randint(0, 800)
        apple.y = randint(800, 1600)

【问题讨论】:

标签: python graphics pygame pgzero


【解决方案1】:

这不是纯粹的pygame,它是Pygame Zero。你必须调用screen.clear()来清除每一帧的显示:

def draw():
    screen.clear()
    apple.draw()
    screen.draw.text("Punkte: " + str(score), (700, 5), color = "white")

【讨论】:

    【解决方案2】:

    每次更新时,使用 pygame.display.flip(),这会重置屏幕。 我还会考虑使用 while 循环,它会处理用户输入,绘制精灵,然后擦除屏幕,然后在游戏结束时结束循环。

    【讨论】:

    • 从他发送的代码中,它只是说import pygame,我已经使用了前面所说的命令
    【解决方案3】:

    实际情况是,苹果实际上并没有被向下移动,而是在新坐标处重新绘制了很多次。看来您正在使用一个内置类,所以不知道它有什么方法,因为我通常创建自己的类。如果您在主循环之前创建了您的苹果对象,可以解决这个问题。然后在主循环中调用一个方法将苹果移动多少像素,然后使用screen.blit() 更新位置

    例如,您可以为您的苹果创建一个类,该类将采用 4 个参数:哪个 pygame 窗口、x 坐标、y 坐标和苹果图像的路径。

    class Apple():
        def __init__(self, place, x, y, path,):
            self.place = place
            self.x = x
            self.y = y
            self.path = path 
    
    
        def load(self):
            screen.blit(self.path, (self.x, self.y))
    
    
        def move(self):
             if self.y > 0:
                self.y = self.y - 4
            else: 
                self.x = randint(0, 800)
                self.y = randint(800, 1600)
    

    然后您将创建苹果对象:

    path = "path_to_the_image_of_the_apple"
    apple_x = random.randint(0, 800)
    apple_y = random.randint(0, 800)
    
    apple = Apple(screen, apple_x, apple_y, path)
    
    

    然后在主循环中调用方法先移动苹果apple.move()然后更新位置apple.load()

    主循环:

    #main game loop
    while True:
        #clear display
        screen.fill(0)
    
        #move call the function to move the apple
        apple.move()
    
    
        #updating the player
        apple.load()
    
        #update display
        pygame.display.flip() 
    

    请注意,screen.blit(self.path, (self.x, self.y)) screen 只是我代码中的变量。用你的任何东西替换它。

    【讨论】:

      猜你喜欢
      • 2014-12-02
      • 2020-07-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多