pythonのTKモジュールでクイズゲームを実現(ソースコード付)

81131 ワード

説明:本ゲームで使用するpythonモジュールにはtkinter,random,hashlibがあります.ゲーム全体は4つのウィンドウに分かれており、1つのゲームに入るウィンドウ、1つの選択ウィンドウ、1つのゲーム進行ウィンドウ、1つのゲーム終了ウィンドウに分かれています.
ソースコードには2つの主要なpyファイルがあります.mygame.pyとsetting.py、mygameファイルはゲームのメインファイルで、すべてのコードロジックはこのファイルにあります.settingモジュールは、問題、答え、ヒントなど、ゲームのリソースを保存します.
player_answers.txtファイルは、プレイヤーが答えたレベルを記録するために使用されます.

   , ,

   , 。

:1. 30 , , ;
2. setting , if __name__ == "__main__"
str1 str2 。

:1. md5 ; ;
2. ;
3. ;
4. , ;
5. , ; ,
mygame if __name__ == "__main__" player_answers.txt ,
0.





、 :

 1 __author__ = {'author': 'caiwanpeng',
 2               'Email': '[email protected]',
 3               'Blog': 'http://www.cnblogs.com/cwp-bg/',
 4               'Created': '2017-09-25',
 5               'Version': '1.1'}
 6 
 7 
 8 class ButtonSelect(object):
 9     """         """
10 
11     def __init__(self, win, num, game_screen, elements, player_answer):
12         self.win = win
13         self.name = tk.StringVar(self.win)
14         self.sum_sc = len(dict_problems)
15         self.num_sc = num
16         self.start_game = game_screen
17         self.eles = elements
18         self.player_answer = player_answer
19 
20     def set_name(self, value):
21         """       """
22         self.name.set(value)
23 
24     def set_bg(self):
25         """        """
26         if self.player_answer == "1":
27             return "green"
28         return "red"
29 
30     def create_button(self, place=(0, 0)):
31         """    """
32         button = tk.Button(self.win, textvariable=self.name,
33                            command=self._select_sc,
34                            bg=self.set_bg(), fg="black",
35                            activebackground="orange",
36                            font=("  ", 16, "bold"))
37         button.place(width=40, height=40,
38                      relx=0.1 + place[0] * 0.8,
39                      rely=0.1 + place[1] * 0.9)
40         return button
41 
42     def _select_sc(self):
43         """        """
44         #            
45         self.num_sc[0] = int(self.name.get())
46         #           
47         try:
48             for ele in self.eles:
49                 ele.destroy()  #        
50         except Exception as re:
51             print(re)
52         self.eles.clear()  #     
53         #        
54         self.start_game()
 
   

 

 、         :
 1 class ButtonNew(object):
 2     """      """
 3 
 4     def __init__(self, wins, v1, v2, result, screen_num, bg='red',
 5                  fg="green", height=1, width=3,
 6                  font=("  ", 20, "bold")):
 7         self.win = wins
 8         self.v1 = v1
 9         self.v2 = v2
10         self.v_name = tk.StringVar(self.win)  #            
11         self.results = result
12         self.screen_num = screen_num  #         
13         #     
14         self.bg = bg
15         self.fg = fg
16         self.height = height
17         self.width = width
18         self.font = font
19 
20     def create_button(self, place_b=(0, 0)):
21         """    """
22         #     ,        ,command        ,bg    ,fg    
23         key_answer = tk.Button(self.win, textvariable=self.v_name,
24                                command=lambda: self._button_event(self.v_name.get()),
25                                activebackground="blue",
26                                bg=self.bg, fg=self.fg,
27                                height=self.height,
28                                width=self.width, font=self.font)
29         #        
30         key_answer.place(x=place_b[0], y=place_b[1])
31         return key_answer
32 
33     def _button_event(self, name1):
34         """             """
35         #    v2  
36         self.v2.set("")
37         if len(self.v1.get()) < 4:  #        
38             self.results.append(name1)
39         else:
40             self.results.clear()
41 
42         result = ""
43         for i in self.results:  #      
44             result += i
45         self.v1.set(result)
46 
47         #         
48         if abt.the_answer is True:
49             abt.the_answer = False
50         password = dict_result[str(self.screen_num[0])]
51         if len(self.results) >= 4 and self.get_md5(result) == password:
52             abt.the_answer = True  #           
53             # print(abt.the_answer)
54 
55     @staticmethod
56     def get_md5(str1):
57         """ st1   MD5  """
58         return hb.md5(str1.encode("utf-8")).hexdigest()
 
   

 

 、      :
  1 class GameWindow(object):
  2     """                """
  3 
  4     def __init__(self):
  5         """     """
  6         #        
  7         self.win = tk.Tk()
  8         self.win.title("       ")  #   
  9         self.win.geometry("500x500+500+100")  #     
 10         self.win.resizable(width=False, height=False)  #      
 11         self.v1 = tk.StringVar(self.win)  #        
 12         self.v2 = tk.StringVar(self.win)  #          
 13         self.v_screen = tk.StringVar(self.win)  #         
 14         self.v_problems = tk.StringVar(self.win)  #            
 15         self.results = []  #              
 16         self.eles = []  #              
 17         self.list_button = []  #           
 18         self.screen_num = [1]  #         ,           
 19         self.sum_screen = len(dict_problems)  #          
 20         self.player_answers = self.player_answer()  #              
 21 
 22     def create_label(self):
 23         """         """
 24         #        
 25         dir1 = tk.Label(self.win, bg="yellow", textvariable=self.v_screen,
 26                         fg="blue", font=("  ", 20, "bold"))
 27         dir1.pack(side=tk.TOP, fill=tk.X)
 28         self.eles.append(dir1)
 29         #       "  "
 30         dir2 = tk.Label(self.win, bg="red", text="  :",
 31                         font=("  ", 20, "bold"))
 32         dir2.place(x=0, y=200)  #       
 33         self.eles.append(dir2)
 34         #         
 35         dir3 = tk.Label(self.win, bg="#00F000", textvariable=self.v_problems,
 36                         wraplength=400, justify="left",
 37                         fg="blue", font=("  ", 20, "bold"), height=4)
 38         dir3.pack(fill=tk.X)
 39         self.eles.append(dir3)
 40         #                
 41         dir4 = tk.Label(self.win, bg="green", textvariable=self.v1,
 42                         font=("  ", 20, "bold"))
 43         dir4.place(x=100, y=200)
 44         self.eles.append(dir4)
 45         #              
 46         dir5 = tk.Label(self.win, textvariable=self.v2, fg="red",
 47                         font=("  ", 12, "bold"))
 48         dir5.place(x=100, y=240)
 49         self.eles.append(dir5)
 50 
 51     def create_button(self):
 52         """           """
 53         #         4*8   
 54         for j in range(4):
 55             for g in range(8):
 56                 button1 = ButtonNew(self.win, v1=self.v1,
 57                                     v2=self.v2, result=self.results,
 58                                     screen_num=self.screen_num)
 59                 #        
 60                 key_b = button1.create_button(place_b=(30 + g * 54, 280 + j * 45))
 61                 self.list_button.append(button1.v_name)  #           
 62                 self.eles.append(key_b)  #          
 63         self._set_key(self.screen_num[0])  #         
 64 
 65         #              
 66         cls = tk.Button(self.win, text="  ", command=self._cls_function,
 67                         bg="black", fg="white", font=("  ", 16, "bold"))
 68         cls.place(x=250, y=200)
 69         self.eles.append(cls)
 70         #              
 71         pmt = tk.Button(self.win, text="  ",
 72                         command=lambda: self._prompt_button(self.screen_num[0]),
 73                         bg="red", fg="white", font=("  ", 16, "bold"))
 74         pmt.place(x=320, y=200)
 75         self.eles.append(pmt)
 76         #              
 77         istrue = tk.Button(self.win, text="  ", command=self._ensure_button,
 78                            bg="red", fg="white", font=("  ", 16, "bold"))
 79         istrue.place(x=390, y=200)
 80         self.eles.append(istrue)
 81         #             
 82         last_sc = tk.Button(self.win, text="   ", command=self._last_sc_button,
 83                             bg="red", fg="white", font=("  ", 16, "bold"))
 84         last_sc.place(x=250, y=155)
 85         self.eles.append(last_sc)
 86         #              
 87         return_button = tk.Button(self.win, text="    ", command=self._return_lock,
 88                                   bg="red", fg="white", font=("  ", 16, "bold"))
 89         return_button.place(x=10, y=155)
 90         self.eles.append(return_button)
 91 
 92     def before_screen(self):
 93         """               """
 94         #     
 95         label1 = self.the_label()
 96         #     "       "
 97         label2 = self.the_label("       ")
 98         #     
 99         label3 = self.the_label()
100         #        
101         label4 = self.the_label(font=("  ", 250, "bold"), bg="#00ee00")
102         #     “    ”
103         dirx = tk.Label(self.win, bg="#00ee00", text="----    ",
104                         fg="blue", font=("  ", 20, "bold"))
105         dirx.place(x=250, y=200)
106         list_labels = [label1, label2, label3, label4, dirx]
107         #            
108         go_game = tk.Button(self.win, text="     ",
109                             command=lambda: self._start_game(go_game, *list_labels),
110                             bg="red", fg="white", activebackground="yellow",
111                             activeforeground="red", font=("  ", 30, "bold"))
112         go_game.place(x=130, y=300)
113 
114     def lock_screen(self):
115         """                   """
116         #     
117         dir_k = tk.Label(self.win, bg="#3b9dff", font=("  ", 20, "bold"))
118         dir_k.pack(fill=tk.X)
119         self.eles.append(dir_k)
120         #       
121         dir1 = tk.Message(self.win, bg="blue", text="    ",
122                           fg="red", font=("  ", 20, "bold"),
123                           width=200)
124         dir1.pack(fill=tk.X)
125         self.eles.append(dir1)
126         #       ,            
127         cans = tk.Canvas(self.win,  #    
128                          bg="#92dba0",  #        
129                          height=500,
130                          borderwidth=0)
131         cans.pack(fill=tk.X)
132         self.eles.append(cans)  #          
133 
134         for i in range(self.sum_screen):  #                  
135             j = i % 10 / 10.0
136             k = i // 10 / 10
137             #                  
138             bn_st = ButtonSelect(cans, self.screen_num,
139                                  self._game_go, self.eles,
140                                  self.player_answers[i])
141             bn_st.create_button(place=(j, k))
142             bn_st.set_name(str(i + 1))
143 
144     def after_screen(self):
145         """           """
146         self.the_label()  #     
147         text1 = ""
148         text2 = ""
149         #        
150         self.the_label(text1)
151         self.the_label(text2)
152         self.the_label()  #     
153         #          
154         go_game = tk.Button(self.win, text="",
155                             command=lambda: exit(),
156                             bg="red", fg="white",
157                             activebackground="yellow",
158                             activeforeground="red",
159                             font=("  ", 30, "bold"))
160         go_game.place(x=170, y=300)
161 
162     def the_label(self, text=None, side=tk.TOP,
163                   font=("  ", 40, "bold"), bg="green"):
164         """      """
165         dir1 = tk.Label(self.win, bg=bg, text=text,
166                         fg="black", font=font)
167         dir1.pack(side=side, fill=tk.X)
168         return dir1
169 
170     def _return_lock(self):
171         """         """
172         #     
173         self.list_button.clear()
174         #          
175         self.clear_screen()
176         #         
177         self.eles.clear()
178         #         1
179         self.screen_num[0] = 1
180         #         
181         self.screen_control(1)
182 
183     def clear_screen(self):
184         """           """
185         try:
186             for ele in self.eles:
187                 ele.destroy()  #        
188         except Exception as re:
189             print(re)
190 
191     def _set_key(self, num):
192         """           """
193         listx = rm.sample(dict_key[str(num)], len(dict_key[str(num)]))  #     
194         #             
195         for j, k in enumerate(self.list_button):
196             k.set(listx[j])  #          
197 
198     def _next_screen(self):
199         """              """
200         #              
201         next_b = tk.Button(self.win, text="   ", command=lambda: self._next_button(next_b),
202                            bg="red", fg="white",
203                            font=("  ", 16, "bold"))
204         next_b.place(x=390, y=155)
205         return next_b
206 
207     def _next_button(self, next_b):
208         """             """
209         try:
210             #            
211             if self.screen_num[0] >= len(dict_problems):
212                 # print("        ")
213                 #          
214                 self.clear_screen()
215                 #          
216                 self.screen_control(3)
217             else:
218                 if abt.the_answer is True:
219                     self.__update_screen()  #     
220                 else:
221                     self.v2.set("")
222 
223             #              
224             self.player_answers[self.screen_num[0] - 2] = "1"
225             #              
226             file = open("./player_answers.txt", "w")
227             file.write("".join(self.player_answers))  #       
228         except Exception as re:
229             print(re)
230         else:
231             #       
232             next_b.destroy()
233         finally:
234             file.close()
235 
236     def _last_sc_button(self):
237         """          """
238         #           
239         if self.screen_num[0] == 1:
240             self.v2.set("")
241         else:
242             self.screen_num[0] -= 2  #     
243             self.__update_screen()
244 
245     def __update_screen(self):
246         """        """
247         #     
248         self.v_problems.set(dict_problems[str(self.screen_num[0] + 1)])
249         self.screen_num[0] += 1  #        
250         #        
251         self.v_screen.set(" " + str(self.screen_num[0]) + " ")
252         #         
253         self._set_key(self.screen_num[0])
254         #   v1 v2     
255         self._cls_function()
256         self.v2.set("")
257         # print("    !")
258 
259     def _start_game(self, *args):
260         """         """
261         try:
262             for ele in args:
263                 ele.destroy()  #        
264         except Exception as re:
265             print(re)
266         self.screen_control(num=1)  #       
267 
268     def _game_go(self):
269         str_num = str(self.screen_num[0])
270         self.v_screen.set(" " + str_num + " ")  #        
271         self.v_problems.set(dict_problems[str_num])  #     
272         self.screen_control(2)  #       
273 
274     def _cls_function(self):
275         """          """
276         self.results.clear()
277         self.v1.set("")  #     
278 
279     def _ensure_button(self):
280         """         """
281         if abt.the_answer is True:
282             self.v2.set("")
283             self._next_screen()  #          
284         else:
285             self.v2.set("")
286 
287     def _prompt_button(self, key):
288         """         """
289         if abt.the_answer is True:  #           
290             abt.the_answer = False
291         self.results.clear()  #         
292         self.results.append(list_answer[int(key)])  #     
293         self.v1.set(list_answer[int(key)])  #       
294 
295     def screen_control(self, num=0):
296         """               """
297         if num == 0:
298             self.before_screen()  #           
299         elif num == 1:
300             self.lock_screen()  #       
301         elif num == 2:
302             self.create_label()  #                 
303             self.create_button()  #                
304         elif num == 3:
305             self.after_screen()  #         
306 
307     def run(self):
308         self.win.mainloop()  #     
309 
310     def player_answer(self):
311         """            """
312         #         
313         number1 = self.sum_screen
314         try:
315             #           ,            ,        
316             f = open("./player_answers.txt", "r")
317             str3 = f.read()
318             # print(str3)
319         except Exception as re:
320             print(re)
321         finally:
322             f.close()
323 
324         if number1 == len(str3):
325             return list(iter(str3))
326         else:  #    
327             str2 = "0" * number1
328             try:
329                 f1 = open("./player_answers.txt", "w")
330                 f1.write(str2)  #     
331             except Exception as re:
332                 print(re)
333             finally:
334                 f1.close()
335             return list(iter(str2))
336 
337 
338 win = GameWindow()
339 sc = win.screen_control
340 bs = win.before_screen
341 as_ = win.after_screen
342 ls = win.lock_screen
343 run = win.run
344 
345 
346 def main():
347     sc()
348     run()  #     
349 
350 
351 if __name__ == "__main__":
352     main()
353     #        
354     # str2 = "0"*len(dict_key)
355     # f1 = open("./player_answers.txt", "w")
356     # f1.write(str2)  #     
357     # f1.close()
 
   

 

 、   setting  。
 1 class AllButton(object):
 2     """                     """
 3 
 4     def __init__(self):
 5         self.the_answer = False  #            
 6         self.cls_answer = False  #          
 7         self.start_game = False  #        
 8 
 9 
10 abt = AllButton()
11 
12 if __name__ == "__main__":
13     print(len(dict_key))
14     str1 = ""  #          
15     md5_answer = hb.md5(str1.encode("utf-8")).hexdigest()
16     print(md5_answer)  #        
17     str2 = ""
18     results = rm.sample(str2, len(str2))
19     results = "".join(results)
20     print(results)  #         

      :https://files.cnblogs.com/files/cwp-bg/game_one.zip

:https://gitee.com/TianYuZhiYou/guess_the_chengyu

作者:天宇の旅出典:http://www.cnblogs.com/cwp-bg/
本文の著作権は作者とブログ園に共有され、転載、交流を歓迎するが、作者の同意を得ずにこの声明を保留し、文章の明らかな位置で原文のリンクを与えなければならない.
転載先:https://www.cnblogs.com/cwp-bg/p/7630166.html