区间猜数字小游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import random
import time

def print_welcome():
print("=" * 30)
print("欢迎来到猜数字游戏")
print("规则说明:")
print("1. 输入数字范围,系统会随机生成一个数字")
print("2. 输入'q'可以随时退出游戏")
print("=" * 30)

def validate_input(prompt):
while True:
try:
user_input = input(prompt)
if user_input.lower() == 'q':
return 'q'
return int(user_input)
except ValueError:
print("❌ 请输入有效的数字!")

def get_range():
while True:
try:
range_input = input("请输入所猜数字区间(如: 1,100): ")
if range_input.lower() == 'q':
return None, None
x, y = range_input.split(',')
x, y = int(x), int(y)
if x >= y:
print("❌ 起始数字必须小于结束数字!")
continue
if y - x > 1000:
confirm = input("⚠️ 数字范围太大,可能会很难猜到,是否继续?(y/n): ")
if confirm.lower() != 'y':
continue
return x, y
except ValueError:
print("❌ 请按正确格式输入两个数字,用逗号分隔!")

def play_game():
best_score = float('inf')
games_played = 0

print_welcome()

while True:
x, y = get_range()
if x is None:
break

target = random.randint(x, y)
attempts = 0
start_time = time.time()

print(f"\n🎮 已生成一个{x}{y}之间的随机数,开始猜吧!")

while True:
attempts += 1
guess = input(f"第{attempts}次猜测,请输入一个数字: ")

if guess.lower() == 'q':
print("\n👋 游戏已退出")
return

if guess == "geass":
print(f"🔮 {target}")
continue

try:
guess = int(guess)
if guess > target:
print("📉 大了!")
elif guess < target:
print("📈 小了!")
else:
end_time = time.time()
time_used = round(end_time - start_time, 2)
print(f"\n🎉 恭喜猜对了!")
print(f"🎯 你一共猜了{attempts}次")
print(f"⏱️ 用时:{time_used}秒")

if attempts < best_score:
best_score = attempts
print(f"🏆 新纪录!最少猜测次数:{best_score}")

games_played += 1
break
except ValueError:
print("❌ 请输入有效的数字!")
attempts -= 1

while True:
key = validate_input("\n继续游戏请按1,退出请按0: ")
if key == 'q' or key in [0, 1]:
break
print("❌ 只能输入0或1!")

if key == 'q' or key == 0:
break

print("\n🎮 游戏统计:")
print(f"📊 共玩了{games_played}局")
if games_played > 0:
print(f"🏆 最好成绩:{best_score}次猜中")
print("👋 游戏结束,欢迎下次再来!")

if __name__ == "__main__":
play_game()