Build a Fun ‘Eat Coins’ Game with Python & Pygame: OOP Tutorial
This tutorial walks you through creating a simple 'Eat Coins' game using Python's Pygame library, covering OOP design, class implementation for player, coin, and game management, game loop handling, collision detection, scoring, visual enhancements, and extension ideas.
After completing several object‑oriented (OOP) mini‑games, this article introduces a light‑hearted yet educational game called "Eat Coins". The player controls a character that moves around the screen, collects randomly appearing coins, and earns points, demonstrating how OOP integrates with Pygame.
🗂️ Directory
Project Overview and Goals
OOP Design Analysis
Creating the Player class (Player)
Creating the Coin class (Coin)
Game Management class (Game)
Game Loop and Event Handling
Collision Detection and Scoring System
Beautification and Optimization Suggestions
Project Summary and Extension Exercises
1. Project Overview and Goals
Goals:
Player controls character movement
Collect as many coins as possible within a time limit
Earn points for each collected coin
Coins appear at random positions at intervals
Technical points:
Use Pygame for drawing and handling keyboard events
Encapsulate character and coin logic with OOP
Use the time module to control coin refresh
2. OOP Design Analysis
We will use the following classes to organize the code:
Player: controls player movement and rendering
Coin: represents a coin, holds its position and drawing ability
Game: manages the main loop, object updates and interactions
3. Creating the Player class (Player)
class Player:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, 40, 40)
self.color = (0, 100, 255)
self.speed = 5
def move(self, keys):
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
def draw(self, window):
pygame.draw.rect(window, self.color, self.rect)4. Creating the Coin class (Coin)
import random
class Coin:
def __init__(self, width, height):
size = 20
x = random.randint(0, width - size)
y = random.randint(0, height - size)
self.rect = pygame.Rect(x, y, size, size)
self.color = (255, 215, 0)
def draw(self, window):
pygame.draw.ellipse(window, self.color, self.rect)5. Game Management class (Game)
class Game:
def __init__(self):
pygame.init()
self.width, self.height = 600, 400
self.window = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("吃金币小游戏")
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont(None, 36)
self.player = Player(280, 180)
self.coin = Coin(self.width, self.height)
self.score = 0
self.running = True6. Game Loop and Event Handling
def run(self):
while self.running:
self.clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
keys = pygame.key.get_pressed()
self.player.move(keys)
self.check_collision()
self.draw()7. Collision Detection and Scoring System
def check_collision(self):
if self.player.rect.colliderect(self.coin.rect):
self.score += 1
self.coin = Coin(self.width, self.height)
def draw(self):
self.window.fill((240, 240, 240))
self.player.draw(self.window)
self.coin.draw(self.window)
text = self.font.render(f"Score: {self.score}", True, (0, 0, 0))
self.window.blit(text, (10, 10))
pygame.display.update()8. Beautification and Optimization Suggestions
Use
pygame.image.load()to load images for coins or the player
Add a timed challenge (e.g., a 60‑second countdown)
Include background music or a coin‑collection sound effect
Spawn multiple coins simultaneously
9. Project Summary and Extension Exercises
🎉 You have successfully completed an OOP‑based mini‑game project! You learned how to:
Design classes to encapsulate game objects
Manage the game loop and interactions
Implement simple collision detection
Further practice ideas:
Coins with different point values
Add obstacles to avoid collisions
Implement a leaderboard to store high scores
Continue developing your own creative games with Python and Pygame! 🚀
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.