-1

I am new to pygame app development. In my game a rectangular object rotates in pygame window in a squarely manner. But what I want is to add one more rectangular object and do the same thing. My code

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)

When I added a new player object like pygame.draw.rect(screen, pygame.color.Color('Grey'), player2) the second image is formed but it doesnt rotate.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137

1 Answers1

0

I think you forgot to update the second player's position (at least that's what I think)

The following code is just a quick update of your code, normally you would use lists if you wanted to hold more than two players, but this should work just fine

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)
wastl
  • 2,643
  • 14
  • 27