1import pygame
2import random
3
4# Initialize Pygame
5pygame.init()
6
7# Set up the game window
8screen_width = 800
9screen_height = 600
10screen = pygame.display.set_mode((screen_width, screen_height))
11
12# Set up the title of the game
13pygame.display.set_caption("Football Frenzy")
14
15# Define some colors
16WHITE = (255, 255, 255)
17BLACK = (0, 0, 0)
18
19# Define the player class
20class Player(pygame.sprite.Sprite):
21 def __init__(self, name, position, speed):
22 super().__init__()
23 self.name = name
24 self.position = position
25 self.speed = speed
26 self.image = pygame.Surface((20, 20))
27 self.image.fill(WHITE)
28 self.rect = self.image.get_rect()
29 self.rect.center = position
30
31 def move(self, direction):
32 if direction == "up":
33 self.rect.y -= self.speed
34 elif direction == "down":
35 self.rect.y += self.speed
36 elif direction == "left":
37 self.rect.x -= self.speed
38 elif direction == "right":
39 self.rect.x += self.speed
40
41# Define the ball class
42class Ball(pygame.sprite.Sprite):
43 def __init__(self):
44 super().__init__()
45 self.image = pygame.Surface((10, 10))
46 self.image.fill(WHITE)
47 self.rect = self.image.get_rect()
48 self.rect.center = (screen_width / 2, screen_height / 2)
49 self.speed_x = random.choice([-5, 5])
50 self.speed_y = random.choice([-5, 5])
51
52 def move(self):
53 self.rect.x += self.speed_x
54 self.rect.y += self.speed_y
55
56 if self.rect.left < 0 or self.rect.right > screen_width:
57 self.speed_x *= -1
58 if self.rect.top < 0 or self.rect.bottom > screen_height:
59 self.speed_y *= -1
60
61# Create the players
62players = []
63for i in range(11):
64 name = f"Player {i+1}"
65 position = (random.randint(0, screen_width), random.randint(0, screen_height))
66 speed = 5
67 player = Player(name, position, speed)
68 players.append(player)
69
70# Create the ball
71ball = Ball()
72
73# Create the game loop
74while True:
75 # Handle events
76 for event in pygame.event.get():
77 if event.type == pygame.QUIT:
78 pygame.quit()
79 sys.exit()
80
81 # Move the players
82 for player in players:
83 keys = pygame.key.get_pressed()
84 if keys[pygame.K_UP]:
85 player.move("up")
86 if keys[pygame.K_DOWN]:
87 player.move("down")
88 if keys[pygame.K_LEFT]:
89 player.move("left")
90 if keys[pygame.K_RIGHT]:
91 player.move("right")
92
93 # Move the ball
94 ball.move()
95
96 # Draw everything
97 screen.fill(BLACK)
98 for player in players:
99 screen.blit(player.image, player.rect)
100 screen.blit(ball.image, ball.rect)
101
102 # Update the screen
103 pygame.display.flip()
104 pygame.time.Clock().tick(60)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter