Untitled
unknown
plain_text
a year ago
1.7 kB
16
Indexable
*Code*
```
import pygame
import random
Window dimensions
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
Block dimensions
BLOCK_WIDTH = 20
BLOCK_HEIGHT = 20
Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
Player properties
PLAYER_WIDTH = 20
PLAYER_HEIGHT = 20
PLAYER_SPEED = 5
class Block(pygame.Rect):
def __init__(self, x, y):
super().__init__(x, y, BLOCK_WIDTH, BLOCK_HEIGHT)
class Player(pygame.Rect):
def __init__(self):
super().__init__(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PLAYER_WIDTH, PLAYER_HEIGHT)
def move(self, dx, dy):
self.x += dx
self.y += dy
def draw_window(window, player, blocks):
window.fill(BLACK)
for block in blocks:
pygame.draw.rect(window, GREEN, block)
pygame.draw.rect(window, WHITE, player)
pygame.display.update()
def main():
pygame.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
clock = pygame.time.Clock()
player = Player()
blocks = [Block(random.randint(0, WINDOW_WIDTH - BLOCK_WIDTH), random.randint(0, WINDOW_HEIGHT - BLOCK_HEIGHT)) for _ in range(10)]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.move(-PLAYER_SPEED, 0)
if keys[pygame.K_RIGHT]:
player.move(PLAYER_SPEED, 0)
if keys[pygame.K_UP]:
player.move(0, -PLAYER_SPEED)
if keys[pygame.K_DOWN]:
player.move(0, PLAYER_SPEED)
draw_window(window, player, blocks)
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main()
```
Editor is loading...
Leave a Comment