How to write a small game using Python?

insert image description here

Hello everyone, I am Muchen. If you are a friend who loves programming and wants to try game development, then this article will definitely satisfy your curiosity. No nonsense, let us immediately enter the wonderful world of Python game development!

The charm of Python game development
Writing small games is not only a good way to exercise programming skills, but also an excellent way to show creativity and enjoy the results. As an easy-to-learn and easy-to-use programming language, Python provides rich possibilities for game development.

Game Example 1: Classic Number Guessing Game

Let's start with a classic guessing number game. Players need to guess a randomly generated number, and experience a sense of accomplishment and fun through interaction with the computer.

import random

target_number = random.randint(1, 100)
attempts = 0
guess = 0

print("欢迎来到“沐尘而生的猜数字游戏”!")
while guess != target_number:
    guess = int(input("请输入你猜的数字:"))
    attempts += 1
    if guess < target_number:
        print("猜小了,再试试!")
    elif guess > target_number:
        print("猜大了,再试试!")
    else:
        print(f"恭喜你,猜对了!你用了{
      
      attempts}次。")

insert image description here

Game Example 2: Classic Snake Game

Next, let's write a classic snake game. Players will control a small snake to move on the screen, eat food, and gradually grow longer. The game is not only a test of reaction speed, but also full of strategy.

import pygame
import random

# 初始化
pygame.init()

# 设置游戏窗口
WINDOW_SIZE = (640, 480)
window = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Snake Game by Muchen")

# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)

# 蛇和食物定义
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randrange(1, 64) * 10, random.randrange(1, 48) * 10]

# 游戏逻辑函数
def update_snake():
    global food_pos, snake_pos, snake_body
    
    # 移动蛇头
    snake_pos[0] += direction[0]
    snake_pos[1] += direction[1]
    
    # 判断是否吃到食物
    if snake_pos == food_pos:
        food_pos = [random.randrange(1, 64) * 10, random.randrange(1, 48) * 10]
    else:
        snake_body.pop()

    # 将新的蛇头添加到蛇身上
    snake_body.insert(0, list(snake_pos))

def update_food():
    global food_pos

    # 绘制食物
    pygame.draw.rect(window, WHITE, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    # 判断食物是否被吃掉
    if snake_pos == food_pos:
        food_pos = [random.randrange(1, 64) * 10, random.randrange(1, 48) * 10]
        snake_body.append([0, 0])

def draw_snake():
    # 绘制贪吃蛇
    for pos in snake_body:
        pygame.draw.rect(window, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))

# 初始化方向
direction = [0, -10]

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    
    # 获取键盘输入
    keys = pygame.key.get_pressed()

    # 判断方向
    if keys[pygame.K_LEFT] and direction != [10, 0]:
        direction = [-10, 0]
    elif keys[pygame.K_RIGHT] and direction != [-10, 0]:
        direction = [10, 0]
    elif keys[pygame.K_UP] and direction != [0, 10]:
        direction = [0, -10]
    elif keys[pygame.K_DOWN] and direction != [0, -10]:
        direction = [0, 10]

    # 更新蛇和食物
    update_snake()
    update_food()

    # 清空屏幕,绘制蛇和食物
    window.fill(BLACK)
    draw_snake()

    # 更新窗口
    pygame.display.update()

insert image description here

Game Example 3: Aircraft War Game

Let's write a plane wars game. Players will control a plane, dodge enemy bullets, and shoot enemies at the same time, experiencing excitement and challenges.

import pygame

# 初始化
pygame.init()

# 设置游戏窗口
window_size = (640, 480)
window = pygame.display.set_mode(window_size)
pygame.display.set_caption("沐尘而生的飞机大战游戏")

# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 飞机和子弹定义
plane_width, plane_height = 40, 40
plane = pygame.Rect(window_size[0]/2-plane_width/2, window_size[1]-plane_height-20, plane_width, plane_height)
bullet_width, bullet_height = 5, 15
bullet = pygame.Rect(0, 0, bullet_width, bullet_height)
bullet_state = "ready"

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    # 飞机的移动逻辑
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        plane.x -= 5
    if keys[pygame.K_RIGHT]:
        plane.x += 5
    if keys[pygame.K_SPACE] and bullet_state == "ready":
        bullet_state = "fire"
        bullet.centerx = plane.centerx
        bullet.y = plane.y

    # 子弹的移动逻辑
    if bullet_state == "fire":
        bullet.y -= 10
    if bullet.y <= 0:
        bullet_state = "ready"

    # 绘制飞机和子弹
    window.fill(black)
    pygame.draw.rect(window, white, plane)
    pygame.draw.rect(window, red, bullet)
    
    # 更新窗口
    pygame.display.update() 

insert image description here

Example 4: Breakout game

Finally, let's write an Arkanoid game using Python and the Pygame library:

import pygame
import random

# 初始化
pygame.init()

# 设置游戏窗口
window_size = (640, 480)
window = pygame.display.set_mode(window_size)
pygame.display.set_caption("沐尘而生的打砖块游戏")

# 颜色定义
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)

# 砖块的定义
brick_width = 60
brick_height = 20
brick_margin = 5
bricks = []

for row in range(5):
    for column in range(10):
        rect = pygame.Rect(column * (brick_width + brick_margin), row * (brick_height + brick_margin), brick_width, brick_height)
        bricks.append(rect)

# 球的定义
ball_size = 20
ball = pygame.Rect(window_size[0] // 2 - ball_size // 2, window_size[1] // 2 - ball_size // 2, ball_size, ball_size)
ball_speed = [5, 5]

# 板子的定义
paddle_width = 100
paddle_height = 10
paddle = pygame.Rect(window_size[0] // 2 - paddle_width // 2, window_size[1] - paddle_height * 2, paddle_width, paddle_height)

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    # 球的移动逻辑
    ball.x += ball_speed[0]
    ball.y += ball_speed[1]

    # 球与窗口边界的碰撞检测
    if ball.left <= 0 or ball.right >= window_size[0]:
        ball_speed[0] = -ball_speed[0]
    if ball.top <= 0:
        ball_speed[1] = -ball_speed[1]

    # 球与板子的碰撞检测
    if ball.colliderect(paddle):
        ball_speed[1] = -ball_speed[1]

    # 球与砖块的碰撞检测
    for brick in bricks:
        if ball.colliderect(brick):
            bricks.remove(brick)
            ball_speed[1] = -ball_speed[1]
            break

    # 板子移动逻辑
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        paddle.x -= 5
    if keys[pygame.K_RIGHT]:
        paddle.x += 5

    # 确保板子不会移出窗口
    if paddle.left < 0:
        paddle.left = 0
    if paddle.right > window_size[0]:
        paddle.right = window_size[0]

    # 更新窗口
    window.fill(BLACK)
    pygame.draw.rect(window, WHITE, paddle)
    pygame.draw.ellipse(window, BLUE, ball)
    for brick in bricks:
        pygame.draw.rect(window, GREEN, brick)
    pygame.display.update()

insert image description here

Through the above several wonderful small game examples, we have a deep understanding of how to use Python for game development. From guessing numbers, eating snakes, to airplane wars, and breaking bricks, each game exudes a unique charm. Whether you are new to Python or an experienced developer, you can get fun and a sense of accomplishment from writing small games. I hope this article can inspire your creativity and start your game programming journey. If you have any questions or ideas about these mini-games, welcome to communicate with me in the comment area. Thanks for reading everyone!

insert image description here

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132319543