1.猜数游戏(限最多2人完成) 要求:设计一个有GUI界面的猜数游戏。有5个游戏者依次玩猜数游戏,“系统随机产生一 个1-500之间整数,同学输入猜测数,猜不中,提示是大了还是小了,继续猜,直到猜中为 止,记录猜测次数。”所有游戏者均完成后,按照猜测次数由低到高的次序排序游戏者
时间: 2023-09-08 10:17:30 浏览: 141
很高兴为您解答,以下是Python语言的代码实现:
```python
import random
import tkinter as tk
class GuessNumberGame:
def __init__(self, master):
self.master = master
self.master.title("猜数游戏")
self.master.geometry("300x150")
self.label1 = tk.Label(self.master, text="猜数游戏", font=("Arial", 18))
self.label1.pack(pady=10)
self.label2 = tk.Label(self.master, text="请输入您的姓名:")
self.label2.pack()
self.name_entry = tk.Entry(self.master)
self.name_entry.pack(pady=5)
self.start_button = tk.Button(self.master, text="开始游戏", command=self.start_game)
self.start_button.pack(pady=10)
self.guess_number = None
self.guess_count = 0
self.player_list = []
def start_game(self):
self.player_list.clear()
self.guess_number = random.randint(1, 500)
self.guess_count = 0
self.name_entry.config(state="disabled")
self.start_button.config(state="disabled")
self.play_game()
def play_game(self):
guess_window = tk.Toplevel(self.master)
guess_window.title("猜数游戏")
guess_window.geometry("300x150")
name_label = tk.Label(guess_window, text="玩家:" + self.name_entry.get(), font=("Arial", 12))
name_label.pack(pady=5)
guess_label = tk.Label(guess_window, text="请猜一个1-500之间的整数:")
guess_label.pack()
guess_entry = tk.Entry(guess_window)
guess_entry.pack(pady=5)
result_label = tk.Label(guess_window, text="")
result_label.pack()
def check_guess():
guess = int(guess_entry.get())
self.guess_count += 1
if guess == self.guess_number:
result_label.config(text="恭喜您猜对了,猜测次数为:" + str(self.guess_count))
self.player_list.append((self.name_entry.get(), self.guess_count))
guess_window.after(2000, guess_window.destroy)
if len(self.player_list) == 5:
self.show_result()
else:
self.start_game()
elif guess > self.guess_number:
result_label.config(text="猜大了,请再猜一次:")
else:
result_label.config(text="猜小了,请再猜一次:")
guess_button = tk.Button(guess_window, text="猜", command=check_guess)
guess_button.pack(pady=10)
def show_result(self):
self.player_list.sort(key=lambda x: x[1])
result_window = tk.Toplevel(self.master)
result_window.title("游戏结果")
result_window.geometry("300x150")
result_label = tk.Label(result_window, text="游戏结果如下:", font=("Arial", 12))
result_label.pack(pady=5)
for i in range(len(self.player_list)):
player_label = tk.Label(result_window, text="第" + str(i+1) + "名:" + self.player_list[i][0] + ",猜测次数为:" + str(self.player_list[i][1]))
player_label.pack(pady=5)
restart_button = tk.Button(result_window, text="重新开始", command=self.start_game)
restart_button.pack(pady=10)
if __name__ == '__main__':
root = tk.Tk()
game = GuessNumberGame(root)
root.mainloop()
```
代码中使用了tkinter库实现GUI界面,玩家需要输入自己的姓名后才能开始游戏。每个玩家猜数时都会弹出一个独立的窗口,直到猜对后窗口才会关闭,记录猜测次数并保存到一个列表中。当所有玩家完成后,按照猜测次数由低到高的次序排序玩家,并在另一个窗口中展示游戏结果。
阅读全文