- 人工智能创作
AI辅助程序设计与开发
- 2025-1-12 19:22:25 @
借助AI辅助创作程序,先说明你想创作程序的功能,并将每次提示词记录整理。运行调试你的作品,不断修改,将作品的最终窗口截图,以及代码提交。
提示:如果需要安装外部库可以使用下面代码在命令行中安装,pip install -i https://mirrors.aliyun.com/pypi/simple 库名
AI工具的选择:可以自选当下通用的AI大模型,也可以选择专门辅助代码生成的AI模型,也可以选择齐洪老师的API:红旗AI助手。
讨论提交可以参考如下格式。
一、作品名称:班级抽奖小程序
二、作品主要功能:
(1)可以从txt中选择抽奖名单;(2)可以设置获奖数量;(3)开始后名单在屏幕上滚动;(4)结束时显示获奖的名单;(5)已经获奖的人员不再参加下一轮抽奖。
三、AI创作提示词变化:
- 使用python tkinter开发一个抽奖小程序:1.可以从Excel中选择抽奖名单;2.可以设置获奖数量;3.开始后名单在屏幕上滚动;4.结束时显示获奖的名单;5.已经获奖的人员不再参加下一轮抽奖。
- 选择名单文件时显示:加载名单失败,'str' object has no attribute value
- 重新修改程序,在txt中读取抽奖名单 一行一个
- 修改成,点击开始抽奖,tkinter界面中就滚动名单,当点击结束抽奖时,停止滚动,显示抽奖的名单。
- 按钮颜色再重新修改美观大气。整体布局修改会左右布局,滚动和获奖名单放在右边。
- 获奖名单的框,宽度变小,长度变大,界面和按钮的背景颜色修改为无。
- 将标题修改为:昆一中西山学校科技班抽奖程序。
四、作品主要截图 (alt+PrtScreen键)
五、作品的代码:
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import random
import time
class LotteryApp:
def __init__(self, root):
self.root = root
self.root.title("抽奖小程序")
self.root.geometry("1200x600") # 设置窗口大小
self.root.configure(bg="#FFFAFA") # 设置窗口背景色
self.participants = []
self.winners = []
self.winner_count = 0
self.prize = ""
self.is_rolling = False
# 创建界面元素
self.create_widgets()
def create_widgets(self):
# 创建标题
title_label = tk.Label(self.root, text="昆一中西山学校科技班抽奖程序", font=("Arial", 24, "bold"), bg="#FFFAFA", fg="#FF6347")
title_label.pack(pady=20)
# 创建整体布局
main_frame = tk.Frame(self.root, bg="#FFFAFA")
main_frame.pack(expand=True)
# 创建左侧布局
left_frame = tk.Frame(main_frame, bg="#FFFAFA")
left_frame.pack(side=tk.LEFT, padx=20, pady=20)
# 创建选择名单文件按钮
self.choose_file_button = tk.Button(left_frame, text="选择名单文件", command=self.choose_file, font=("Arial", 14), bg="#FF6347", fg="white")
self.choose_file_button.pack(pady=10)
# 创建设置奖项输入框
self.prize_label = tk.Label(left_frame, text="奖项:", font=("Arial", 14), bg="#FFFAFA")
self.prize_label.pack()
self.prize_entry = tk.Entry(left_frame, font=("Arial", 14))
self.prize_entry.pack()
# 创建设置获奖数量输入框
self.winner_count_label = tk.Label(left_frame, text="获奖数量:", font=("Arial", 14), bg="#FFFAFA")
self.winner_count_label.pack()
self.winner_count_entry = tk.Entry(left_frame, font=("Arial", 14))
self.winner_count_entry.pack()
# 创建开始抽奖按钮
self.start_lottery_button = tk.Button(left_frame, text="开始抽奖", command=self.start_lottery, font=("Arial", 14), bg="#FF6347", fg="white")
self.start_lottery_button.pack(pady=10)
# 创建结束抽奖按钮
self.end_lottery_button = tk.Button(left_frame, text="结束抽奖", command=self.end_lottery, state=tk.DISABLED, font=("Arial", 14), bg="#FF6347", fg="white")
self.end_lottery_button.pack(pady=10)
# 创建右侧布局
right_frame = tk.Frame(main_frame, bg="#FFFAFA")
right_frame.pack(side=tk.RIGHT, padx=20, pady=20)
# 创建显示滚动名单的标签
self.rolling_label = tk.Label(right_frame, text="", font=("Arial", 24), fg="red", bg="#FFFAFA")
self.rolling_label.pack(pady=20)
# 创建显示奖项和获奖名单的文本框
self.prize_winners_text = tk.Text(right_frame, height=20, width=50, font=("Arial", 14), bg="#FFFAFA", fg="black")
self.prize_winners_text.pack()
def choose_file(self):
# 打开文件选择对话框,选择文本文件
file_path = filedialog.askopenfilename(filetypes=[("文本文件", "*.txt")])
if file_path:
try:
# 读取文本文件中的名单
with open(file_path, 'r', encoding='utf-8') as file:
self.participants = [line.strip() for line in file if line.strip()]
messagebox.showinfo("提示", "名单加载成功!")
except Exception as e:
messagebox.showerror("错误", f"加载名单失败: {e}")
def start_lottery(self):
# 获取奖项
self.prize = self.prize_entry.get()
if not self.prize:
messagebox.showerror("错误", "奖项不能为空")
return
# 获取获奖数量
try:
self.winner_count = int(self.winner_count_entry.get())
if self.winner_count <= 0:
raise ValueError("获奖数量必须大于0")
except ValueError as e:
messagebox.showerror("错误", f"无效的获奖数量: {e}")
return
# 检查是否有足够的参与者
if len(self.participants) < self.winner_count:
messagebox.showerror("错误", "参与者数量不足")
return
# 开始抽奖
self.is_rolling = True
self.start_lottery_button.config(state=tk.DISABLED)
self.end_lottery_button.config(state=tk.NORMAL)
self.roll_participants()
def roll_participants(self):
if self.is_rolling:
random.shuffle(self.participants)
self.rolling_label.config(text=random.choice(self.participants))
self.root.after(50, self.roll_participants)
def end_lottery(self):
# 结束抽奖
self.is_rolling = False
self.start_lottery_button.config(state=tk.NORMAL)
self.end_lottery_button.config(state=tk.DISABLED)
self.rolling_label.config(text="")
self.choose_winners()
self.update_winners_text()
def choose_winners(self):
# 选择获奖者
self.winners = random.sample(self.participants, self.winner_count)
self.participants = [participant for participant in self.participants if participant not in self.winners]
def update_winners_text(self):
# 更新显示奖项和获奖名单的文本框
self.prize_winners_text.delete("1.0", tk.END)
self.prize_winners_text.insert(tk.END, f"{self.prize}:\n", "prize")
for winner in self.winners:
self.prize_winners_text.insert(tk.END, winner + "\n", "winner")
self.prize_winners_text.tag_config("prize", foreground="blue", font=("Arial", 16, "bold"), justify="center")
self.prize_winners_text.tag_config("winner", foreground="red", font=("Arial", 16, "bold"), justify="center")
self.prize_winners_text.tag_add("prize", "1.0", "1.end")
self.prize_winners_text.tag_add("winner", "2.0", tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = LotteryApp(root)
root.mainloop()
六、你对AI辅助代码编写的思考:
(结合自己实践写不少于100字的思考)
53 条评论
-
kyxscy2023028 LV 1 @ 2025-1-13 14:03:25已修改
作品名称:错题本; 主要功能:1.记录各个学科的错题;2.可以修改错题。 AI提示词的变化:1.生成一个问题记录器; 2.tkinter界面; 3.设置结束按钮; 4.添加结束时鼓励的话; 5.增大页面,将背景改为蓝色; 6.增加问题回看功能和按钮; 7.在问题回看页面加入问题修改功能; 8.改为可以选择修改问题; 9.增加选择删除问题功能; 10.选择问题学科分类; 11.每个学科设置不同的背景。
作品主要截图:
主要代码: import tkinter as tk from tkinter import messagebox, Text, StringVar, OptionMenu, filedialog
def start_page(): start_window = tk.Toplevel(root) start_window.title("欢迎使用错题本") start_window.geometry("400x300") start_window.configure(bg='blue')
label = tk.Label(start_window, text="欢迎使用错题本系统!", bg='blue', fg='white', font=("Arial", 16)) label.pack(pady=50) start_button = tk.Button(start_window, text="开始使用", command=lambda: (start_window.destroy(), root.deiconify())) start_button.pack(pady=20)
def save_question_answer(): subject = var_subject.get() question = entry_question.get() answer = entry_answer.get() if not subject or not question or not answer: messagebox.showwarning("警告", "学科、错题和正确答案都不能为空!") return try: with open(f'{subject}_question_answers.txt', 'a', encoding='utf-8') as file: file.write(f"问题:{question}\n回答:{answer}\n\n") entry_question.delete(0, tk.END) entry_answer.delete(0, tk.END) messagebox.showinfo("提示", "错题和正确答案已成功保存!") update_statistics(subject) except Exception as e: messagebox.showerror("错误", f"保存时发生错误: {str(e)}")
def close_window(): encouragement = "感谢使用错题本!希望你在学习的道路上不断进步,取得更好的成绩!" messagebox.showinfo("结束提示", encouragement) root.destroy()
def view_wrong_questions(): subject = var_subject.get() try: with open(f'{subject}_question_answers.txt', 'r', encoding='utf-8') as file: content = file.read() view_window = tk.Toplevel(root) view_window.title(f"查看{subject}错题") view_window.configure(bg='blue') view_window.geometry("600x400")
text_widget = Text(view_window) text_widget.pack(fill=tk.BOTH, expand=True) # 为每个错题添加序号 lines = content.split('\n') numbered_content = '' for i in range(0, len(lines), 3): index = i // 3 + 1 question = lines[i] if i < len(lines) else '' answer = lines[i + 1] if i + 1 < len(lines) else '' numbered_content += f"{index}. 问题:{question}\n答案:{answer}\n\n" text_widget.insert(tk.END, numbered_content) text_widget.config(state=tk.DISABLED) def modify_question(): current_text = text_widget.get(1.0, tk.END) lines = current_text.split('\n') questions = [] for i in range(0, len(lines), 3): question = lines[i] if i < len(lines) else '' # 包含序号 questions.append(question) select_window = tk.Toplevel(view_window) select_window.title(f"选择{subject}错题") select_window.configure(bg='blue') select_window.geometry("300x200") var = tk.StringVar(select_window) var.set(questions[0] if questions else '') option_menu = tk.OptionMenu(select_window, var, *questions) option_menu.pack(pady=10) def confirm_selection(): selected_question = var.get() index = 0 for i in range(0, len(lines), 3): if lines[i] == selected_question: # 比较完整的问题行 index = i // 3 # 计算问题的序号 question = lines[i][4:] # 去掉序号 answer = lines[i + 1][4:] # 去掉序号 modify_top = tk.Toplevel(select_window) modify_top.title(f"修改{subject}错题") modify_top.configure(bg='blue') modify_top.geometry("400x200") q_label = tk.Label(modify_top, text=f"{index + 1}. 错题:") q_label.pack(pady=5) q_entry = tk.Entry(modify_top, width=50) q_entry.pack(pady=5) q_entry.insert(0, question) a_label = tk.Label(modify_top, text="正确答案:") a_label.pack(pady=5) a_entry = tk.Entry(modify_top, width=50) a_entry.pack(pady=5) a_entry.insert(0, answer) def save_modified(): new_question = q_entry.get() new_answer = a_entry.get() if not new_question or not new_answer: messagebox.showwarning("警告", "错题和正确答案都不能为空!") return lines[i] = f"{index + 1}. 问题:{new_question}" # 保留序号 lines[i + 1] = f"答案:{new_answer}" new_content = '\n'.join(lines) with open(f'{subject}_question_answers.txt', 'w', encoding='utf-8') as f: f.write(new_content) update_text_widget(subject) modify_top.destroy() select_window.destroy() update_statistics(subject) save_button = tk.Button(modify_top, text="保存修改", command=save_modified) save_button.pack(pady=10) break confirm_button = tk.Button(select_window, text="确认选择", command=confirm_selection) confirm_button.pack(pady=10) def delete_question(): current_text = text_widget.get(1.0, tk.END) lines = current_text.split('\n') questions = [] for i in range(0, len(lines), 3): question = lines[i] if i < len(lines) else '' # 包含序号 questions.append(question) delete_window = tk.Toplevel(view_window) delete_window.title(f"选择要删除的{subject}错题") delete_window.configure(bg='blue') delete_window.geometry("300x200") var = tk.StringVar(delete_window) var.set(questions[0] if questions else '') option_menu = tk.OptionMenu(delete_window, var, *questions) option_menu.pack(pady=10) def confirm_deletion(): selected_question = var.get() new_lines = [] for i in range(0, len(lines), 3): if lines[i]!= selected_question: new_lines.append(lines[i]) # 只添加不删除的问题行 new_lines.append(lines[i + 1]) # 只添加不删除的答案行 new_lines.append('') # 添加空行 new_content = '\n'.join(new_lines) with open(f'{subject}_question_answers.txt', 'w', encoding='utf-8') as f: f.write(new_content) update_text_widget(subject) delete_window.destroy() update_statistics(subject) confirm_button = tk.Button(delete_window, text="确认删除", command=confirm_deletion) confirm_button.pack(pady=10) def show_all_questions(): all_questions_window = tk.Toplevel(view_window) all_questions_window.title(f"所有{subject}错题") all_questions_window.configure(bg='blue') all_questions_window.geometry("400x300") all_text = Text(all_questions_window) all_text.pack(fill=tk.BOTH, expand=True) all_text.insert(tk.END, numbered_content) all_text.config(state=tk.DISABLED) def show_by_index(): index_window = tk.Toplevel(view_window) index_window.title(f"按序号查看{subject}错题") index_window.configure(bg='blue') index_window.geometry("300x200") index_label = tk.Label(index_window, text="请输入错题序号:") index_label.pack(pady=10) index_entry = tk.Entry(index_window) index_entry.pack(pady=10) def show_question_by_index(): try: index = int(index_entry.get()) - 1 lines = numbered_content.split('\n') question_index = index * 3 if 0 <= question_index < len(lines): question = lines[question_index][4:] answer_index = question_index + 1 answer = lines[answer_index][4:] question_window = tk.Toplevel(index_window) question_window.title(f"{subject}错题 {index + 1}") question_window.configure(bg='blue') question_window.geometry("400x200") q_label = tk.Label(question_window, text=f"错题:") q_label.pack(pady=5) q_text = tk.Text(question_window, height=5, width=50) q_text.pack(pady=5) q_text.insert(tk.END, question) q_text.config(state=tk.DISABLED) a_label = tk.Label(question_window, text="正确答案:") a_label.pack(pady=5) a_text = tk.Text(question_window, height=5, width=50) a_text.pack(pady=5) a_text.insert(tk.END, answer) a_text.config(state=tk.DISABLED) else: messagebox.showwarning("警告", "输入的序号无效!") except ValueError: messagebox.showwarning("警告", "请输入有效的数字!") show_button = tk.Button(index_window, text="查看错题", command=show_question_by_index) show_button.pack(pady=10) modify_button = tk.Button(view_window, text="修改错题", command=modify_question) modify_button.pack(pady=10) delete_button = tk.Button(view_window, text="删除错题", command=delete_question) delete_button.pack(pady=10) show_all_button = tk.Button(view_window, text="显示全部错题", command=show_all_questions) show_all_button.pack(pady=10) show_by_index_button = tk.Button(view_window, text="按序号查看错题", command=show_by_index) show_by_index_button.pack(pady=10) except FileNotFoundError: messagebox.showinfo("提示", f"还没有记录任何{subject}错题。")
def update_statistics(subject): try: with open(f'{subject}_question_answers.txt', 'r', encoding='utf-8') as file: content = file.read() lines = content.split('\n') num_questions = len(lines) // 3 label_statistics.config(text=f"{subject}错题数量: {num_questions}") except FileNotFoundError: # 当文件不存在时,创建文件并更新统计信息 with open(f'{subject}_question_answers.txt', 'w', encoding='utf-8') as file: pass label_statistics.config(text=f"{subject}错题数量: 0")
def show_statistics(): stats_window = tk.Toplevel(root) stats_window.title("错题统计") stats_window.geometry("400x300") stats_window.configure(bg='blue') stats_text = Text(stats_window) stats_text.pack(fill=tk.BOTH, expand=True) stats_text.config(state=tk.DISABLED) stats = [] for subject in subjects: try: with open(f'{subject}_question_answers.txt', 'r', encoding='utf-8') as file: content = file.read() lines = content.split('\n') num_questions = len(lines) // 3 stats.append(f"{subject}: {num_questions} 个错题") except FileNotFoundError: # 处理文件不存在的情况,添加相应的统计信息 stats.append(f"{subject}: 0 个错题") stats_text.config(state=tk.NORMAL) stats_text.insert(tk.END, "\n".join(stats)) stats_text.config(state=tk.DISABLED)
def update_text_widget(subject): try: with open(f'{subject}_question_answers.txt', 'r', encoding='utf-8') as file: content = file.read() view_window = None for child in root.winfo_children(): if isinstance(child, tk.Toplevel) and child.title() == f"查看{subject}错题": view_window = child break if view_window: text_widget = view_window.children['!text'] text_widget.config(state=tk.NORMAL) text_widget.delete(1.0, tk.END) lines = content.split('\n') numbered_content = '' for i in range(0, len(lines), 3): index = i // 3 + 1 question = lines[i] if i < len(lines) else '' answer = lines[i + 1] if i + 1 < len(lines) else '' numbered_content += f"{index}. 问题:{question}\n答案:{answer}\n\n" text_widget.insert(tk.END, numbered_content) text_widget.config(state=tk.DISABLED) except FileNotFoundError: pass
def select_txt_file(): file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")]) # 选择.txt文件 if file_path: subject = file_path.split('/')[-1].split('.')[0] # 提取文件名作为学科名称 var_subject.set(subject) try: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() entry_question.delete(0, tk.END) entry_answer.delete(0, tk.END) lines = content.split('\n') if len(lines) >= 2: entry_question.insert(0, lines[0][4:]) # 提取问题 entry_answer.insert(0, lines[1][4:]) # 提取答案 except Exception as e: messagebox.showerror("错误", f"读取文件时发生错误: {str(e)}")
root = tk.Tk() root.withdraw() start_page()
root.title("错题本") root.geometry("600x400") root.configure(bg='blue') 学科选择部分 label_subject = tk.Label(root, text="学科:", bg='blue', fg='white') label_subject.pack(pady=5) subjects = ["数学", "语文", "英语", "物理", "化学", "生物", "历史", "地理", "政治"] var_subject = StringVar(root) var_subject.set(subjects[0]) option_menu_subject = OptionMenu(root, var_subject, *subjects) option_menu_subject.pack(pady=5)
label_question = tk.Label(root, text="错题:", bg='blue', fg='white') label_question.pack(pady=5)
entry_question = tk.Entry(root, width=50) entry_question.pack(pady=5)
label_answer = tk.Label(root, text="正确答案:", bg='blue', fg='white') label_answer.pack(pady=5)
entry_answer = tk.Entry(root, width=50) entry_answer.pack(pady=5)
save_button = tk.Button(root, text="保存", command=save_question_answer, bg='white', fg='black') save_button.pack(pady=10)
end_button = tk.Button(root, text="结束", command=close_window, bg='white', fg='black') end_button.pack(pady=10)
view_button = tk.Button(root, text="查看错题", command=view_wrong_questions, bg='white', fg='black') view_button.pack(pady=10)
stats_button = tk.Button(root, text="查看统计", command=show_statistics, bg='white', fg='black') stats_button.pack(pady=10)
label_statistics = tk.Label(root, text="", bg='blue', fg='white') label_statistics.pack(pady=5)
select_file_button = tk.Button(root, text="选择文件", command=select_txt_file, bg='white', fg='black') # 新增按钮 select_file_button.pack(pady=10)
update_statistics(subjects[0])
root.mainloop()
使用AI辅助代码编写的感想: 它提升了我们写代码的效率,方便了我们在工作量,时间短的工作中提升时间。当遇到瓶颈时也可以方便我们答疑解惑。大大减轻工作负担。
-
2025-1-13 13:27:49@
一、作品名称:苏联方块小游戏(新春四字词语版)
二、作品主要功能:
(1)左右键控制方块左右移动(2)上键控制方块旋转(3)填满一行会消失一行,并加100分
三、AI创作提示词变化:
-
-
-
-
-
- 写一个俄罗斯方块小游戏
-
-
-
-
不会下落下一个方块了,而且最底部的方块仍可以移动请改进一下
填满一行的方块不会消失请改进一下
最下面一行还是不能消除,请改进一下
让每个小正方形上有一个字,四个正方形组成的图形正好是一个四字词语
按上键后会报错请改进一下
新的代码按上键还是会报错,而且按完上键后就不会下落了
按完上键后会出现以下报错:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\HUAWEI\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 1968, in call return self.func(*args) ^^^^^^^^^^^^^^^^ File "E:\114514.py", line 104, in handle_key_press self.rotate_shape() File "E:\114514.py", line 118, in rotate_shape self.draw_board() File "E:\114514.py", line 140, in draw_board phrase = self.phrase_map[tuple(map(tuple, self.current_shape))] ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: ((4, 4), (4, 0), (4, 0)) Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\HUAWEI\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 1968, in call return self.func(*args) ^^^^^^^^^^^^^^^^ File "C:\Users\HUAWEI\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py", line 862, in callit func(*args) File "E:\114514.py", line 93, in game_loop self.move_shape(0, 1) File "E:\114514.py", line 110, in move_shape self.draw_board() File "E:\114514.py", line 140, in draw_board phrase = self.phrase_map[tuple(map(tuple, self.current_shape))] ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ KeyError: ((4, 4), (4, 0), (4, 0))请改正一下
确定位置后的方块上的字不见了,请让他保留下来
四、作品主要截图
五、作品的代码:
import tkinter as tk from tkinter import messagebox import random # 游戏常量 WIDTH = 10 HEIGHT = 20 CELL_SIZE = 30 SHAPES = [ [[1, 1, 1], [0, 1, 0]], [[0, 2, 2], [2, 2, 0]], [[3, 3, 0], [0, 3, 3]], [[4, 0, 0], [4, 4, 4]], [[0, 0, 5], [5, 5, 5]], [[6, 6, 6, 6]], [[7, 7], [7, 7]] ] # 四字词语列表 PHRASES = [ "一帆风顺", "二龙戏珠", "三阳开泰", "四季平安", "五福临门", "六六大顺", "七星高照", "八方来财", "九九归一", "十全十美", "百事可乐", "千秋万代", "万事如意", "心想事成", "恭喜发财", "福星高照" ] class Tetris: def __init__(self, root): self.root = root self.root.title("俄罗斯方块") self.canvas = tk.Canvas(root, width=WIDTH * CELL_SIZE, height=HEIGHT * CELL_SIZE, bg='black') self.canvas.pack() self.board = [[0] * WIDTH for _ in range(HEIGHT)] self.board_text = [["" for _ in range(WIDTH)] for _ in range(HEIGHT)] self.current_shape = None self.next_shape = None self.shape_x = 0 self.shape_y = 0 self.game_over = False self.score = 0 self.phrase_map = self.create_phrase_map() self.spawn_shape() self.spawn_next_shape() self.draw_next_shape() self.root.bind('<Key>', self.handle_key_press) self.game_loop() def create_phrase_map(self): phrase_map = {} for shape in SHAPES: phrase = random.choice(PHRASES) for _ in range(4): shape_tuple = tuple(map(tuple, shape)) phrase_map[shape_tuple] = phrase shape = list(zip(*shape[::-1])) return phrase_map def spawn_shape(self): self.current_shape = self.next_shape if self.next_shape else random.choice(SHAPES) self.next_shape = random.choice(SHAPES) self.shape_x = WIDTH // 2 - len(self.current_shape[0]) // 2 self.shape_y = 0 if self.check_collision(): self.game_over = True messagebox.showinfo("游戏结束", f"你的得分是:{self.score}") self.root.destroy() self.draw_board() def spawn_next_shape(self): self.next_shape = random.choice(SHAPES) def draw_next_shape(self): next_canvas = tk.Canvas(self.root, width=4 * CELL_SIZE, height=4 * CELL_SIZE, bg='black') next_canvas.place(x=WIDTH * CELL_SIZE + 20, y=20) phrase = self.phrase_map[tuple(map(tuple, self.next_shape))] for y, row in enumerate(self.next_shape): for x, cell in enumerate(row): if cell: color = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta', 'orange'][cell] next_canvas.create_rectangle(x * CELL_SIZE, y * CELL_SIZE, (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE, fill=color, outline='white') if len(phrase) > 0: next_canvas.create_text(x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2, text=phrase[0], fill='white', font=('Arial', 10)) phrase = phrase[1:] def game_loop(self): if not self.game_over: self.move_shape(0, 1) self.root.after(500, self.game_loop) def handle_key_press(self, event): if event.keysym == 'Left': self.move_shape(-1, 0) elif event.keysym == 'Right': self.move_shape(1, 0) elif event.keysym == 'Down': self.move_shape(0, 1) elif event.keysym == 'Up': self.rotate_shape() def move_shape(self, dx, dy): if not self.check_collision(dx, dy): self.shape_x += dx self.shape_y += dy self.draw_board() elif dy == 1: self.lock_shape() def rotate_shape(self): rotated_shape = list(zip(*self.current_shape[::-1])) if not self.check_collision(0, 0, rotated_shape): self.current_shape = [list(row) for row in rotated_shape] self.draw_board() def check_collision(self, dx=0, dy=0, shape=None): shape = shape or self.current_shape for y, row in enumerate(shape): for x, cell in enumerate(row): try: if cell and (self.shape_y + y + dy >= HEIGHT or self.shape_x + x + dx < 0 or self.shape_x + x + dx >= WIDTH or self.board[self.shape_y + y + dy][self.shape_x + x + dx]): return True except IndexError: return True return False def draw_board(self): self.canvas.delete('all') for y, row in enumerate(self.board): for x, cell in enumerate(row): if cell: self.draw_cell(x, y, cell, self.board_text[y][x]) phrase = self.phrase_map[tuple(map(tuple, self.current_shape))] for y, row in enumerate(self.current_shape): for x, cell in enumerate(row): if cell: self.draw_cell(self.shape_x + x, self.shape_y + y, cell, phrase[0]) phrase = phrase[1:] def draw_cell(self, x, y, color_id, text=""): color = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta', 'orange'][color_id] self.canvas.create_rectangle(x * CELL_SIZE, y * CELL_SIZE, (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE, fill=color, outline='white') if text: self.canvas.create_text(x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2, text=text, fill='white', font=('Arial', 10)) def lock_shape(self): phrase = self.phrase_map[tuple(map(tuple, self.current_shape))] for y, row in enumerate(self.current_shape): for x, cell in enumerate(row): if cell: self.board[self.shape_y + y][self.shape_x + x] = cell self.board_text[self.shape_y + y][self.shape_x + x] = phrase[0] phrase = phrase[1:] self.clear_lines() self.spawn_shape() self.draw_next_shape() def clear_lines(self): lines_to_clear = [] # 用于记录需要清除的行索引 for i in range(HEIGHT - 1, -1, -1): if 0 not in self.board[i]: lines_to_clear.append(i) lines_cleared = len(lines_to_clear) if lines_cleared: # 根据记录的满行索引,从下往上删除满行 for index in sorted(lines_to_clear, reverse=True): del self.board[index] del self.board_text[index] # 在棋盘顶部插入相应数量的空白行 for _ in range(lines_cleared): self.board.insert(0, [0] * WIDTH) self.board_text.insert(0, [""] * WIDTH) self.score += lines_cleared * 100 self.draw_board() if __name__ == "__main__": root = tk.Tk() game = Tetris(root) root.mainloop()
六、你对AI辅助代码编写的思考: AI辅助代码编写提高了我的工作效率,不仅速度很快而且很专业,但有时会出现一些错误,需要我们进行测试并让他改正错误,这也许也是一种防止人们滥用AI的手段吧,总之我们要合理使用AI,将它当成一种工具而不是一种偷懒的机会。
👍 3 -
-
2025-1-13 11:44:31@
import tkinter as tk
摩斯密码表
MORSE_CODE_DICT = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ',': '--..--', '.': '.-.-.-', '?': '..--..', '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-','': '/' }
反向摩斯密码表
REVERSE_MORSE_CODE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()}
def convert_to_morse(): input_text = entry.get() output_text.delete(0, tk.END) morse_code = "" for char in input_text.upper(): if char in MORSE_CODE_DICT: morse_code += MORSE_CODE_DICT[char] + " " else: morse_code += char + " " output_text.insert(0, morse_code.strip())
def convert_from_morse(): input_text = entry.get() output_text.delete(0, tk.END) text = "" for code in input_text.split(): if code in REVERSE_MORSE_CODE_DICT: text += REVERSE_MORSE_CODE_DICT[code] else: text += code output_text.insert(0, text)
root = tk.Tk() root.title("中英文与摩斯密码转换程序") root.configure(bg='black')
输入框
entry = tk.Entry(root, bg='gray20', fg='white') entry.pack(pady=10)
转换按钮
convert_button = tk.Button(root, text="转换为摩斯密码", command=convert_to_morse, bg='gray40', fg='white') convert_button.pack(pady=5)
reverse_convert_button = tk.Button(root, text="从摩斯密码转换", command=convert_from_morse, bg='gray40', fg='white') reverse_convert_button.pack(pady=5)
输出框
output_text = tk.Entry(root, bg='gray20', fg='white') output_text.pack(pady=10)
root.mainloop()