Improve this code and add 2 player one for wasd and one for arrow keys
Here is an improved code with two players, one for WASD and one for arrow keys:
import pygame
# initialize pygame
pygame.init()
# set up the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Two Player Game")
# set up the clock
clock = pygame.time.Clock()
# set up the players
player1_x = screen_width // 4
player1_y = screen_height // 2
player1_speed = 5
player1_color = (255, 0, 0)
player2_x = 3 * screen_width // 4
player2_y = screen_height // 2
player2_speed = 5
player2_color = (0, 0, 255)
# set up the game loop
running = True
while running:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# handle player 1 movement
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player1_x -= player1_speed
elif keys[pygame.K_d]:
player1_x += player1_speed
elif keys[pygame.K_w]:
player1_y -= player1_speed
elif keys[pygame.K_s]:
player1_y += player1_speed
# handle player 2 movement
if keys[pygame.K_LEFT]:
player2_x -= player2_speed
elif keys[pygame.K_RIGHT]:
player2_x += player2_speed
elif keys[pygame.K_UP]:
player2_y -= player2_speed
elif keys[pygame.K_DOWN]:
player2_y += player2_speed
# keep players within the screen bounds
player1_x = max(0, min(player1_x, screen_width))
player1_y = max(0, min(player1_y, screen_height))
player2_x = max(0, min(player2_x, screen_width))
player2_y = max(0, min(player2_y, screen_height))
# draw the players
screen.fill((255, 255, 255))
pygame.draw.circle(screen, player1_color, (player1_x, player1_y), 20)
pygame.draw.circle(screen, player2_color, (player2_x, player2_y), 20)
pygame.display.flip()
# set the frame rate
clock.tick(60)
# quit pygame
pygame.quit()
In this code, we added a second set of movement controls for player 2 using the arrow keys. We also adjusted the positions and speeds of the players to make the game more balanced. Additionally, we added code to ensure that the players stay within the screen bounds
原文地址: https://www.cveoy.top/t/topic/dTTE 著作权归作者所有。请勿转载和采集!