import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH, HEIGHT = 640, 480
BLOCK_SIZE = 32
FPS = 60
# Set up some colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Create the game screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Create the red block
red_block = pygame.Rect(WIDTH // 2, HEIGHT // 2, BLOCK_SIZE, BLOCK_SIZE)
# Create the blue block
blue_block = pygame.Rect(WIDTH // 2 - BLOCK_SIZE, HEIGHT // 2, BLOCK_SIZE, BLOCK_SIZE)
# Set up the clock
clock = pygame.time.Clock()
# Game loop
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Update the red block position
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
red_block.y -= 5
if keys[pygame.K_DOWN]:
red_block.y += 5
if keys[pygame.K_LEFT]:
red_block.x -= 5
if keys[pygame.K_RIGHT]:
red_block.x += 5
# Check for collisions
if red_block.colliderect(blue_block):
# If there is a collision, destroy the red block
red_block = pygame.Rect(WIDTH // 2, HEIGHT // 2, BLOCK_SIZE, BLOCK_SIZE)
# Draw everything
screen.fill(WHITE)
pygame.draw.rect(screen, RED, red_block)
pygame.draw.rect(screen, BLUE, blue_block)
# Flip the display
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)
0 Comments