Python学习入门笔记(十八) 猜数字小游戏

程序介绍:
猜数字小游戏,计算机随机生成一个1-100的数字,然后用户猜数字的值,系统提示用户:“数字太高了/数字太低了”。

代码部分:

#原版1
import random

n = random.randint(1,100) #生成一个1-100的随机整数
step = 0 #游戏的步数

print('Game start')
guess = int(input('Please enter an integer from 1 to 100:'))

while True:
    step+=1
    print('step',step)
    if guessn:
        print(guess,'is high')
    else:
        print('You win!')
        break
    guess = int(input('Please enter an integer from 1 to 100:'))
    
print('Game over')

结果:
游戏存在bug,
1、输入非数字字符会报错
2、游戏没有退出功能

#改进2  解决BUG 输入0退出游戏
import random

n = random.randint(1,100) #生成一个1-100的随机整数
step = 0 #游戏的步数
print('Game start')

def get_number():
    guess = input('Please enter an integer from 1 to 100:')
    while True:
        if guess.isdigit():#判断输入内容是否是数字
            guess = int(guess)
            return guess
        else:
            guess = input('Please enter an integer from 1 to 100:')

guess = get_number()#获取输入数字

while True:
    step+=1
    print('step',step)
    
    if guess == 0:#退出游戏
        print('quit')
        break
    
    if guessn:
        print(guess,'is high')
    else:
        print('You win!')
        break
    guess = get_number()
    
print('Game over')

结果2
Game start
Please enter an integer from 1 to 100:50
step 1
50 is high
Please enter an integer from 1 to 100:0 #按0退出游戏
step 2
quit
Game over

#改进3 增加提示,降低游戏难度,增加提示区间

import random

n = random.randint(1,100) #生成一个1-100的随机整数
step = 0 #游戏的步数
high = 100
low = 1
print('Game start')

def get_number():
    guess = input('Please enter an integer from 1 to 100:')
    while True:
        if guess.isdigit():#判断输入内容是否是数字
            guess = int(guess)
            return guess
        else:
            guess = input('Please enter an integer from 1 to 100:')

guess = get_number()

while True:
    step+=1
    print('step',step)
    
    if guess == 0:#退出游戏
        print('quit')
        break
    
    if guessn:
        print(guess,'is high')
        high = guess - 1
    else:
        print('You win!')
        break
    print('You can try',low,'to',high)
    guess = get_number()
    
print('Game over')

结果
Game start
Please enter an integer from 1 to 100:50
step 1
50 is low
You can try 51 to 100
Please enter an integer from 1 to 100:80
step 2
80 is high
You can try 51 to 79
Please enter an integer from 1 to 100:60
step 3
60 is high
You can try 51 to 59
Please enter an integer from 1 to 100:55
step 4
55 is high
You can try 51 to 54
Please enter an integer from 1 to 100:53
step 5
You win!
Game over

你可能感兴趣的:(Python学习入门笔记(十八) 猜数字小游戏)