我正在使用 Pygame 在 Python 中工作,我想知道如何根据用光标键移动某些对象来绘制像素。
所以,我想做的是画一个“运动轨迹”,例如当玩家向右移动他的对象时,程序必须在这个对象后面从运动开始到运动结束绘制像素。
您可以跟踪对象的过去位置。
在下面的代码中,pygame.Rect 正在使用箭头键移动。
你会感兴趣的部分在Player
课堂上,即
lasts
(列表)update_list()
(功能)
fade
.draw()
(功能)
注意:这不是最有效的代码。
编码
import pygame
bg = (255, 255, 255)
def add_colors(color1, color2):
retval = []
for i in range(3):
c1 = color1[i]
c2 = color2[i]
c = c1+c2
if c > 255: # just basic handling
c -= 255
retval.append(round(int(c)))
return tuple(retval)
def calc_colors(color, fade):
retval = []
# calculating the color change rate
diff_color = []
for i in range(3):
diff = bg[i] - color[i]
c_diff = diff/float(fade)
diff_color.append(c_diff)
diff_color = tuple(diff_color)
# get the fading colors
lastcolor = bg
for i in range(fade):
new_color = add_colors(lastcolor, diff_color)
retval.append(new_color)
lastcolor = new_color
return retval[::-1]
class Player:
def __init__(self, color, fade, pygame_Rect_args):
"""Give arguments as given to pygame.Rect"""
self.rect = pygame.Rect(*pygame_Rect_args)
self.size = self.rect.size
self.vx = 0.0
self.vy = 0.0
self.lasts = []
self.maincolor = color
self.colors = calc_colors(color,fade)
self.fade = fade
def draw(self):
for i in range(len(self.lasts)):
pos = self.lasts[i]
c_color = self.colors[i]
pygame.draw.rect(screen, c_color, pygame.Rect(pos, self.size))
pygame.draw.rect(screen, self.maincolor, self.rect)
def update_list(self):
self.lasts.append(self.rect.topleft)
if len(self.lasts) > self.fade:
self.lasts.remove(self.lasts[0])
def update(self):
self.rect.x += int(round(self.vx))
self.rect.y += int(round(self.vy))
def handle_keys(self):
key = pygame.key.get_pressed()
if key[pygame.K_UP]: self.vy -= 0.1
if key[pygame.K_DOWN]: self.vy += 0.1
if key[pygame.K_LEFT]: self.vx -= 0.1
if key[pygame.K_RIGHT]: self.vx += 0.1
player = Player((255,255,0), 10, (10,10,10,10))
pygame.init()
screen = pygame.display.set_mode((640,480))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
break
if not running:
break
player.handle_keys()
player.update_list()
player.update()
screen.fill(bg)
player.draw()
pygame.display.flip()
clock.tick(40)
您可能还想完成本教程(不是全部,而只是最后一部分 (#9))