我正在为我的cs类创建一个游戏,模型是Tron。基本上,我让我的两个球员一直在前进,他们可以左转或右转(以90°角度),同时在他们后面创建线条。我想创建一个函数,在给定玩家的最后位置时绘制这些线。然而,我无法弄清楚当玩家转动时如何创建新线,同时保持旧线的正常运转(我会稍微了解这意味着什么)。此外,由于我每次都会从同一个变量中调用这个“绘制线”函数,我是否可以通过调用一个变量来检测播放器与任何给定行之间的冲突,即使这些行在技术上都不同?这是一本词典的优化情况吗?
到目前为止,我和我的伙伴已经尝试延长一个矩形,创建一个列表(虽然我在这个领域没有太多经验,所以也许我只是把它搞砸了)并且在字面上创造了多个变量... < / p>
My code(如果您决定查看代码并玩游戏,请记住,说明屏幕中的下一个按钮因某些原因被破坏,需要点击垃圾邮件)。
答案 0 :(得分:0)
您可以执行以下操作:对行使用pygame.Rect
s,因为它们具有有用的碰撞检测方法。当玩家移动时,你只需增加当前矩形的大小,当方向改变时,你可以将这个矩形附加到一个rects列表并创建一个新的。对于碰撞检测,您将遍历rects
列表并使用播放器rect .colliderect
方法。
这是一个完整的解决方案:
import pygame as pg
from pygame.math import Vector2
def main():
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
background_color = (30, 30, 30)
blue = pg.Color('dodgerblue1')
lightblue = pg.Color('cadetblue3')
sienna = pg.Color('sienna1')
player_color = lightblue
player = pg.Rect(400, 300, 10, 10)
vel = Vector2(3, 0)
current_rect = pg.Rect(400, 300, 0, 10)
rects = [current_rect]
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
vel.x = 3
vel.y = 0
# A new rect with 0 width.
current_rect = pg.Rect(player.topleft, (0, 10))
elif event.key == pg.K_a:
vel.x = -3
vel.y = 0
current_rect = pg.Rect(player.topright, (0, 10))
elif event.key == pg.K_w:
vel.y = -3
vel.x = 0
current_rect = pg.Rect(player.bottomleft, (10, 0))
elif event.key == pg.K_s:
vel.y = 3
vel.x = 0
current_rect = pg.Rect(player.topleft, (10, 0))
if event.key in (pg.K_d, pg.K_a, pg.K_w, pg.K_s):
# Append the new current rect.
rects.append(current_rect)
# Update the position of the player.
player[0] += vel.x
player[1] += vel.y
# Need to adjust the rect position if we're moving up or left.
if vel.x < 0:
current_rect.x += vel.x
elif vel.y < 0:
current_rect.y += vel.y
# Increase the size of the current rect.
# abs is needed to avoid negative width & height.
current_rect.w += abs(vel.x)
current_rect.h += abs(vel.y)
player_color = lightblue
# Collision detection with the rects.
for line_rect in rects:
if player.colliderect(line_rect):
player_color = sienna
break
screen.fill(background_color)
# Draw all rects in the list.
for line_rect in rects:
pg.draw.rect(screen, blue, line_rect)
# Draw the player rect.
pg.draw.rect(screen, player_color, player)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()