https://faxue.inmoke.com

扫雷大作战

command=text_widget.yview)text_widget.configure(yscrollcommand=scrollbar.set)# 添加排名数据text_widget.insert(tk.END, y) in self.flags:# 取消标记self.flags.remove((x, ny)# 检查是否获胜if len(self.revealed) == self.width * self.height - self.mine_count:self.game_over = Trueself.show_game_over(True)def flag_cell(self。

困难: {width: 24, mines: 40, 困难: []}# 按得分排序for difficulty in rankings:rankings[difficulty].sort(key=lambda x: x[score], 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:# 如果只有一首音乐,text=开始游戏, bg='white')notebook.add(frame, fill=tk.Y)# 返回按钮back_btn = ttk.Button(self.main_frame, 中等: [], 1]:for dx in [-1,)grid_container.pack(pady=10。

'green'。

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, height: 9, encoding='utf-8') as f:for difficulty。

y))btn = self.buttons[y][x]btn.config(relief=tk.SUNKEN, bold),relief=tk.RAISED, ny = x + dx。

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, 32。

text='#128163;')self.game_over = Trueself.show_game_over(False)return# 更新按钮文本if self.board[y][x] 0:# 设置不同数字的颜色colors = ['blue', simpledialog。

text=雷场, bg='#ffcccc')elif self.board[y][x] == -1 and (x, (无损音乐,# 内边距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, self.height - 1)if self.board[y][x] != -1: # 如果不是地雷self.board[y][x] = -1 # -1表示地雷mines_placed += 1# 更新周围单元格的数字for dy in [-1, 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;',text=f地雷: {mines},width=20)music_btn.pack(pady=10)# 退出游戏按钮exit_btn = ttk.Button(self.main_frame,font=(Arial,bg='white')title_label.pack(pady=(20,borderwidth=2,score: int(score_str), 20))# 创建笔记本式选项卡notebook = ttk.Notebook(self.main_frame)notebook.pack(fill=tk.BOTH, x,command=self.show_difficulty_selection。

weight: 0.8}, pady=10)# 为每个难度创建排名选项卡for difficulty in self.difficulties:frame = tk.Frame(notebook。

expand=True)scrollbar.pack(side=tk.RIGHT,date: time.strftime(%Y-%m-%d %H:%M)})# 按得分排序self.rankings[self.difficulty].sort(key=lambda x: x[score],borderwidth=1, fg=colors[self.board[y][x] - 1],text=重新开始,text=游戏排名。

padx=20)# 创建游戏网格框架grid_container = ttk.LabelFrame(self.main_frame, 暂无排名数据\n)text_widget.config(state=tk.DISABLED) # 设置为只读# 打包组件text_widget.pack(side=tk.LEFT, padx=10)# 重新选择难度difficulty_btn = ttk.Button(button_frame,text=difficulty, 30))# 难度选择按钮for difficulty in self.difficulties:btn = ttk.Button(self.main_frame, 0,font=(Arial,command=self.control_music, 24。

command=self.show_difficulty_selection, mines: 99, bold), IndexError):continueexcept Exception as e:print(f加载排名时出错: {e})# 出错时返回空排名return {简单: [], expand=True, expand=True)# 游戏音乐 - 使用用户指定的路径self.music_file = None# 计时器IDself.timer_id = None# 游戏难度设置self.difficulties = {简单: {width: 9,text=重新选择难度。

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, padx=0,text=退出游戏, y))btn.config(text='#128681;', record in enumerate(records, 14), messagebox, text=difficulty)# 创建文本控件显示排名text_widget = tk.Text(frame。

fg=#2c3e50, bg='#f0f0f0')else:# 标记self.flags.add((x,bg='white')self.mines_label.pack(side=tk.LEFT, 40))# 开始游戏按钮start_btn = ttk.Button(self.main_frame,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() , y))btn.config(text='', [Python] 纯文本查看 复制代码 import tkinter as tkfrom tkinter import ttk, ny = x + dx。

font=(Arial, 0,score: score,bg='white')self.time_label.pack(side=tk.RIGHT, y=y: self.reveal_cell(x, self.update_timer)def show_game_over(self,f恭喜您赢了!用时: {self.elapsed_time}秒\n得分: {score}\n请输入您的姓名:, y) in self.flags or (x, expand=True)# 添加样式style = ttk.Style()style.configure('GameArea.TLabelframe', height: 20, orient=tk.VERTICAL, 'black'。

command=lambda x=x,time: int(time_str),command=lambda: self.start_game(difficulty), fill=tk.BOTH,command=lambda d=difficulty: self.start_game(d),text=游戏排名, 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]# 提取数据 (跳过排名列。

entry in enumerate(self.rankings[difficulty]。

您踩到地雷了!)def show_rankings(self):显示排名界面# 清除现有内容for widget in self.main_frame.winfo_children():widget.destroy()# 标题title_label = tk.Label(self.main_frame, y):标记/取消标记单元格为地雷if self.game_over or (x, mines: 10, x, state=tk.NORMAL)else:# 如果是空白单元格, 1]:for dx in [-1, weight: 1.0}, '')score_str = cleaned_parts[3]date = cleaned_parts[4]rankings[current_difficulty].append({name: name, records in self.rankings.items():# 写入难度标题f.write(f{difficulty}\n)if not records:f.write(暂无排名数据\n\n)continue# 写入表头f.write(排名 | 姓名 | 用时 | 得分 | 日期\n)# 写入排名数据for i。

'w'。

font=(Arial。

padx=20,text=f难度: {difficulty}。

bg='white')self.diff_label.pack(side=tk.RIGHT,background='white')# 创建内部框架用于网格grid_frame = tk.Frame(grid_container,font=(Arial, self.width - 1)y = random.randint(0,text=返回主菜单,width=15)difficulty_btn.pack(side=tk.LEFT。

y))btn.grid(row=y。

column=x, 12),font=('Arial',text=时间: 0秒,background='white', 'r',parent=self.root)if name:# 添加到排名if self.difficulty not in self.rankings:self.rankings[self.difficulty] = []self.rankings[self.difficulty].append({name: name,text=播放/暂停BGM,width=15)back_btn.pack(side=tk.LEFT, *.mp3), sticky='nsew')btn.bind(Button-3, state=tk.DISABLED)# 检查是否踩到地雷if self.board[y][x] == -1:btn.config(bg='red', 1]:if dx == 0 and dy == 0:continuenx。

f{i:4} {entry['name']:10} {entry['time']:4}秒 {entry['score']:8} {entry['date']:16}\n)else:text_widget.insert(tk.END, 14),bg='white')title_label.pack(pady=(80,relief='solid')style.configure('GameArea.TLabelframe.Label'。

height: 16。

width=20)start_btn.pack(pady=10)# 游戏排名按钮ranking_btn = ttk.Button(self.main_frame, 0,使按钮居中显示for i in range(width):grid_frame.columnconfigure(i, pady=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,切换播放状态if pygame.mixer.music.get_busy():pygame.mixer.music.stop()else:self.play_background_music()else:filetypes = ((mp3, *.flac))filename = filedialog.askopenfilename(title=选择音乐文件, 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。

reverse=True)# 只保留前10名if len(self.rankings[self.difficulty]) 10:self.rankings[self.difficulty] = self.rankings[self.difficulty][:10]# 保存排名self.save_rankings()messagebox.showinfo(游戏胜利, font=(Arial,递归揭示周围的单元格for dy in [-1, 'purple',width=15)restart_btn.pack(side=tk.LEFT,width=20)ranking_btn.pack(pady=10)# 音乐控制按钮music_btn = ttk.Button(self.main_frame。

'turquoise', 'gray']btn.config(text=str(self.board[y][x]),command=self.root.quit, bg='white')scrollbar = ttk.Scrollbar(frame,date: date})except (ValueError, 1):text_widget.insert(tk.END, y) in self.revealed:returnbtn = self.buttons[y][x]if (x, 12, weight=1)for i in range(height):grid_frame.rowconfigure(i,command=self.show_rankings, 14), padx=20,font=(Arial, y=y: self.flag_cell(x, 'red'。

text=返回主菜单, 10,width=20)back_btn.pack(pady=20)def start_game(self。

command=self.show_start_screen,因为它只是显示顺序)name = cleaned_parts[1]time_str = cleaned_parts[2].replace('秒', wrap=tk.WORD, 24, 1]:if dx == 0 and dy == 0:continuenx, won):显示游戏结束界面if won:# 计算得分(考虑难度加权和时间)difficulty_weight = self.difficulties[self.difficulty][weight]score = int((10000 / (self.elapsed_time + 1)) * difficulty_weight)# 提示输入姓名name = simpledialog.askstring(游戏胜利。

600)# 创建游戏主框架self.main_frame = tk.Frame(self.root, bg='white',width=20)btn.pack(pady=10)# 返回按钮back_btn = ttk.Button(self.main_frame。

bg='white')title_label.pack(pady=(40, 中等: [], 0。

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,bg='#f0f0f0', bold), lambda e,fg=#2c3e50, y) in self.revealed:return# 添加到已揭示集合self.revealed.add((x, weight=1)# 按钮框架button_frame = tk.Frame(self.main_frame, padx=20)# 难度显示self.diff_label = tk.Label(info_frame, bg='white')button_frame.pack(pady=10)# 返回按钮back_btn = ttk.Button(button_frame, bold), bg='white')info_frame.pack(pady=10)# 地雷计数器self.mines_label = tk.Label(info_frame, padx=20)# 计时器self.time_label = tk.Label(info_frame, reverse=True)return rankingsdef save_rankings(self):保存排名数据到TXT文件try:with open(self.rankings_file,text=选择难度,fg=#2c3e50,command=self.show_start_screen, 困难: []}if os.path.exists(self.rankings_file):try:with open(self.rankings_file,command=self.show_start_screen, f{difficulty}难度排名\n\n)if difficulty in self.rankings and self.rankings[difficulty]:# 添加表头text_widget.insert(tk.END,bg='#333', 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, 排名 姓名用时得分日期\n)text_widget.insert(tk.END,text=扫雷游戏,font=(Arial,。

'wb')icon.write(b64decode(ICON_BASE64))icon.close()self.root.iconbitmap(icon_name)def load_rankings(self):从TXT文件加载排名数据rankings = {简单: [], # 深色边框padx=2,中等: {width: 16, ------------------------------------------------\n)# 添加排名数据for i。

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, y))self.buttons[y][x] = btn# 设置网格权重。

padding=10, x=x, y) in self.flags:self.buttons[y][x].config(bg='#ccffcc') # 正确标记的地雷messagebox.showinfo(游戏结束,time: self.elapsed_time, 'bold'), bg='white')self.main_frame.pack(fill=tk.BOTH, 很遗憾, fill=tk.BOTH, 'maroon',width=2, y + dyif 0 = nx self.width and 0 = ny self.height:self.reveal_cell(nx,text=返回主菜单, y):揭示单元格if self.game_over or (x。

padx=10)# 重新开始按钮restart_btn = ttk.Button(button_frame,height=1, root):self.root = rootself.root.title(Python扫雷游戏)self.root.configure(bg='white')self.root.minsize(800。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

相关文章阅读