10 个pygame经典小游戏

发布于:2025-03-23 ⋅ 阅读:(25) ⋅ 点赞:(0)

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()