-1

我是 pygame 应用程序开发的新手。在我的游戏中,一个矩形对象在 pygame 窗口中以正向方式旋转。但我想要的是再添加一个矩形对象并做同样的事情。我的代码

import pygame
from itertools import cycle
pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)

dirs = cycle([up, right, down, left])

dir = next(dirs)

while True:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        raise

# move player
player.move_ip(dir)
# if it's outside the screen
if not s_r.contains(player):
    # put it back inside
    player.clamp_ip(s_r)
    # and switch to next direction
    dir = next(dirs)

screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

pygame.display.flip()
timer.tick(25)

当我添加一个新的播放器对象pygame.draw.rect(screen, pygame.color.Color('Grey'), player2)时,第二个图像已形成但它不旋转。

4

1 回答 1

0

我想你忘了更新第二个玩家的位置(至少我是这么认为的)

以下代码只是您的代码的快速更新,通常如果您想容纳两个以上的玩家,您会使用列表,但这应该可以正常工作

import pygame
from itertools import cycle
pygame.init() 
screen = pygame.display.set_mode((300, 300)) 
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
player2 = pygame.Rect((200, 100, 50, 50))
timer = pygame.time.Clock()
speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)

dirs1 = cycle([up, right, down, left])
dirs2 = cycle([up, right, down, left])

dir1 = next(dirs1)
dir2 = next(dirs2)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    # move player    
    player.move_ip(dir1)
    player2.move_ip(dir2)
    # if it's outside the screen
    if not s_r.contains(player):
    # put it back inside
        player.clamp_ip(s_r)
        # and switch to next direction
        dir1 = next(dirs1)

    if not s_r.contains(player2):
        # put it back inside
        player2.clamp_ip(s_r)
        # and switch to next direction
        dir2 = next(dirs2)

    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player2)
    pygame.display.flip()
    timer.tick(25)
于 2014-07-01T16:52:29.557 回答