25级数应四班第八次实验

2025010142 杨旭洁
用类来制作一个打boss的游戏,分为不同的boss,并标注他们的血量和伤害值
# 敌人父类
class Boss:
    def __init__(self, name, hp, attack):
        self.name = name
        self.hp = hp      # 血量
        self.attack = attack  # 攻击力

    # 受到伤害
    def take_damage(self, damage):
        self.hp -= damage
        if self.hp < 0:
            self.hp = 0
        print(f"{self.name} 受到 {damage} 点伤害,剩余血量:{self.hp}")

    # 敌人攻击
    def fight(self):
        print(f"{self.name} 发起攻击,伤害值:{self.attack}")

    # 判断是否死亡
    def is_dead(self):
        return self.hp <= 0

# 小Boss 子类
class SmallBoss(Boss):
    def __init__(self):
        super().__init__("小Boss", 150, 20)

# 中Boss 子类
class MidBoss(Boss):
    def __init__(self):
        super().__init__("中Boss", 400, 35)

# 大Boss 子类
class BigBoss(Boss):
    def __init__(self):
        super().__init__("大Boss", 900, 60)

# 测试运行
if __name__ == "__main__":
    print("===== BOSS 对战演示 =====")
    # 创建三个BOSS对象
    small = SmallBoss()
    mid = MidBoss()
    big = BigBoss()

    # 查看基础属性
    print(f"\n小Boss:血量{small.hp},攻击力{small.attack}")
    print(f"中Boss:血量{mid.hp},攻击力{mid.attack}")
    print(f"大Boss:血量{big.hp},攻击力{big.attack}")

    # 模拟攻击小Boss
    print("\n--- 攻击小Boss ---")
    small.take_damage(80)
    small.take_damage(90)
    if small.is_dead():
        print("小Boss 已阵亡")

    # 模拟攻击中Boss
    print("\n--- 攻击中Boss ---")
    mid.take_damage(180)
    mid.fight()

    # 模拟攻击大Boss
    print("\n--- 攻击大Boss ---")
    big.take_damage(300)
    big.take_damage(400)
    big.fight()
屏幕截图 2026-06-17 124840

 

 

 




 2025010146 顾芳菲

 连连看(基本)

import turtle

class LianLianKanLine:
    def __init__(self):
        # 初始化绘图环境
        self.win = turtle.Screen()
        self.win.title("连连看折线(类实现)")
        self.pen = turtle.Turtle()
        self.pen.hideturtle()
        self.pen.speed(0)
        self.pen.pensize(3)
        self.pen.pencolor("red")

    # 设置线条样式
    def set_line_style(self, color, width):
        self.pen.pencolor(color)
        self.pen.pensize(width)

    # 绘制两点直线(无拐点)
    def draw_straight(self, x1, y1, x2, y2):
        self.pen.penup()
        self.pen.goto(x1, y1)
        self.pen.pendown()
        self.pen.goto(x2, y2)

    # 绘制单拐点直角折线(L型,连连看常用)
    def draw_one_corner(self, start, mid, end):
        """
        start: 起点坐标 (x,y)
        mid: 拐点坐标 (x,y)
        end: 终点坐标 (x,y)
        """
        self.pen.penup()
        self.pen.goto(start)
        self.pen.pendown()
        self.pen.goto(mid)
        self.pen.goto(end)

    # 绘制双拐点直角折线(Z型,连连看最大转弯数)
    def draw_two_corner(self, p1, p2, p3, p4):
        self.pen.penup()
        self.pen.goto(p1)
        self.pen.pendown()
        self.pen.goto(p2)
        self.pen.goto(p3)
        self.pen.goto(p4)

    # 清空画布
    def clear_canvas(self):
        self.pen.clear()

    # 保持窗口
    def keep_window(self):
        turtle.done()

# 主程序调用
if __name__ == "__main__":
    # 实例化对象
    link = LianLKanLine()

    # 1. 绘制直线
    link.draw_straight(-300, 200, -100, 200)

    # 2. 绘制单拐点L型折线
    link.set_line_style(color="blue", width=3)
    link.draw_one_corner(start=(-300, 100), mid=(-300, 0), end=(-100, 0))

    # 3. 绘制双拐点折线
    link.set_line_style(color="green", width=3)
    link.draw_two_corner(p1=(100, 200), p2=(200, 200), p3=(200, 0), p4=(100, 0))

    link.keep_window()

屏幕截图 2026-06-17 132031

屏幕截图 2026-06-17 132044

 


2025010151侯益波
import tkinter as tk
import matplotlib.pyplot as plt
from collections import deque

# 存储坐标点
x_list = deque(maxlen=300)
y_list = deque(maxlen=300)

def mouse_track(event):
    # 保存鼠标坐标
    x_list.append(event.x)
    y_list.append(event.y)
    # 清空画布重绘轨迹
    canvas.delete("all")
    # 连线绘制轨迹
    if len(x_list) > 1:
        points = []
        for xi, yi in zip(x_list, y_list):
            points.append(xi)
            points.append(yi)
        canvas.create_line(points, fill="red", width=2)
    # 当前鼠标圆点
    canvas.create_oval(event.x-5, event.y-5, event.x+5, event.y+5, fill="blue")

# 窗口
win = tk.Tk()
win.title("鼠标轨迹追踪器")
canvas = tk.Canvas(win, bg="white", width=800, height=600)
canvas.pack()
canvas.bind("<Motion>", mouse_track)

# 导出轨迹图按钮
def save_plot():
    plt.rcParams["font.sans-serif"] = ["SimHei"]
    plt.figure(figsize=(8,6))
    plt.plot(x_list, y_list, c="red", linewidth=2, label="移动轨迹")
    plt.scatter(x_list[0], y_list[0], c="green", s=80, label="起点")
    plt.scatter(x_list[-1], y_list[-1], c="blue", s=80, label="终点")
    plt.gca().invert_yaxis()  # tk y轴向下,反转匹配视觉
    plt.title("鼠标运动轨迹图")
    plt.xlabel("X坐标")
    plt.ylabel("Y坐标")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.savefig("mouse_track.png", dpi=200)
    plt.show()

tk.Button(win, text="导出轨迹统计图", command=save_plot).pack(pady=5)
win.mainloop()

联想截图_20260617093503

 2025010153范鹏展

图片亮度的调节

from PIL import Image, ImageEnhance
import tkinter as tk

# 图片路径
img_path = r"C:\Users\34151\Desktop\图片1.png"
save_path = r"C:\Users\34151\Desktop\亮度调整结果.jpg"


root = tk.Tk()
root.title("方向键控制亮度")
root.geometry("500x200")

bright_factor = 1.0
step = 0.1
origin_img = Image.open(img_path)
# 处理PNG透明通道
if origin_img.mode == "RGBA":
    origin_img = origin_img.convert("RGB")

def refresh_save():
    global bright_factor
    bright_img = ImageEnhance.Brightness(origin_img).enhance(bright_factor)
    bright_img.save(save_path)
    tip_label.config(text=f"当前亮度:{bright_factor:.1f},图片已保存桌面")

# 上箭头变亮
def key_up(event):
    global bright_factor
    bright_factor += step
    refresh_save()

# 下箭头变暗
def key_down(event):
    global bright_factor
    bright_factor -= step
    if bright_factor < 0.1:
        bright_factor = 0.1
    refresh_save()

# 绑定上下方向键
root.bind("<Up>", key_up)
root.bind("<Down>", key_down)

# 文字提示
tip_label = tk.Label(root, text="激活窗口,按 ↑ 变亮  ↓ 变暗", font=("微软雅黑",14))
tip_label.pack(expand=True)

# 初始化保存
refresh_save()
root.mainloop()

屏幕截图 2026-06-17 100223

 

 

 

 

 

 

 

 

 

 

 

2025010160韩俊杰
机械臂防抖动
import numpy as np
import matplotlib.pyplot as plt

# ====================== 卡尔曼滤波器(消抖核心) ======================
class KalmanFilter:
    def __init__(self, Q=0.001, R=0.01):
        self.Q = Q      # 过程噪声:越小轨迹越平滑,响应越慢
        self.R = R      # 观测噪声
        self.P = 1.0
        self.X = 0.0

    def update(self, measure):
        # 预测
        X_pred = self.X
        P_pred = self.P + self.Q
        # 校正
        K = P_pred / (P_pred + self.R)
        self.X = X_pred + K * (measure - X_pred)
        self.P = (1 - K) * P_pred
        return self.X

# 为XYZ三轴分别创建独立滤波器
kf_x = KalmanFilter(Q=0.002, R=0.02)
kf_y = KalmanFilter(Q=0.002, R=0.02)
kf_z = KalmanFilter(Q=0.002, R=0.02)

# ====================== 模拟抖动坐标 + 滤波 + 可视化 ======================
if __name__ == "__main__":
    raw_x, raw_y, raw_z = 0.0, 0.0, 50.0

    # 记录数据用于绘图
    raw_x_list = []
    smooth_x_list = []
    steps = range(50)

    print("原始抖动坐标 | 滤波平滑后坐标")
    print("-"*45)

    for i in steps:
        # 模拟真实场景里剧烈抖动的原始点位(随机小幅跳变)
        raw_x += np.random.uniform(-0.9, 0.9)
        raw_y += np.random.uniform(-0.9, 0.9)

        # 滤波消抖
        smooth_x = kf_x.update(raw_x)
        smooth_y = kf_y.update(raw_y)
        smooth_z = kf_z.update(raw_z)

        # 记录数据
        raw_x_list.append(raw_x)
        smooth_x_list.append(smooth_x)

        # 打印对比效果
        print(f"X:{raw_x:6.2f} Y:{raw_y:6.2f} | X:{smooth_x:6.2f} Y:{smooth_y:6.2f}")

    # 绘制对比图
    plt.figure(figsize=(10, 5))
    plt.plot(steps, raw_x_list, color='r', label='原始抖动坐标', alpha=0.6)
    plt.plot(steps, smooth_x_list, color='b', label='滤波平滑后坐标', linewidth=2)
    plt.title('机械臂抖动消除效果对比(卡尔曼滤波)')
    plt.xlabel('步数')
    plt.ylabel('X轴坐标')
    plt.legend()
    plt.grid(True)
    plt.show()

屏幕截图 2026-06-17 131215

 2025010164李朋祖 三维建模

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 创建3D画布
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

# ---------------------- 1. 绘制立方体 ----------------------
def draw_cube(ox, oy, oz, size):
    # 8个顶点
    verts = np.array([
        [ox, oy, oz],
        [ox+size, oy, oz],
        [ox+size, oy+size, oz],
        [ox, oy+size, oz],
        [ox, oy, oz+size],
        [ox+size, oy, oz+size],
        [ox+size, oy+size, oz+size],
        [ox, oy+size, oz+size]
    ])
    # 12条棱
    edges = [
        [verts[0], verts[1]], [verts[1], verts[2]], [verts[2], verts[3]], [verts[3], verts[0]],
        [verts[4], verts[5]], [verts[5], verts[6]], [verts[6], verts[7]], [verts[7], verts[4]],
        [verts[0], verts[4]], [verts[1], verts[5]], [verts[2], verts[6]], [verts[3], verts[7]]
    ]
    for edge in edges:
        ax.plot3D(*zip(*edge), color="#2277dd", linewidth=2)

# 画立方体 原点(0,0,0) 边长2
draw_cube(0, 0, 0, 2)

# ---------------------- 2. 绘制球体 ----------------------
u = np.linspace(0, 2 * np.pi, 60)
v = np.linspace(0, np.pi, 60)
x = 1.5 * np.outer(np.cos(u), np.sin(v)) + 4
y = 1.5 * np.outer(np.sin(u), np.sin(v))
z = 1.5 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, color="#ff6666", alpha=0.7)

# ---------------------- 3. 绘制圆柱 ----------------------
theta = np.linspace(0, 2*np.pi, 50)
z_cyl = np.linspace(0, 3, 30)
theta, z_cyl = np.meshgrid(theta, z_cyl)
cx = np.cos(theta) + 0
cy = np.sin(theta) + 4
cz = z_cyl
ax.plot_surface(cx, cy, cz, color="#77dd77", alpha=0.7)

# 坐标轴设置
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Python 3D Modeling Demo (Cube + Sphere + Cylinder)")
plt.show()

屏幕截图 2026-06-17 133103

 

2025010168袁艺伦 植物大战僵尸静态场景
import pygame

# 初始化pygame
pygame.init()
# 窗口尺寸
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("植物大战僵尸 静态场景")

# 颜色定义
GRASS_GREEN = (102, 204, 102)
GRASS_DARK = (76, 153, 76)
BROWN = (139, 90, 43)
WHITE = (255, 255, 255)
SKY_BLUE = (135, 206, 235)
SUN_YELLOW = (255, 220, 0)

# 格子参数
cell_w = 100
cell_h = 80
row_num = 5
col_num = 9

# 绘制背景天空
screen.fill(SKY_BLUE)

# 绘制左上角阳光圆形(去掉文字渲染,消除字体报错)
pygame.draw.circle(screen, SUN_YELLOW, (60, 60), 30)

# 绘制草坪格子
start_x = 0
start_y = 120
for row in range(row_num):
    for col in range(col_num):
        x = start_x + col * cell_w
        y = start_y + row * cell_h
        # 交替深浅绿色格子
        if (row + col) % 2 == 0:
            pygame.draw.rect(screen, GRASS_GREEN, (x, y, cell_w, cell_h))
        else:
            pygame.draw.rect(screen, GRASS_DARK, (x, y, cell_w, cell_h))
        # 格子边框
        pygame.draw.rect(screen, BROWN, (x, y, cell_w, cell_h), 2)

# 绘制右侧僵尸道路空地
pygame.draw.rect(screen, (80, 60, 30), (WIDTH - 120, start_y, 120, row_num * cell_h))

# 绘制底部工具栏
pygame.draw.rect(screen, (60, 60, 60), (0, HEIGHT - 100, WIDTH, 100))
# 绘制植物卡槽
plant_slot_x = 20
for i in range(8):
    pygame.draw.rect(screen, (220, 220, 220), (plant_slot_x, HEIGHT - 90, 80, 80), 3)
    plant_slot_x += 100

# 刷新画面
pygame.display.flip()

# 保持窗口,关闭窗口退出循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

pygame.quit()

屏幕截图 2026-06-17 132707

 




2025010172 张景悦
图像拼接
from PIL import Image # 打开图片 img1 = Image.open("1.jpg") img2 = Image.open("2.jpg") img3 = Image.open("3.jpg") # 统一高度,计算画布尺寸 h = img1.height total_w = img1.width + img2.width + img3.width # 创建空白画布 new_img = Image.new("RGB", (total_w, h), color=(255,255,255)) # 拼接图片 new_img.paste(img1, (0, 0)) new_img.paste(img2, (img1.width, 0)) new_img.paste(img3, (img1.width+img2.width, 0)) # 保存+预览 new_img.save("横向拼接_图片.jpg") new_img.show()
微信图片_20260616233744_27_2

 

 

 


 杨云飞2025010173

微信小程序的游戏

import tkinter as tk
import random
import time

class MoleGame:
    def __init__(self, root):
        self.root = root
        self.root.title("Python打地鼠")
        self.canvas = tk.Canvas(root, width=600, height=400, bg="#333")
        self.canvas.pack()
        
        # 游戏参数
        self.score = 0
        self.time_left = 60
        self.hole_count = 5
        self.mole_size = 40
        self.current_mole = None
        
        # 创建UI
        self.create_widgets()
        self.create_holes()
        self.start_game()

    def create_widgets(self):
        # 得分显示
        self.score_label = tk.Label(self.root, text=f"得分:{self.score}", 
                                   fg="white", bg="#333", font=("Arial", 16))
        self.score_label.pack(pady=10)
        
        # 时间显示
        self.time_label = tk.Label(self.root, text=f"剩余时间:{self.time_left}", 
                                   fg="white", bg="#333", font=("Arial", 16))
        self.time_label.pack(pady=10)

    def create_holes(self):
        self.holes = []
        for i in range(self.hole_count):
            x = random.randint(50, 550)
            y = random.randint(50, 350)
            hole = self.canvas.create_oval(x-30, y-30, x+30, y+30, 
                                          fill="#999", outline="#666")
            self.holes.append(hole)
            self.canvas.tag_bind(hole, "<Button-1>", self.hit_mole)

    def start_game(self):
        self.spawn_mole()
        self.update_time()

    def spawn_mole(self):
        # 随机选择一个地洞
        hole = random.choice(self.holes)
        x1, y1, x2, y2 = self.canvas.coords(hole)
        center_x = (x1 + x2) // 2
        center_y = (y1 + y2) // 2
        
        # 显示地鼠
        if self.current_mole:
            self.canvas.delete(self.current_mole)
        self.current_mole = self.canvas.create_oval(
            center_x - self.mole_size, 
            center_y - self.mole_size, 
            center_x + self.mole_size, 
            center_y + self.mole_size,
            fill="yellow", outline="black"
        )
        
        # 定时消失并重新生成
        self.root.after(1000, self.spawn_mole)

    def hit_mole(self, event):
        if self.current_mole:
            # 检查点击位置是否在地鼠范围内
            x, y = event.x, event.y
            x1, y1, x2, y2 = self.canvas.coords(self.current_mole)
            if x1 <= x <= x2 and y1 <= y <= y2:
                self.score += 10
                self.score_label.config(text=f"得分:{self.score}")
                self.canvas.delete(self.current_mole)
                self.current_mole = None

    def update_time(self):
        if self.time_left > 0:
            self.time_left -= 1
            self.time_label.config(text=f"剩余时间:{self.time_left}")
            self.root.after(1000, self.update_time)
        else:
            self.game_over()

    def game_over(self):
        self.canvas.delete("all")
        self.canvas.create_text(300, 200, text=f"游戏结束!\n最终得分:{self.score}",
                               fill="white", font=("Arial", 24, "bold"))
        self.root.after(3000, self.root.destroy)

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("600x500")
    root.config(bg="#333")
    game = MoleGame(root)
    root.mainloop()

屏幕截图 2026-06-17 001626

 

posted @ 2026-06-17 21:10  szmtjs10  阅读(5)  评论(0)    收藏  举报