Python Game Development Code Collection
This article presents a collection of thirteen Python game development examples, each with a brief description, gameplay illustration, and complete source code using libraries such as pygame and PyQt5, covering games like coin collector, ping‑pong, skiing, space shooter, whack‑a‑mole, dinosaur runner, match‑3, Tetris, snake, 24‑point puzzle, balance beam, alien invasion, and tic‑tac‑toe.
This document provides a curated set of Python game examples, each accompanied by a short description, an animated GIF preview, and the full source code. The games demonstrate the use of pygame , PyQt5 , and custom modules to create interactive desktop applications.
1. Coin Collector (吃金币)
A simple game where the player collects coins. The code initializes pygame, loads assets, and runs the main loop.
<code>import os
import cfg
import sys
import pygame
from modules import *
def initGame():
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('吃金币——九歌')
return screen
# ... (rest of the game logic)</code>2. Ping‑Pong (打乒乓)
A two‑player table tennis game with keyboard controls. The script sets up the display, handles player input, and updates ball and paddle positions.
<code>import sys
import cfg
import pygame
from modules import *
# ... initialization code
def GamingInterface(num_player, screen):
# game loop with event handling for player controls
while True:
# ... update and render
pass
</code>3. Skiing (滑雪)
A side‑scrolling skiing game where the player avoids obstacles. The code defines a SkierClass , obstacle generation, and collision handling.
<code>import sys
import cfg
import pygame
import random
from modules import *
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.direction = 0
# ... load images and set rect
# ... main loop and game logic</code>4. Space Shooter (飞机大战)
A classic space‑invader style shooter supporting one or two players. It uses pygame sprites for ships, bullets, and asteroids.
<code>import sys
import cfg
import pygame
from modules import *
class GamingInterface(num_player, screen):
# initialization of background, player groups, and game loop
while True:
# handle movement, shooting, collisions
pass
</code>5. Whack‑a‑Mole (打地鼠)
An arcade‑style whack‑a‑mole game with timed mole appearances and scoring.
<code>import cfg
import sys
import pygame
import random
from modules import *
def initGame():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('打地鼠——九歌')
return screen
# ... main loop with mole logic</code>6. Dinosaur Runner (小恐龙)
An endless runner featuring a dinosaur that jumps over obstacles. The script loads sounds, fonts, and sprite groups for clouds, cacti, and pterodactyls.
<code>import cfg
import sys
import pygame
from modules import *
def main(highest_score):
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
# ... game loop with dino.update(), obstacle spawning, scoring
</code>7. Match‑3 (消消乐)
A gem‑matching puzzle where three identical gems disappear. The code sets up the game grid, loads sounds, and handles player input.
<code>import os
import sys
import cfg
import pygame
from modules import *
def main():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('Gemgem——九歌')
# ... load music, sound effects, gem images, and run game loop
</code>8. Tetris (俄罗斯方块)
A PyQt5 implementation of the classic Tetris game with pause, rotate, and fast‑drop features.
<code>from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class TetrisGame(QMainWindow):
def __init__(self, parent=None):
super(TetrisGame, self).__init__(parent)
self.is_paused = False
self.is_started = False
self.initUI()
# ... UI setup, timer events, key handling
</code>9. Snake (贪吃蛇)
A classic snake game where the snake grows by eating apples. The script manages movement, collision, and scoring.
<code>import cfg
import sys
import pygame
from modules import *
def main(cfg):
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
# ... game loop with snake.update(), apple.draw(), score display
</code>10. 24‑Point Puzzle (24点小游戏)
A mathematical puzzle that challenges the player to reach 24 using four numbers and basic operators. The code includes UI handling, card selection, and calculation logic.
<code>import os
import sys
import pygame
from fractions import Fraction
def calculate(number1, number2, operator):
operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'}
try:
result = str(eval(number1+operator_map[operator]+number2))
return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))
except:
return None
</code>11. Balance Beam (平衡木)
A simple balance‑beam game using a breakout‑style clone from the modules package.
<code>import cfg
from modules import breakoutClone
def main():
game = breakoutClone(cfg)
game.run()
</code>12. Alien Invasion (外星人入侵)
A space‑shooter where the player defends against waves of alien ships. The code defines enemy sprites, UFO, player aircraft, and handles shooting, movement, and collision.
<code>import os
import sys
import cfg
import random
import pygame
from modules import *
def startGame(screen):
# initialize groups, load fonts, create enemies, player, UFO
while running:
# event handling, player shooting, enemy movement, collision detection
pass
</code>13. Tic‑Tac‑Toe (井字棋888)
A GUI implementation of tic‑tac‑toe using Tkinter. The script creates a 3×3 grid of buttons, tracks player turns, and determines win or tie conditions.
<code>from tkinter import *
import tkinter.messagebox as msg
root = Tk()
root.title('TIC-TAC-TOE---Project Gurukul')
panels = ["panel"] * 10
def win(panels, sign):
return ((panels[1]==panels[2]==panels[3]==sign) or ... )
def checker(digit):
global count, mark, digits
# handle button clicks, update panels, check win/tie
pass
</code>Each example is self‑contained and can be run directly after installing the required dependencies. The collection serves as a practical reference for developers learning game programming with Python.
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.