程序代码:import random
history = {}
def creat_answer():
return random.randint(0, 1024)
def try_to_guess(name, answer):
try_num = 0
while try_num < 10:
guess_answer = int(input("请输入一个数字:"))
if guess_answer < answer:
print("你猜小了~")
history[name].append('失败')
elif guess_answer == answer:
print("bingo,你猜对了~")
history[name].append('成功')
break
else:
print("你猜大了~")
history[name].append('失败')
try_num += 1
else:
print("你猜的次数太多啦,失败~")
history[name].append('失败')
def show_history():
for name, score in history.items():
print('用户名:',name + ',历史成绩', score)
def start():
guess_name = input("请输入你的名字:")
if guess_name not in history.keys():
history[guess_name] = []
try_to_guess(guess_name, creat_answer())
if __name__ == '__main__':
select_dict = {'1': show_history, '2': start, '3': exit}
while True:
guess_select = input('1. 历史记录\n2. 开始游戏\n3. 退出游戏\n请输入数字选择:')
select_dict.get(guess_select)()
- 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
拓展,用户自定义数字区间import random
import math
history = {}
def input_guess(start, end):
''' 判断用户输入的字符,不符合则提示用户重新输入,符合则返回这个字符 '''
guess = int(input('请输入{}~{}之间,猜测的数字:'.format(start, end)))
if guess >= start and guess <= end:
return guess
else:
print('输入非法数字,重新输入,请确定数字在{}~{}之间'.format(start, end))
def try_to_guess(name):
try_num = 0
start, end = input("请输入猜测数字的范围(用,分隔):").split(',')
start, end = int(start), int(end)
answer = random.randrange(start, end+1)
times = math.log2(start + end)
times = math.floor(times)
print('请在{}次内猜测正确数字'.format(times))
while try_num < times:
guess_answer = input_guess(start, end)
if guess_answer < answer:
print("你猜小了~")
history[name].append('失败')
elif guess_answer == answer:
print("bingo,你猜对了~")
history[name].append('成功')
break
else:
print("你猜大了~")
history[name].append('失败')
try_num += 1
else:
print("你猜的次数太多啦,失败~")
history[name].append('失败')
def show_history():
for name, score in history.items():
print('用户名:',name + ',历史成绩', score)
def start():
guess_name = input("请输入你的名字:")
if guess_name not in history.keys():
history[guess_name] = []
try_to_guess(guess_name)
if __name__ == '__main__':
select_dict = {'1': show_history, '2': start, '3': exit}
while True:
guess_select = input('1. 历史记录\n2. 开始游戏\n3. 退出游戏\n请输入数字选择:')
select_dict.get(guess_select)()

- 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