学号 20241317 2024-2025-2《Python程序设计》实验四报告

学号 20241317 2024-2025-2《Python程序设计》实验四报告

课程:《Python程序设计》
班级: 2413
姓名: 文彩懿
学号:20241317
实验教师:王志强
实验日期:2025年5月14日
必修/选修: 公选课

一.实验内容

1.纯控制台界面代码编写;
2.图形化界面;
3.对代码继续润色修改;
4.呈现最终代码和运行结果。

二. 实验过程及结果

(一)通过所学知识,编写2048游戏的简易版本并运行,我想的是先写一个纯控制台界面

import random
import os

class Game2048:
    def __init__(self):
        self.board = [[0 for _ in range(4)] for _ in range(4)]
        self.score = 0
        self.game_over = False
        self.won = False
        self.add_new_tile()
        self.add_new_tile()

    def add_new_tile(self):
        empty_cells = [(i, j) for i in range(4) for j in range(4) if self.board[i][j] == 0]
        if not empty_cells:
            return
        i, j = random.choice(empty_cells)
        self.board[i][j] = 4 if random.random() < 0.1 else 2

    def transpose(self):
        self.board = [list(row) for row in zip(*self.board)]

    def reverse(self):
        self.board = [row[::-1] for row in self.board]

    def merge_left(self):
        moved = False
        for i in range(4):
            merged = [False] * 4
            for j in range(1, 4):
                if self.board[i][j] == 0:
                    continue
                k = j
                while k > 0 and self.board[i][k-1] == 0:
                    self.board[i][k-1] = self.board[i][k]
                    self.board[i][k] = 0
                    k -= 1
                    moved = True
                if k > 0 and self.board[i][k-1] == self.board[i][k] and not merged[k-1]:
                    self.board[i][k-1] *= 2
                    self.score += self.board[i][k-1]
                    self.board[i][k] = 0
                    merged[k-1] = True
                    moved = True
        return moved

    def can_move(self):
        for i in range(4):
            for j in range(4):
                if self.board[i][j] == 0:
                    return True
                if i < 3 and self.board[i][j] == self.board[i+1][j]:
                    return True
                if j < 3 and self.board[i][j] == self.board[i][j+1]:
                    return True
        return False

    def move(self, direction):
        if self.game_over or self.won:
            return False

        moved = False
        if direction == 'w':
            self.transpose()
            moved = self.merge_left()
            self.transpose()
        elif direction == 's':
            self.transpose()
            self.reverse()
            moved = self.merge_left()
            self.reverse()
            self.transpose()
        elif direction == 'a':
            moved = self.merge_left()
        elif direction == 'd':
            self.reverse()
            moved = self.merge_left()
            self.reverse()
        else:
            return False

        if moved:
            self.add_new_tile()
            self.check_status()
            return True
        return False

    def check_status(self):
        if any(2048 in row for row in self.board):
            self.won = True
        if not self.can_move():
            self.game_over = True

    def print_board(self):
        os.system('cls' if os.name == 'nt' else 'clear')
        print("Score:", self.score)
        print("-" * 21)
        for row in self.board:
            print("|", end="")
            for num in row:
                if num == 0:
                    print(f"{' ':^4}|", end="")
                else:
                    print(f"{num:^4}|", end="")
            print("\n" + "-" * 21)
        print("\nUse 'w', 's', 'a', 'd' to move (q to quit)")

def main():
    game = Game2048()
    game.print_board()

    while not game.game_over and not game.won:
        move = input().lower()
        if move == 'q':
            break
        if game.move(move):
            game.print_board()

    if game.won:
        print("Congratulations! You won!")
    elif game.game_over:
        print("Game Over!")
    print(f"Final Score: {game.score}")

if __name__ == "__main__":
    main()

运行结果:

可见,改代码可基本实现2048游戏,但单一的界面和颜色明显达不到想要的效果,所以继续向图形化界面进军
(二)图形化界面
在B站学习的过程中,被种草了pygame迫不及待下载了

但是发现下不了,询问AI后选择清华大学的镜像加速下载

终于下载成功,基于此继续代码编写
代码如下:

import pygame
import random
import math

# 初始化 Pygame
pygame.init()

# 游戏基本设置
FPS = 60
WIDTH, HEIGHT = 800, 800
ROWS = 4
COLS = 4
RECT_HEIGHT = HEIGHT // ROWS
RECT_WIDTH = WIDTH // COLS
OUTLINE_COLOR = (187, 173, 160)
OUTLINE_THICKNESS = 10
BACKGROUND_COLOR = (205, 192, 180)
FONT_COLOR = (119, 110, 101)
FONT = pygame.font.SysFont(name="comicsans", size=60, bold=True)
MOVE_VEL = 20

# 创建游戏窗口
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048")


class Tile:
    # 不同数值方块对应的颜色
    COLORS = [
        (237, 229, 218),
        (238, 225, 201),
        (243, 178, 122),
        (246, 150, 101),
        (247, 124, 95),
        (247, 95, 59),
        (237, 208, 115),
        (237, 204, 99),
        (236, 202, 80),
    ]

    def __init__(self, value, row, col):
        self.value = value
        self.row = row
        self.col = col
        self.x = col * RECT_WIDTH
        self.y = row * RECT_HEIGHT

    def get_color(self):
        color_index = int(math.log2(self.value)) - 1
        return self.COLORS[color_index]

    def draw(self, window):
        color = self.get_color()
        # 绘制方块
        pygame.draw.rect(window, color, (self.x, self.y, RECT_WIDTH, RECT_HEIGHT))
        # 绘制方块上的数字
        text = FONT.render(str(self.value), True, FONT_COLOR)
        window.blit(
            text,
            (
                self.x + (RECT_WIDTH / 2 - text.get_width() / 2),
                self.y + (RECT_HEIGHT / 2 - text.get_height() / 2),
            ),
        )

    def set_pos(self, ceil=False):
        if ceil:
            self.row = math.ceil(self.y / RECT_HEIGHT)
            self.col = math.ceil(self.x / RECT_WIDTH)
        else:
            self.row = math.floor(self.y / RECT_HEIGHT)
            self.col = math.floor(self.x / RECT_WIDTH)

    def move(self, delta):
        self.x += delta[0]
        self.y += delta[1]


# 生成随机方块(2 或 4 )
def spawn_random_tile(tiles):
    empty_cells = []
    for row in range(ROWS):
        for col in range(COLS):
            if not any(tile.row == row and tile.col == col for tile in tiles):
                empty_cells.append((row, col))
    if empty_cells:
        row, col = random.choice(empty_cells)
        value = 2 if random.random() < 0.9 else 4
        return Tile(value, row, col)
    return None


# 处理行或列的合并逻辑
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 left_move(tiles):
    new_tiles = []
    for row in range(ROWS):
        line = [tile.value for tile in tiles if tile.row == row]
        merged_line = merge(line)
        for col, val in enumerate(merged_line):
            if val:
                new_tiles.append(Tile(val, row, col))
    return new_tiles


def right_move(tiles):
    new_tiles = []
    for row in range(ROWS):
        line = [tile.value for tile in tiles if tile.row == row]
        line.reverse()
        merged_line = merge(line)
        merged_line.reverse()
        for col, val in enumerate(merged_line):
            if val:
                new_tiles.append(Tile(val, row, col))
    return new_tiles


# 处理上下移动
def up_move(tiles):
    new_tiles = []
    for col in range(COLS):
        line = [tile.value for tile in tiles if tile.col == col]
        merged_line = merge(line)
        for row, val in enumerate(merged_line):
            if val:
                new_tiles.append(Tile(val, row, col))
    return new_tiles


def down_move(tiles):
    new_tiles = []
    for col in range(COLS):
        line = [tile.value for tile in tiles if tile.col == col]
        line.reverse()
        merged_line = merge(line)
        merged_line.reverse()
        for row, val in enumerate(merged_line):
            if val:
                new_tiles.append(Tile(val, row, col))
    return new_tiles


# 游戏主循环
def main():
    clock = pygame.time.Clock()
    tiles = [Tile(2, 0, 0), Tile(2, 1, 1)]  # 初始方块
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    tiles = left_move(tiles)
                    new_tile = spawn_random_tile(tiles)
                    if new_tile:
                        tiles.append(new_tile)
                elif event.key == pygame.K_RIGHT:
                    tiles = right_move(tiles)
                    new_tile = spawn_random_tile(tiles)
                    if new_tile:
                        tiles.append(new_tile)
                elif event.key == pygame.K_UP:
                    tiles = up_move(tiles)
                    new_tile = spawn_random_tile(tiles)
                    if new_tile:
                        tiles.append(new_tile)
                elif event.key == pygame.K_DOWN:
                    tiles = down_move(tiles)
                    new_tile = spawn_random_tile(tiles)
                    if new_tile:
                        tiles.append(new_tile)

        # 绘制游戏背景
        WINDOW.fill(BACKGROUND_COLOR)
        # 绘制方块轮廓(可优化为遍历绘制线条,这里简单示例 )
        for i in range(1, ROWS):
            pygame.draw.line(
                WINDOW,
                OUTLINE_COLOR,
                (0, i * RECT_HEIGHT),
                (WIDTH, i * RECT_HEIGHT),
                OUTLINE_THICKNESS,
            )
            pygame.draw.line(
                WINDOW,
                OUTLINE_COLOR,
                (i * RECT_WIDTH, 0),
                (i * RECT_WIDTH, HEIGHT),
                OUTLINE_THICKNESS,
            )
        # 绘制方块
        for tile in tiles:
            tile.draw(WINDOW)

        pygame.display.update()

    pygame.quit()


if __name__ == "__main__":
    main()

期间查询了如何获取颜色和制作色块
运行结果:

到这里已经实现主要代码设计,接下来就是不断优化代码运行,;我的想法是想上课时一样提供开场动画和提示性语句,再加上计分系统
(三)代码优化润色
开场动画:

结束动画:

计分系统:

代码运行:

神奇的发现,文字无法显示,询问AI后选择从系统里调用文字,成功呈现

询问AI改进意见时,提到了动画的平移,从而进一步美化运行结果
(四)最终代码呈现
代码如下:

# -*- coding: utf-8 -*-
import pygame
import random
import math
import time
import sys

# 初始化Pygame
pygame.init()
pygame.mixer.init()

# 游戏基本设置
FPS = 60
WIDTH, HEIGHT = 800, 900
ROWS = 4
COLS = 4
RECT_HEIGHT = (HEIGHT - 150) // ROWS
RECT_WIDTH = WIDTH // COLS
OUTLINE_COLOR = (187, 173, 160)
OUTLINE_THICKNESS = 10
BACKGROUND_COLOR = (205, 192, 180)
FONT_COLOR = (119, 110, 101)

# 字体设置(确保使用支持中文的字体)
try:
    FONT = pygame.font.SysFont("Microsoft YaHei", 60, bold=True)
    SMALL_FONT = pygame.font.SysFont("Microsoft YaHei", 36, bold=True)
    MEDIUM_FONT = pygame.font.SysFont("Microsoft YaHei", 48, bold=True)
    LARGE_FONT = pygame.font.SysFont("Microsoft YaHei", 72, bold=True)
except:
    try:
        FONT = pygame.font.SysFont("SimHei", 60, bold=True)
        SMALL_FONT = pygame.font.SysFont("SimHei", 36, bold=True)
        MEDIUM_FONT = pygame.font.SysFont("SimHei", 48, bold=True)
        LARGE_FONT = pygame.font.SysFont("SimHei", 72, bold=True)
    except:
        FONT = pygame.font.SysFont(None, 60, bold=True)
        SMALL_FONT = pygame.font.SysFont(None, 36, bold=True)
        MEDIUM_FONT = pygame.font.SysFont(None, 48, bold=True)
        LARGE_FONT = pygame.font.SysFont(None, 72, bold=True)
        print("警告:未找到中文字体,中文显示可能不正常")

# 创建游戏窗口
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2048")


class Tile:
    COLORS = [
        (237, 229, 218), (238, 225, 201), (243, 178, 122), (246, 150, 101),
        (247, 124, 95), (247, 95, 59), (237, 208, 115), (237, 204, 99),
        (236, 202, 80), (237, 197, 63), (237, 194, 46)
    ]

    def __init__(self, value, row, col):
        self.value = value
        self.row = row
        self.col = col
        self.x = col * RECT_WIDTH
        self.y = row * RECT_HEIGHT + 150
        self.merged = False
        self.animating = False
        self.target_x = self.x
        self.target_y = self.y

    def get_color(self):
        color_index = int(math.log2(self.value)) - 1
        color_index = max(0, min(color_index, len(self.COLORS) - 1))
        return self.COLORS[color_index]

    def draw(self, window):
        if self.animating:
            dx = self.target_x - self.x
            dy = self.target_y - self.y
            distance = math.sqrt(dx * dx + dy * dy)
            if distance < 5:
                self.x, self.y = self.target_x, self.target_y
                self.animating = False
            else:
                self.x += dx * 0.2
                self.y += dy * 0.2

        color = self.get_color()
        pygame.draw.rect(window, color, (self.x, self.y, RECT_WIDTH, RECT_HEIGHT))

        font_size = 40 if self.value >= 1000 else 60
        try:
            font = pygame.font.SysFont("Microsoft YaHei", font_size, bold=True)
        except:
            font = pygame.font.SysFont(None, font_size, bold=True)
        text = font.render(str(self.value), True, FONT_COLOR)
        window.blit(text, (self.x + (RECT_WIDTH - text.get_width()) / 2,
                           self.y + (RECT_HEIGHT - text.get_height()) / 2))

    def move(self, row, col, animate=True):
        self.target_x = col * RECT_WIDTH
        self.target_y = row * RECT_HEIGHT + 150

        if animate and (self.row != row or self.col != col):
            self.animating = True
            self.row = row
            self.col = col
            return True
        else:
            self.x = self.target_x
            self.y = self.target_y
            self.row = row
            self.col = col
            return False


def spawn_random_tile(tiles):
    empty_cells = [(r, c) for r in range(ROWS) for c in range(COLS)
                   if not any(t.row == r and t.col == c for t in tiles)]
    if empty_cells:
        row, col = random.choice(empty_cells)
        return Tile(2 if random.random() < 0.9 else 4, row, col)
    return None


def get_grid(tiles):
    grid = [[None for _ in range(COLS)] for _ in range(ROWS)]
    for tile in tiles:
        grid[tile.row][tile.col] = tile
    return grid


def reset_animation_state(tiles):
    for tile in tiles:
        tile.animating = False
        tile.merged = False


def move_left(tiles, score):
    reset_animation_state(tiles)
    moved = False
    grid = get_grid(tiles)
    new_tiles = []

    for row in range(ROWS):
        line = [grid[row][col] for col in range(COLS) if grid[row][col]]
        new_line = []
        skip = False

        for i in range(len(line)):
            if skip:
                skip = False
                continue

            if i + 1 < len(line) and line[i].value == line[i + 1].value and not line[i].merged and not line[
                i + 1].merged:
                new_tile = Tile(line[i].value * 2, row, len(new_line))
                new_tile.merged = True
                new_line.append(new_tile)
                skip = True
                moved = True
                score += new_tile.value
            else:
                if line[i].move(row, len(new_line)):
                    moved = True
                new_line.append(line[i])

        new_tiles.extend([t for t in new_line + [None] * (COLS - len(new_line)) if t])

    return new_tiles, moved, score


def move_right(tiles, score):
    reset_animation_state(tiles)
    moved = False
    grid = get_grid(tiles)
    new_tiles = []

    for row in range(ROWS):
        line = [grid[row][col] for col in range(COLS) if grid[row][col]]
        line.reverse()
        new_line = []
        skip = False

        for i in range(len(line)):
            if skip:
                skip = False
                continue

            if i + 1 < len(line) and line[i].value == line[i + 1].value and not line[i].merged and not line[
                i + 1].merged:
                new_tile = Tile(line[i].value * 2, row, COLS - 1 - len(new_line))
                new_tile.merged = True
                new_line.append(new_tile)
                skip = True
                moved = True
                score += new_tile.value
            else:
                if line[i].move(row, COLS - 1 - len(new_line)):
                    moved = True
                new_line.append(line[i])

        new_line = [None] * (COLS - len(new_line)) + new_line[::-1]
        new_tiles.extend([t for t in new_line if t])

    return new_tiles, moved, score


def move_up(tiles, score):
    reset_animation_state(tiles)
    moved = False
    grid = get_grid(tiles)
    new_tiles = []

    for col in range(COLS):
        line = [grid[row][col] for row in range(ROWS) if grid[row][col]]
        new_line = []
        skip = False

        for i in range(len(line)):
            if skip:
                skip = False
                continue

            if i + 1 < len(line) and line[i].value == line[i + 1].value and not line[i].merged and not line[
                i + 1].merged:
                new_tile = Tile(line[i].value * 2, len(new_line), col)
                new_tile.merged = True
                new_line.append(new_tile)
                skip = True
                moved = True
                score += new_tile.value
            else:
                if line[i].move(len(new_line), col):
                    moved = True
                new_line.append(line[i])

        new_tiles.extend([t for t in new_line + [None] * (ROWS - len(new_line)) if t])

    return new_tiles, moved, score


def move_down(tiles, score):
    reset_animation_state(tiles)
    moved = False
    grid = get_grid(tiles)
    new_tiles = []

    for col in range(COLS):
        line = [grid[row][col] for row in range(ROWS) if grid[row][col]]
        line.reverse()
        new_line = []
        skip = False

        for i in range(len(line)):
            if skip:
                skip = False
                continue

            if i + 1 < len(line) and line[i].value == line[i + 1].value and not line[i].merged and not line[
                i + 1].merged:
                new_tile = Tile(line[i].value * 2, ROWS - 1 - len(new_line), col)
                new_tile.merged = True
                new_line.append(new_tile)
                skip = True
                moved = True
                score += new_tile.value
            else:
                if line[i].move(ROWS - 1 - len(new_line), col):
                    moved = True
                new_line.append(line[i])

        new_line = [None] * (ROWS - len(new_line)) + new_line[::-1]
        new_tiles.extend([t for t in new_line if t])

    return new_tiles, moved, score


def can_move(tiles):
    grid = get_grid(tiles)

    # 检查是否有空格
    if any(any(cell is None for cell in row) for row in grid):
        return True

    # 检查是否有相邻相同数字
    for r in range(ROWS):
        for c in range(COLS):
            if r < ROWS - 1 and grid[r][c] and grid[r + 1][c] and grid[r][c].value == grid[r + 1][c].value:
                return True
            if c < COLS - 1 and grid[r][c] and grid[r][c + 1] and grid[r][c].value == grid[r][c + 1].value:
                return True
    return False


def draw_game_info(window, score, high_score):
    pygame.draw.rect(window, (187, 173, 160), (0, 0, WIDTH, 150))

    # 绘制游戏标题
    title = MEDIUM_FONT.render("2048游戏", True, (255, 255, 255))
    window.blit(title, (20, 10))

    # 绘制版权信息
    copyright = SMALL_FONT.render("版权: WCY", True, (255, 255, 255))
    window.blit(copyright, (20, 60))

    # 绘制提示标语
    notice = SMALL_FONT.render("未成年儿童请在父母陪同下游戏", True, (255, 255, 255))
    window.blit(notice, (WIDTH - notice.get_width() - 20, 10))

    health = SMALL_FONT.render("适当游戏有益身体健康", True, (255, 255, 255))
    window.blit(health, (WIDTH - health.get_width() - 20, 50))

    # 绘制分数
    score_text = SMALL_FONT.render(f"当前分数: {score}", True, (255, 255, 255))
    window.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, 100))

    high_score_text = SMALL_FONT.render(f"最高分: {high_score}", True, (255, 255, 255))
    window.blit(high_score_text, (WIDTH // 2 - high_score_text.get_width() // 2, 130))


def show_start_animation():
    WINDOW.fill(BACKGROUND_COLOR)

    title = LARGE_FONT.render("2048游戏", True, (119, 110, 101))
    WINDOW.blit(title, (WIDTH // 2 - title.get_width() // 2, HEIGHT // 2 - 100))

    copyright = MEDIUM_FONT.render("版权: WCY", True, (119, 110, 101))
    WINDOW.blit(copyright, (WIDTH // 2 - copyright.get_width() // 2, HEIGHT // 2))

    notice = SMALL_FONT.render("未成年儿童请在父母陪同下游戏", True, (119, 110, 101))
    WINDOW.blit(notice, (WIDTH // 2 - notice.get_width() // 2, HEIGHT // 2 + 70))

    health = SMALL_FONT.render("适当游戏有益身体健康", True, (119, 110, 101))
    WINDOW.blit(health, (WIDTH // 2 - health.get_width() // 2, HEIGHT // 2 + 110))

    pygame.display.update()
    time.sleep(2)

    for i in range(3, 0, -1):
        WINDOW.fill(BACKGROUND_COLOR)
        text = LARGE_FONT.render(f"游戏即将开始: {i}", True, (119, 110, 101))
        WINDOW.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT // 2 - text.get_height() // 2))
        pygame.display.update()
        time.sleep(1)


def show_game_over(score, high_score):
    WINDOW.fill(BACKGROUND_COLOR)

    game_over = LARGE_FONT.render("游戏结束!", True, (255, 0, 0))
    WINDOW.blit(game_over, (WIDTH // 2 - game_over.get_width() // 2, HEIGHT // 2 - 150))

    good = MEDIUM_FONT.render("棒棒哒!", True, (255, 215, 0))
    WINDOW.blit(good, (WIDTH // 2 - good.get_width() // 2, HEIGHT // 2 - 70))

    score_text = FONT.render(f"最终分数: {score}", True, (119, 110, 101))
    WINDOW.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2))

    high_score_text = FONT.render(f"最高分: {high_score}", True, (119, 110, 101))
    WINDOW.blit(high_score_text, (WIDTH // 2 - high_score_text.get_width() // 2, HEIGHT // 2 + 70))

    restart = SMALL_FONT.render("按R键重新开始", True, (119, 110, 101))
    WINDOW.blit(restart, (WIDTH // 2 - restart.get_width() // 2, HEIGHT // 2 + 150))

    quit_text = SMALL_FONT.render("按ESC键退出", True, (119, 110, 101))
    WINDOW.blit(quit_text, (WIDTH // 2 - quit_text.get_width() // 2, HEIGHT // 2 + 190))

    pygame.display.update()


def main():
    clock = pygame.time.Clock()
    high_score = 0

    while True:  # 主游戏循环
        show_start_animation()

        # 初始化游戏
        tiles = [Tile(2, row, col) for row, col in [(0, 0), (0, 1), (1, 0), (1, 1)]]
        score = 0
        running = True

        while running:  # 游戏运行循环
            clock.tick(FPS)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.KEYDOWN:
                    moved = False
                    if event.key == pygame.K_LEFT:
                        tiles, moved, score = move_left(tiles, score)
                    elif event.key == pygame.K_RIGHT:
                        tiles, moved, score = move_right(tiles, score)
                    elif event.key == pygame.K_UP:
                        tiles, moved, score = move_up(tiles, score)
                    elif event.key == pygame.K_DOWN:
                        tiles, moved, score = move_down(tiles, score)
                    elif event.key == pygame.K_ESCAPE:
                        running = False

                    if moved:
                        if new_tile := spawn_random_tile(tiles):
                            tiles.append(new_tile)
                        high_score = max(score, high_score)
                        if not can_move(tiles):
                            show_game_over(score, high_score)
                            running = False

            # 绘制游戏
            WINDOW.fill(BACKGROUND_COLOR)
            draw_game_info(WINDOW, score, high_score)

            # 绘制网格
            for i in range(ROWS + 1):
                pygame.draw.line(WINDOW, OUTLINE_COLOR,
                                 (0, 150 + i * RECT_HEIGHT),
                                 (WIDTH, 150 + i * RECT_HEIGHT),
                                 OUTLINE_THICKNESS)
            for i in range(COLS + 1):
                pygame.draw.line(WINDOW, OUTLINE_COLOR,
                                 (i * RECT_WIDTH, 150),
                                 (i * RECT_WIDTH, HEIGHT),
                                 OUTLINE_THICKNESS)

            # 绘制方块
            for tile in tiles:
                tile.draw(WINDOW)

            pygame.display.update()

        # 游戏结束后的处理
        waiting = True
        while waiting:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        waiting = False
                    elif event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit()


if __name__ == "__main__":
    main()

运行代码:


视频链接:https://www.bilibili.com/video/BV1DsTCz6E85/?vd_source=2c5e9589d21407843e86fe44c3704667

三、实验中遇到的问题和解决方法

1.颜色的获取和如何构建色块
解决方法:去B站学习。
2.pygame安装问题
解决方法:询问AI后选择清华大学的镜像加速下载
3.文字无法正常显示
解决方法:调取系统文字
(以上问题的具体解决过程在第二部分已详细说明)

四、参考资料

《零基础学Python》
B站相关视频

五、实验感悟

实验的灵感来自于中学在学校无聊时经常用电话手表玩的小游戏:2048。说实话,刚开始可谓毫无头绪,可以说要将想法和代码的编写统一实现是一件困难的事情,于是在B站上找到了一系列的制作简单游戏的视频,从推箱子,贪吃蛇,飞机大战等经典游戏的学习中不断体悟编写游戏的过程,即拆分一个个过程,由简单渐渐深入,不好高骛远。这给我带来了极大的启发。于是,我决定从简单入手,先用最简单的控制台界面,了解运行的过程,如两数相加的条件即两数相等,数字随机位置如何生成等等,在了解代码基本逻辑后,便自然的向更深层次进发。我开始学习构建图形化界面,画网格,画色块,实际操作的时候总是比视频上看到的要难得多,在经过不断的试错,询问大模型,才最后写出了一个简单的游戏,可见,python的学习真的不是一蹴而就的,还是需要源源不断的学习和练习。

六、课程感悟

时光就这样悄悄地从指尖溜走,一学期的python学习落下了帷幕,留下指尖敲打代码的声音依然回响于耳。不敢想,不敢想,学习的过程竟然可以如此生动有趣,不曾想,不曾想,节课的瞬间,喜悦的心情却夹杂了大量不舍。初印象,高贵的世界第一计算机语言:python大王!小弟膜拜膜拜,不由心生向往,同时带来几分胆怯,然而,王老师的教学让我打开心扉,轻松的课堂氛围让我更加自由的查找课上不清楚的内容,进一步学会它,当然,偶尔会带来几分小刺激,课上的随机提问让我胆战心惊,清楚记得有一次被老师抽到,叫上去猜拳,说输的就“挂”,一时担惊受怕,好在有惊无险,老师只是在开玩笑,经过这件事后让我更加体到了老师的幽默风趣。渐渐地,我体会到了python语言的简洁和强大,给了我好好学习python的决心,实现代码的过程纵然困难重重,但程序运行成功的喜悦绝非其可比拟!如果说,我对python课还有遗憾的话,那一定是最后一节课一直抢答,然而一次也没有抢到了,正是“人生长恨水长东”。不过,正如王老师写到“人生苦短,我用python”,只要心中有梦,遗憾也能交织成画卷。愿在接下来的大学时光里一直阳光,一直进取,不断进步。最后,感谢王老师的辛勤教学,完结!撒花!!!

posted @ 2025-06-09 19:34  manurios  阅读(19)  评论(0)    收藏  举报