Python pygame-移动图形(演员)
我只是在和Pygame做个小游戏。对象应该在屏幕上移动。当我尝试这样做时,一条“轨迹”总是被拖走(见图)。我怎样才能移动苹果而不画出移动的“路线”Python pygame-移动图形(演员),python,graphics,pygame,pgzero,Python,Graphics,Pygame,Pgzero,我只是在和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.
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)
这不是纯粹的pygame,它是。您必须调用以清除每个帧中的显示:
def draw():
screen.clear()
apple.draw()
screen.draw.text(“Punkte:+str(score),(700,5),color=“white”)
每次更新时,请使用pygame.display.flip(),这将重置屏幕。
我也会考虑使用一个while循环,它将处理用户输入,绘制精灵,然后擦拭屏幕,当游戏结束时,结束循环。
发生的是,苹果在新的坐标上实际上被多次重画而不是被移动。看起来您使用的是一个内置类,所以我知道它有什么方法,因为我通常创建自己的类。如果在主循环之前创建了apple对象,那么可以解决这个问题。然后在主循环中调用一个方法,将苹果移动多少像素,然后使用
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)
然后创建apple对象:
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))中
屏幕
只是我代码中的变量。把它换成你的 这回答了你的问题吗@UliSotschok不,这并没有回答问题,因为这不仅仅是他发送的代码,它只是说import pygame,我在前面提到的命令中使用了它