how to build a simple game in Python

# Importing Required Libraries
import pygame
import random

# Initializing Pygame
pygame.init()

# Setting up the game window
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame Game")

# Defining game variables
player_x = width // 2
player_y = height - 50
player_speed = 5

enemy_x = random.randint(0, width)
enemy_y = -50
enemy_speed = 3

score = 0
font = pygame.font.Font(None, 36)

# Game loop
running = True
while running:
    # Handling events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Moving the player with arrow keys
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < width:
        player_x += player_speed

    # Moving the enemy down the screen
    enemy_y += enemy_speed
    if enemy_y > height:
        enemy_x = random.randint(0, width)
        enemy_y = -50
        score += 1

    # Checking for collision between player and enemy
    if abs(player_x - enemy_x) < 50 and abs(player_y - enemy_y) < 50:
        running = False

    # Drawing the game objects
    screen.fill((255, 255, 255))
    pygame.draw.rect(screen, (255, 0, 0), (player_x, player_y, 50, 50))
    pygame.draw.rect(screen, (0, 0, 255), (enemy_x, enemy_y, 50, 50))

    # Updating the score display

In this example, we first import the necessary libraries – pygame and random. We then initialize Pygame and set up the game window. We define game variables, such as the player and enemy positions, speed, and score. We then enter the game loop and handle events such as closing the window and moving the player with arrow keys. We move the enemy down the screen, check for collision between the player and enemy, and draw the game objects on the screen. We update the score display, update the display, and limit the frame rate. Finally, we quit Pygame when the game is over.

Please note that this is a simple example, and games can be much more complex and require more advanced game engines and libraries. Additionally, game development may require additional knowledge in areas such as game design, art, and sound engineering.

Leave a Reply