Python library pygame: Create a simple character image and code a basic game

Python library pygame: Create a simple character image and code a basic game


1. Knight Character Creation (Using Pillow)

First, we'll create a knight character image using Pillow. This is a simplified example; you can create more detailed sprites using image editing software.




from PIL import Image, ImageDraw

# Character dimensions
width = 64
height = 64

# Create a new image
img = Image.new('RGBA', (width, height), (0, 0, 0, 0))  # Transparent background
draw = ImageDraw.Draw(img)

# Body
draw.rectangle([(16, 16), (48, 48)], fill=(100, 100, 100))  # Gray body

# Head
draw.ellipse([(24, 8), (36, 24)], fill=(200, 200, 200))  # Light gray head

# Helmet
draw.polygon([(20, 8), (30, 2), (40, 8)], fill=(150, 150, 150))

# Legs
draw.rectangle([(16, 48), (48, 56)], fill=(100, 100, 100))

# Save the image
img.save('knight.png')

@
Knight Character Creation (Using Pillow)


 

This code creates a simple knight sprite and saves it as knight.png.

2. Pygame Game Framework

Now, let's build the game framework using Pygame.




import pygame
import random

# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TILE_SIZE = 32
FPS = 60

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# --- Classes ---

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load('knight.png').convert_alpha()  # Load the knight image
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5
        self.hp = 100
        self.attack = 10

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT]:
            self.rect.x += self.speed
        if keys[pygame.K_UP]:
            self.rect.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.rect.y += self.speed

        # Keep player within screen bounds
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
        if self.rect.top < 0:
            self.rect.top = 0
        if self.rect.bottom > SCREEN_HEIGHT:
            self.rect.bottom = SCREEN_HEIGHT

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface([TILE_SIZE, TILE_SIZE])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 2
        self.hp = 20
        self.attack = 5

    def update(self):
        # Simple AI: Move towards the player
        dx = player.rect.x - self.rect.x
        dy = player.rect.y - self.rect.y
        distance = (dx**2 + dy**2)**0.5

        if distance > 0:
            dx /= distance
            dy /= distance

            self.rect.x += dx * self.speed
            self.rect.y += dy * self.speed

# --- Initialization ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Knight's Adventure")
clock = pygame.time.Clock()

# --- Game Objects ---
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
enemies = pygame.sprite.Group()
for _ in range(5):
    x = random.randint(0, SCREEN_WIDTH - TILE_SIZE)
    y = random.randint(0, SCREEN_HEIGHT - TILE_SIZE)
    enemy = Enemy(x, y)
    enemies.add(enemy)

all_sprites = pygame.sprite.Group()
all_sprites.add(player)
all_sprites.add(enemies)

# --- Game Loop ---
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # --- Update ---
    player.update()
    for enemy in enemies:
        enemy.update()

    # --- Collision Detection ---
    collisions = pygame.sprite.spritecollide(player, enemies, False)
    for enemy in collisions:
        print("Collision!")
        # Implement combat logic here (e.g., reduce HP)
        enemy.hp -= player.attack
        if enemy.hp <= 0:
            enemies.remove(enemy)
            all_sprites.remove(enemy)

    # --- Rendering ---
    screen.fill(BLACK)
    all_sprites.draw(screen)

    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()

@

Explanation:

  • Character Creation: The Pillow code creates a knight.png image.

  • Pygame Initialization: Sets up the Pygame window and clock.

  • Player Class: Loads the knight image, handles movement, and has basic stats.

  • Enemy Class: Creates a simple enemy with basic AI (move towards the player).

  • Game Loop: Handles input, updates game objects, detects collisions, and renders the screen.

  • Collision Detection: Checks for collisions between the player and enemies. (Basic combat logic is included, but needs expansion).

Next Steps (Expanding the Game):

  • More Detailed Combat: Implement attack animations, damage calculation, and enemy death.

  • Inventory System: Add items, equipment, and inventory management.

  • Level Design: Create more complex levels with obstacles and challenges.

  • Sound Effects & Music: Enhance the game with audio.

  • UI: Add a user interface for displaying health, inventory, and other information.

  • More Enemy Types: Create different enemy types with unique behaviors.

  • Procedural Generation: Generate levels randomly.

  • Story & Quests: Add a narrative and quests to give the game more depth.

Important Considerations:

  • Organization: As the game grows, use classes and functions to keep your code organized.

  • Testing: Test your code frequently to catch bugs early.

  • Optimization: Optimize your code for performance, especially if you're dealing with large levels or many enemies.

  • Game Design: Think carefully about the game's mechanics and how they interact with each other.

Comments