扫雷大作战
1]:if dx == 0 and dy == 0:continuenx, padx=20)# 难度显示self.diff_label = tk.Label(info_frame, 困难: []}if os.path.exists(self.rankings_file):try:with open(self.rankings_file。
text=选择难度, fill=tk.BOTH,width=15)difficulty_btn.pack(side=tk.LEFT,font=(Arial。
text='#128163;')self.game_over = Trueself.show_game_over(False)return# 更新按钮文本if self.board[y][x] 0:# 设置不同数字的颜色colors = ['blue',date: date})except (ValueError, *.flac))filename = filedialog.askopenfilename(title=选择音乐文件, 10, 'black', y))btn = self.buttons[y][x]btn.config(relief=tk.SUNKEN, self.height - 1)if self.board[y][x] != -1: # 如果不是地雷self.board[y][x] = -1 # -1表示地雷mines_placed += 1# 更新周围单元格的数字for dy in [-1, ny = x + dx,command=lambda d=difficulty: self.start_game(d)。
command=text_widget.yview)text_widget.configure(yscrollcommand=scrollbar.set)# 添加排名数据text_widget.insert(tk.END,command=self.control_music, padx=20)# 创建游戏网格框架grid_container = ttk.LabelFrame(self.main_frame, bg='#f0f0f0')else:# 标记self.flags.add((x。
filetypes=filetypes)if filename:self.music_file = filenameself.play_background_music()def show_start_screen(self):显示开始界面# 清除现有内容for widget in self.main_frame.winfo_children():widget.destroy()# 取消现有计时器if self.timer_id is not None:self.root.after_cancel(self.timer_id)self.timer_id = None# 标题title_label = tk.Label(self.main_frame,中等: {width: 16。
padx=0。
padx=20, 中等: [], 40))# 开始游戏按钮start_btn = ttk.Button(self.main_frame, y) in self.revealed:return# 添加到已揭示集合self.revealed.add((x, y))self.buttons[y][x] = btn# 设置网格权重, expand=True)# 游戏音乐 - 使用用户指定的路径self.music_file = None# 计时器IDself.timer_id = None# 游戏难度设置self.difficulties = {简单: {width: 9, x,text=时间: 0秒, 0, encoding='utf-8') as f:for difficulty, y=y: self.flag_cell(x, 600)# 创建游戏主框架self.main_frame = tk.Frame(self.root, 1]:for dx in [-1,width=20)ranking_btn.pack(pady=10)# 音乐控制按钮music_btn = ttk.Button(self.main_frame, encoding='utf-8') as f:current_difficulty = Nonefor line in f:line = line.strip()if not line:continue# 检查是否为难度标题行if line in rankings:current_difficulty = lineelif current_difficulty and line.startswith(排名):# 跳过表头行continueelif current_difficulty and line:# 解析数据行: 排名 | 姓名 | 用时 | 得分 | 日期parts = line.split('|')if len(parts) = 5:try:# 去除各部分的首尾空格cleaned_parts = [part.strip() for part in parts]# 提取数据 (跳过排名列,command=self.show_difficulty_selection,time: self.elapsed_time, ny = x + dx, bold),font=(Arial, 'green',bg='white')title_label.pack(pady=(20, x。
fg=#2c3e50, 'turquoise', height: 16,width=20)back_btn.pack(pady=20)def start_game(self, 0。
parent=self.root)if name:# 添加到排名if self.difficulty not in self.rankings:self.rankings[self.difficulty] = []self.rankings[self.difficulty].append({name: name,text=difficulty。
text=退出游戏, bg='#ffec8b')# 更新地雷计数器self.mines_label.config(text=f地雷: {self.mine_count - len(self.flags)})def update_timer(self):更新计时器if not self.game_over:self.elapsed_time = int(time.time() - self.start_time)self.time_label.config(text=f时间: {self.elapsed_time}秒)self.timer_id = self.root.after(1000,困难: {width: 24,command=self.root.quit, 1):f.write(f{i} | {record['name']} | {record['time']}秒 | {record['score']} | {record['date']}\n)f.write(\n) # 添加空行分隔不同难度except Exception as e:print(f保存排名时出错: {e})def play_background_music(self):播放背景音乐if self.music_file:try:# 尝试播放当前音乐pygame.mixer.music.load(self.music_file)pygame.mixer.music.play(-1) # -1表示循环播放except Exception as e:print(f播放音乐时出错: {e})def control_music(self):控制音乐播放if self.music_file:# 如果只有一首音乐, difficulty):开始游戏# 获取难度设置settings = self.difficulties[difficulty]width = settings[width]height = settings[height]mines = settings[mines]# 清除现有内容for widget in self.main_frame.winfo_children():widget.destroy()# 创建游戏顶部信息栏info_frame = tk.Frame(self.main_frame,borderwidth=1, y) in self.revealed:returnbtn = self.buttons[y][x]if (x。
'w',text=返回主菜单,width=20)start_btn.pack(pady=10)# 游戏排名按钮ranking_btn = ttk.Button(self.main_frame。
------------------------------------------------\n)# 添加排名数据for i, padx=10)# 开始计时self.update_timer()def create_board(self):创建游戏板并随机放置地雷# 初始化空白板self.board = [[0 for _ in range(self.width)] for _ in range(self.height)]# 放置地雷mines_placed = 0while mines_placed self.mine_count:x = random.randint(0, 暂无排名数据\n)text_widget.config(state=tk.DISABLED) # 设置为只读# 打包组件text_widget.pack(side=tk.LEFT,height=1。
borderwidth=2, 0,# 内边距pady=2# 内边距)grid_frame.pack(expand=True)# 初始化游戏状态self.difficulty = difficultyself.width = widthself.height = heightself.mine_count = minesself.flags = set()self.revealed = set()self.game_over = Falseself.start_time = time.time()self.elapsed_time = 0# 创建游戏板self.create_board()# 创建按钮网格self.buttons = [[None for _ in range(width)] for _ in range(height)]for y in range(height):for x in range(width):btn = tk.Button(grid_frame, text=difficulty)# 创建文本控件显示排名text_widget = tk.Text(frame。
weight=1)for i in range(height):grid_frame.rowconfigure(i, filedialogimport pygameimport randomimport osimport timefrom base64 import b64decodeICON_BASE64 = 'AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAHudAAB7nQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASzyQAEs8jwBLPI8ASzyPAEs8jwRLPI8BSz2PAEs8jwBLPI8ISzyPKks8j0hLPI9YSzyPWEs8j0dLPI8pSzyPB0s8jwBMPZAASzyPAUs8jwRLPI8ASzyPAEs8jwBMO44AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEs8jwBLPI8ASzyPAEs8jwJLPI8DSzyPAEs8jwZLPI9LSzyPoks8j9tLPI/4SzyP/0s8j/9LPI//SzyP/0s8j/hLPI/bSzyPoUs8j0lLPI8FSzyPAEs8jwNLPI8CSzyPAEs8jwBLPI8AAAAAAAAAAAAAAAAAAAAAAAAAAABLPI8ASzyPAEs8jwBLPI8CSzyPAkk8jwBLPI9vSzyP80s8j/9LPI/+SzyP+ks8j/lLPI/7SzyP/Eo7jvxKO478SzyP/Es8j/tLPI/5SzyP+ks8j/5LPI//SzyP8ks8j2xKPI4ASzyPAks8jwJLPI8ASzyPAEs9kAAAAAAAAAAAAAAAAABLPI8ASzyPAEs8jwBLPI8BSzyPA0s8jwBLPI8eSzyPlUs8j/BLPI//SzyP/ks8j/9LPI//Sz2P/0s9j/9LPI//SzyP/0s8j/5LPI//SzyP70s8j5NLPI8cSzyPAEs8jwNLPI8BSzyPAEs8jwBLPI8AAAAAAAAAAAAAAAAAAAAAAAAAAABLPJAASzyPAEs8jwBLPI8ASzyPA0s8jwFLPI8ASzyPFEs8j1tLPI+eSzyPy0s8j+NLPI/tSzyP7Us8j+NLPI/LSzyPnUs8j1pLPI8TSzyPAEs8jwFLPI8DSzyPAEs8jwBLPI8ASz2OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASzyPAEs8jwBLPI8ASzyPAks8jwRIPIoATD2QAEw+kABMPY8BSzyPDUs8jxlLPI8ZSzyPDUo+jgBKP48ASz6PAEs6jwBLPI8ESzyPAks8jwBLPI8ASzyPAAAAAAAAAAAAAAAAAAAAAAAAAAAA+hAIX/SAAS/pAACX1AAAK6gAABVQAAAKIAAABCAAAARAAAACQAAAAoAAAAGAAAABgAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAGAAAABgAAAAUAAAAJAAAACoAAABRAAAAhQAAAKqAAABdIAAEvpAACX9EACL/kIEJ8='# 初始化pygame音频 mixerpygame.mixer.init()class Minesweeper:扫雷游戏主类def __init__(self, y) in self.flags:# 取消标记self.flags.remove((x,command=self.show_difficulty_selection,bg='white')title_label.pack(pady=(40, 'r', 1]:if dx == 0 and dy == 0:continuenx, bg='#ffcccc')elif self.board[y][x] == -1 and (x, bg='white')scrollbar = ttk.Scrollbar(frame,text=返回主菜单,text=f难度: {difficulty}, padx=20, height: 9, bold), column=x, mines: 40,relief='solid')style.configure('GameArea.TLabelframe.Label'。
bg='white')notebook.add(frame, 1]:for dx in [-1, 14)。
f{i:4} {entry['name']:10} {entry['time']:4}秒 {entry['score']:8} {entry['date']:16}\n)else:text_widget.insert(tk.END, 'purple',font=(Arial, self.width - 1)y = random.randint(0, 'red', simpledialog, sticky='nsew')btn.bind(Button-3。
bg='white')self.mines_label.pack(side=tk.LEFT,因为它只是显示顺序)name = cleaned_parts[1]time_str = cleaned_parts[2].replace('秒'。
使按钮居中显示for i in range(width):grid_frame.columnconfigure(i,text=开始游戏,text=游戏排名,score: score, 1):text_widget.insert(tk.END, pady=0, expand=True)scrollbar.pack(side=tk.RIGHT, reverse=True)# 只保留前10名if len(self.rankings[self.difficulty]) 10:self.rankings[self.difficulty] = self.rankings[self.difficulty][:10]# 保存排名self.save_rankings()messagebox.showinfo(游戏胜利, (无损音乐, x=x, mines: 99, padx=10)# 重新选择难度difficulty_btn = ttk.Button(button_frame。
text=重新选择难度, 'bold'), ny)# 检查是否获胜if len(self.revealed) == self.width * self.height - self.mine_count:self.game_over = Trueself.show_game_over(True)def flag_cell(self。
command=self.show_start_screen, fill=tk.Y)# 返回按钮back_btn = ttk.Button(self.main_frame,text=扫雷游戏。
time: int(time_str), expand=True)# 添加样式style = ttk.Style()style.configure('GameArea.TLabelframe'。
bg='white')self.main_frame.pack(fill=tk.BOTH,。
lambda e, reverse=True)return rankingsdef save_rankings(self):保存排名数据到TXT文件try:with open(self.rankings_file,text=f地雷: {mines}, '')score_str = cleaned_parts[3]date = cleaned_parts[4]rankings[current_difficulty].append({name: name,text=播放/暂停BGM, weight: 0.6}}# 加载排名self.rankings_file = minesweeper_rankings.txtself.rankings = self.load_rankings()# 显示开始界面self.show_start_screen()self.set_icon()# 开始播放音乐self.play_background_music()def set_icon(self):icon_name = '.mine.ico'if not os.path.exists(icon_name):icon = open(icon_name, y=y: self.reveal_cell(x, bold), 'gray']btn.config(text=str(self.board[y][x])。
records in self.rankings.items():# 写入难度标题f.write(f{difficulty}\n)if not records:f.write(暂无排名数据\n\n)continue# 写入表头f.write(排名 | 姓名 | 用时 | 得分 | 日期\n)# 写入排名数据for i,background='white', 24, y))btn.grid(row=y, 中等: []。
30))# 难度选择按钮for difficulty in self.difficulties:btn = ttk.Button(self.main_frame, y + dyif 0 = nx self.width and 0 = ny self.height and self.board[ny][nx] != -1:self.board[ny][nx] += 1def reveal_cell(self, y) not in self.flags:self.buttons[y][x].config(text='#128163;', bold), f恭喜您赢了!用时: {self.elapsed_time}秒\n得分: {score})else:# 游戏失败时显示所有地雷for y in range(self.height):for x in range(self.width):if self.board[y][x] == -1 and (x, 20))# 创建笔记本式选项卡notebook = ttk.Notebook(self.main_frame)notebook.pack(fill=tk.BOTH,command=self.show_rankings, fg=colors[self.board[y][x] - 1], 'maroon',command=self.show_start_screen, self.update_timer)def show_game_over(self, state=tk.NORMAL)else:# 如果是空白单元格, bg='white', y):揭示单元格if self.game_over or (x, padx=20)# 计时器self.time_label = tk.Label(info_frame, 12, won):显示游戏结束界面if won:# 计算得分(考虑难度加权和时间)difficulty_weight = self.difficulties[self.difficulty][weight]score = int((10000 / (self.elapsed_time + 1)) * difficulty_weight)# 提示输入姓名name = simpledialog.askstring(游戏胜利,command=lambda: self.start_game(difficulty), state=tk.DISABLED)# 检查是否踩到地雷if self.board[y][x] == -1:btn.config(bg='red', 很遗憾,递归揭示周围的单元格for dy in [-1, wrap=tk.WORD,width=15)back_btn.pack(side=tk.LEFT, padx=10)# 重新开始按钮restart_btn = ttk.Button(button_frame,fg=#2c3e50。
y + dyif 0 = nx self.width and 0 = ny self.height:self.reveal_cell(nx,date: time.strftime(%Y-%m-%d %H:%M)})# 按得分排序self.rankings[self.difficulty].sort(key=lambda x: x[score],width=20)back_btn.pack(pady=20)# 运行游戏if __name__ == __main__:# 打包命令 pyinstaller -F -w -i .mine.ico saolei.pyroot = tk.Tk()game = Minesweeper(root)root.mainloop() , [Python] 纯文本查看 复制代码 import tkinter as tkfrom tkinter import ttk, orient=tk.VERTICAL,f恭喜您赢了!用时: {self.elapsed_time}秒\n得分: {score}\n请输入您的姓名:, fill=tk.BOTH。
font=(Arial。
bg='#f0f0f0', weight=1)# 按钮框架button_frame = tk.Frame(self.main_frame, bg='white')button_frame.pack(pady=10)# 返回按钮back_btn = ttk.Button(button_frame,font=(Arial,text=重新开始, root):self.root = rootself.root.title(Python扫雷游戏)self.root.configure(bg='white')self.root.minsize(800,font=('Arial',score: int(score_str),width=15)restart_btn.pack(side=tk.LEFT, 32。
text=游戏排名, y) in self.flags or (x, y) in self.flags:self.buttons[y][x].config(bg='#ccffcc') # 正确标记的地雷messagebox.showinfo(游戏结束。
width=20)btn.pack(pady=10)# 返回按钮back_btn = ttk.Button(self.main_frame, y))btn.config(text='#128681;', 12), weight: 1.0},width=20)exit_btn.pack(pady=10)def show_difficulty_selection(self):显示难度选择界面# 清除现有内容for widget in self.main_frame.winfo_children():widget.destroy()# 取消现有计时器if self.timer_id is not None:self.root.after_cancel(self.timer_id)self.timer_id = None# 标题title_label = tk.Label(self.main_frame, 排名 姓名用时得分日期\n)text_widget.insert(tk.END,command=lambda x=x,background='white')# 创建内部框架用于网格grid_frame = tk.Frame(grid_container,bg='#333',bg='white')self.diff_label.pack(side=tk.RIGHT, y):标记/取消标记单元格为地雷if self.game_over or (x,width=2, weight: 0.8},text=雷场,您踩到地雷了!)def show_rankings(self):显示排名界面# 清除现有内容for widget in self.main_frame.winfo_children():widget.destroy()# 标题title_label = tk.Label(self.main_frame,bg='white')title_label.pack(pady=(80,bg='white')self.time_label.pack(side=tk.RIGHT, bg='white')info_frame.pack(pady=10)# 地雷计数器self.mines_label = tk.Label(info_frame, IndexError):continueexcept Exception as e:print(f加载排名时出错: {e})# 出错时返回空排名return {简单: [], 困难: []}# 按得分排序for difficulty in rankings:rankings[difficulty].sort(key=lambda x: x[score], 14)。
14)。
font=(Arial。
entry in enumerate(self.rankings[difficulty],)grid_container.pack(pady=10, 0。
pady=10)# 为每个难度创建排名选项卡for difficulty in self.difficulties:frame = tk.Frame(notebook,text=返回主菜单, *.mp3), 24, f{difficulty}难度排名\n\n)if difficulty in self.rankings and self.rankings[difficulty]:# 添加表头text_widget.insert(tk.END,fg=#2c3e50, mines: 10,width=20)music_btn.pack(pady=10)# 退出游戏按钮exit_btn = ttk.Button(self.main_frame,font=(Arial, record in enumerate(records。
font=(Arial,relief=tk.RAISED,padding=10, y))btn.config(text='', # 深色边框padx=2,command=self.show_start_screen, height: 20,切换播放状态if pygame.mixer.music.get_busy():pygame.mixer.music.stop()else:self.play_background_music()else:filetypes = ((mp3, messagebox, expand=True。
'wb')icon.write(b64decode(ICON_BASE64))icon.close()self.root.iconbitmap(icon_name)def load_rankings(self):从TXT文件加载排名数据rankings = {简单: []。
评论列表