我可以使用类或列表来提高代码的效率吗?

2024-04-26 18:45:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pygame用python制作一个2D游戏。我已经做了4个不同的圆圈,它们在屏幕上移动,当它们撞到墙上时循环回到起点。这不仅是为了美观,而且还可以计算分数。我想简化它,我觉得a可以使用列表、类或其他东西

capimg = pygame.image.load('cap.png')
cy = 575
cx1 = 200
cx2 = 400
cx3 = 600
cx4 = 800

从这里开始,它就进入了游戏循环

    cx1 += speed
    cx2 += speed
    cx3 += speed
    cx4 += speed
    if cx1 <= -20:
        score += 1
        print(score)
        cx1 = 800
    if cx2 <= -20:
        score += 1
        print(score)
        cx2 = 800
    if cx3 <= -20:
        score += 1
        print(score)
        cx3 = 800
    if cx4 <= -20:
        score += 1
        print(score)
        cx4 = 800
    screen.blit(capimg, (cx1, cy))
    screen.blit(capimg, (cx2, cy))
    screen.blit(capimg, (cx3, cy))
    screen.blit(capimg, (cx4, cy))

1条回答
网友
1楼 · 发布于 2024-04-26 18:45:36

创建x个Cooridate的列表:

lx = [200 + i*200 for i in range(4)]

更改循环中的坐标:

for i in range(len(lx)):
    lx[i] += speed
    if lx[i] <= -20:
        score += 1
        print(score)
        lx[i] = 800    

将汽车画成一个圈:

for cx in lx:
    screen.blit(capimg, (cx, cy))

相关问题 更多 >