我是pygame app开发的新手。在我的游戏中,矩形对象以方形方式在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)
这样的新玩家对象时,第二张图像会形成,但它不会旋转。
答案 0 :(得分: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)