首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐
2025年5月10日 星期六 12:11pm

10 个pygame经典小游戏

  • 25-04-25 09:01
  • 4151
  • 6083
blog.csdn.net

10个具有代表性的高级小游戏思路及简单代码

1. 2048 游戏
import random


def new_tile(board):
    empty_cells = [(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]
    if empty_cells:
        i, j = random.choice(empty_cells)
        board[i][j] = 2 if random.random() < 0.9 else 4


def transpose(board):
    return list(map(list, zip(*board)))


def reverse(board):
    return [row[::-1] for row in board]


def merge(line):
    new_line = [i for i in line if i]
    for i in range(len(new_line) - 1):
        if new_line[i] == new_line[i + 1]:
            new_line[i] *= 2
            new_line[i + 1] = 0
    new_line = [i for i in new_line if i]
    new_line += [0] * (len(line) - len(new_line))
    return new_line


def move_left(board):
    new_board = []
    for row in board:
        new_row = merge(row)
        new_board.append(new_row)
    return new_board


def move_right(board):
    board = reverse(board)
    new_board = move_left(board)
    return reverse(new_board)


def move_up(board):
    board = transpose(board)
    new_board = move_left(board)
    return transpose(new_board)


def move_down(board):
    board = transpose(board)
    new_board = move_right(board)
    return transpose(new_board)


board = [[0] * 4 for _ in range(4)]
new_tile(board)
new_tile(board)
2. 扫雷游戏
import random


def create_board(width, height, mines):
    board = [[0] * width for _ in range(height)]
    mine_count = 0
    while mine_count < mines:
        x = random.randint(0, width - 1)
        y = random.randint(0, height - 1)
        if board[y][x] != -1:
            board[y][x] = -1
            mine_count += 1

    for y in range(height):
        for x in range(width):
            if board[y][x] != -1:
                count = 0
                for dy in [-1, 0, 1]:
                    for dx in [-1, 0, 1]:
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < width and 0 <= ny < height and board[ny][nx] == -1:
                            count += 1
                board[y][x] = count
    return board


width, height, mines = 10, 10, 10
game_board = create_board(width, height, mines)
3. 贪吃蛇游戏(基于pygame库)

import pygame
import random

# 初始化 pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')

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

# 蛇的初始位置和大小
snake_block = 10
snake_speed = 15

# 字体
font_style = pygame.font.SysFont(None, 50)


def message(msg, color):
    mesg = font_style.render(msg, True, color)
    screen.blit(mesg, [screen_width / 2 - 100, screen_height / 2])


def gameLoop():
    game_over = False
    game_close = False

    x1 = screen_width / 2
    y1 = screen_height / 2

    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close:
            screen.fill(WHITE)
            message("你输了!按Q退出或按C重新开始", RED)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0

        if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        screen.fill(WHITE)
        pygame.draw.rect(screen, RED, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True

        for segment in snake_List:
            pygame.draw.rect(screen, GREEN, [segment[0], segment[1], snake_block, snake_block])

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1

        clock = pygame.time.Clock()
        clock.tick(snake_speed)

    pygame.quit()
    quit()


gameLoop()


gameLoop()
4. 国际象棋(简单棋盘实现)
class ChessBoard:
    def __init__(self):
        self.board = [['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
                      ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
                      [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                      [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                      [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                      [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
                      ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
                      ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']]

    def display(self):
        for row in self.board:
            print(' '.join(row))


board = ChessBoard()
board.display()
5. 推箱子游戏
class BoxPuzzle:
    def __init__(self, layout):
        self.layout = layout
        self.player_x, self.player_y = self.find_player()

    def find_player(self):
        for i in range(len(self.layout)):
            for j in range(len(self.layout[0])):
                if self.layout[i][j] == 'P':
                    return j, i

    def move(self, direction):
        dx, dy = 0, 0
        if direction == 'up':
            dy = -1
        elif direction == 'down':
            dy = 1
        elif direction == 'left':
            dx = -1
        elif direction == 'right':
            dx = 1

        new_x, new_y = self.player_x + dx, self.player_y + dy
        if 0 <= new_y < len(self.layout) and 0 <= new_x < len(self.layout[0]):
            if self.layout[new_y][new_x] == ' ':
                self.layout[self.player_y][self.player_x] = ' '
                self.layout[new_y][new_x] = 'P'
                self.player_x, self.player_y = new_x, new_y
            elif self.layout[new_y][new_x] == 'B' and 0 <= new_y + dy < len(self.layout) and 0 <= new_x + dx < len(
                    self.layout[0]) and self.layout[new_y + dy][new_x + dx] == ' ':
                self.layout[self.player_y][self.player_x] = ' '
                self.layout[new_y][new_x] = 'P'
                self.layout[new_y + dy][new_x + dx] = 'B'
                self.player_x, self.player_y = new_x, new_y

    def display(self):
        for row in self.layout:
            print(''.join(row))


layout = [
    ['#', '#', '#', '#', '#'],
    ['#', ' ', 'B', ' ', '#'],
    ['#', ' ', 'P', ' ', '#'],
    ['#', ' ', ' ', ' ', '#'],
    ['#', '#', '#', '#', '#']
]
puzzle = BoxPuzzle(layout)
puzzle.display()
6. 猜数字游戏(带提示和多次机会)
import random


def guess_number():
    target = random.randint(1, 100)
    attempts = 0
    while True:
        try:
            guess = int(input("请猜一个1到100之间的整数: "))
            attempts += 1
            if guess == target:
                print(f"恭喜你,猜对了!你用了{attempts}次尝试。")
                break
            elif guess < target:
                print("猜小了,请再试一次。")
            else:
                print("猜大了,请再试一次。")
        except ValueError:
            print("请输入一个有效的整数。")


guess_number()
7. 四子连珠游戏
class ConnectFour:
    def __init__(self):
        self.board = [[' '] * 7 for _ in range(6)]
        self.current_player = 'X'

    def drop(self, col):
        if col < 0 or col >= 7:
            return False
        for row in range(5, -1, -1):
            if self.board[row][col] == ' ':
                self.board[row][col] = self.current_player
                return True
        return False

    def check_win(self):
        # 检查行
        for row in self.board:
            for i in range(4):
                if row[i:i + 4] == [self.current_player] * 4:
                    return True

        # 检查列
        for col in range(7):
            for i in range(3):
                if [self.board[i][col], self.board[i + 1][col], self.board[i + 2][col], self.board[i + 3][col]] == [
                    self.current_player] * 4:
                    return True

        # 检查对角线
        for i in range(3):
            for j in range(4):
                if self.board[i][j] == self.board[i + 1][j + 1] == self.board[i + 2][j + 2] == self.board[i + 3][j + 3] == \
                        self.current_player:
                    return True
                if self.board[i][j + 3] == self.board[i + 1][j + 2] == self.board[i + 2][j + 1] == self.board[i + 3][j] == \
                        self.current_player:
                    return True
        return False

    def display(self):
        for row in self.board:
            print(' '.join(row))
        print('0 1 2 3 4 5 6')


game = ConnectFour()
while True:
    game.display()
    print(f"玩家 {game.current_player} 的回合")
    col = int(input("请选择列 (0-6): "))
    if game.drop(col):
        if game.check_win():
            game.display()
            print(f"玩家 {game.current_player} 获胜!")
            break
        game.current_player = 'O' if game.current_player == 'X' else 'X'
    else:
        print("该列已满,请重新选择。")
8. 记忆配对游戏(基于Tkinter库)
import tkinter as tk
import random


class MemoryGame:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("记忆配对游戏")
        self.buttons = []
        self.pairs = [(i, i) for i in range(8)]
        random.shuffle(self.pairs)
        self.flip_count = 0
        self.first_card = None
        self.second_card = None

        for i in range(4):
            row_buttons = []
            for j in range(4):
                button = tk.Button(self.window, text="?", width=10, height=5,
                                   command=lambda r=i, c=j: self.flip_card(r, c))
                button.grid(row=i, column=j)
                row_buttons.append(button)
            self.buttons.append(row_buttons)

    def flip_card(self, row, col):
        button = self.buttons[row][col]
        pair_index = row * 4 + col
        button.config(text=str(self.pairs[pair_index][0]))
        if self.flip_count == 0:
            self.first_card = (row, col)
            self.flip_count = 1
        elif self.flip_count == 1:
            self.second_card = (row, col)
            self.flip_count = 2
            self.window.after(500, self.check_match)

    def check_match(self):
        first_pair = self.pairs[self.first_card[0] * 4 + self.first_card[1]]
        second_pair = self.pairs[self.second_card[0] * 4 + self.second_card[1]]
        if first_pair == second_pair:
            for button in [self.buttons[self.first_card[0]][self.first_card[1]],
                           self.buttons[self.second_card[0]][self.second_card[1]]]:
                button.config(state=tk.DISABLED)
        else:
            for button in [self.buttons[self.first_card[0]][self.first_card[1]],
                           self.buttons[self.second_card[0]][self.second_card[1]]]:
                button.config(text="?")
        self.first_card = None
        self.second_card = None
        self.flip_count = 0

    def run(self):
        self.window.mainloop()


game = MemoryGame()
game.run()
9. 弹球游戏(基于pygame库)

import pygame

# 初始化 pygame
pygame.init()

# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('弹球游戏')

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

# 弹球属性
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_dx = 0.3
ball_dy = -0.3

# 球拍属性
paddle_width = 100
paddle_height = 10
paddle_x = screen_width // 2 - paddle_width // 2
paddle_y = screen_height - 50

clock = pygame.time.Clock()

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

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_x > 0:
        paddle_x -= 5
    elif keys[pygame.K_RIGHT] and paddle_x < screen_width - paddle_width:
        paddle_x += 5

    ball_x += ball_dx
    ball_y += ball_dy

    if ball_x - ball_radius < 0 or ball_x + ball_radius > screen_width:
        ball_dx = -ball_dx
    if ball_y - ball_radius < 0:
        ball_dy = -ball_dy
    if (
        ball_y + ball_radius > paddle_y
        and ball_y - ball_radius < paddle_y + paddle_height
        and ball_x > paddle_x
        and ball_x < paddle_x + paddle_width
    ):
        ball_dy = -ball_dy

    screen.fill(WHITE)
    pygame.draw.circle(screen, BLACK, (int(ball_x), int(ball_y)), ball_radius)
    pygame.draw.rect(screen, BLACK, (paddle_x, paddle_y, paddle_width, paddle_height))
    pygame.display.flip()

    clock.tick(60)

pygame.quit()

 

注:本文转载自blog.csdn.net的Ttcoffee_2048的文章"https://blog.csdn.net/2505_90340337/article/details/146445041"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
游戏

Python版贪吃蛇保姆级教程

Python版贪吃蛇(最后附上完整代码并有详细注释):从零开始用Pygame实现经典游戏一、前言:童年经典游戏重生贪吃蛇作为一款经典游戏,承载着无数人的童年回忆。今天我们将用Python+pygame从零开始实现这个经典游戏!通过本教程,你...
2025-04-25 3704 11970
游戏

python3.x 安装pygame常见报错即处理方法

Pygame 安装报错$ sudopip3install pygameerror: externally-managed-environment× This environment is externally managed╰─>To in...
2025-04-25 2439 14183
游戏

【unity的一些快捷键】

Unity中的快捷键可以帮助你极大地提高工作效率。以下是一些常用的Unity快捷键:文件操作:Ctrl + N:新建项目。Ctrl + S:保存场景或资产。Ctrl + Shift + S:保存所有场景和资产。视图控制:Ctrl + 0:重...
2025-04-25 3348 12299
游戏

【Unity基础】Unity中角色动画的三种实现方式

在Unity中,角色动画有三种不同的实现方式:逐帧动画(Frame-by-Frame)、剪裁动画(Cutout)和骨骼动画(Skeletal),各自适用于不同的场景和需求。以下是它们的核心区别及特点:1. 逐帧动画(Frame-by-Fra...
2025-04-25 3523 9590
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

  • 1

    Python版贪吃蛇保姆级教程

  • 2

    python3.x 安装pygame常见报错即处理方法

  • 3

    【unity的一些快捷键】

  • 4

    【Unity基础】Unity中角色动画的三种实现方式

  • 5

    Unity6000下载地址

  • 6

    10 个pygame经典小游戏

  • 7

    【逆向工程】破解unity的安卓apk包

  • 8

    unity 无法安装6000版本的问题

  • 9

    Pico 4 Enterprise(企业版)与Unity的交互-打包运行及UI交互篇

  • 10

    从零开始打造属于你的Pygame小游戏:轻松入门与高效开发

134
游戏
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top