欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现猜数字小游戏

程序员文章站 2022-10-29 15:57:49
python初学者小游戏:猜数字 游戏逻辑:电脑随机生成一个数字,然后玩家猜数字,电脑提示猜的数字大了还是小了,供玩家缩小数字范围,达到既定次数后,玩家失败。若在次数内猜...

python初学者小游戏:猜数字

游戏逻辑:电脑随机生成一个数字,然后玩家猜数字,电脑提示猜的数字大了还是小了,供玩家缩小数字范围,达到既定次数后,玩家失败。若在次数内猜对,玩家获胜。

涉及知识点:random.randint() , print() , input() ( raw_input() )

参考实现代码:

#!/usr/bin/env python 
# encoding: utf-8 
 
#使用print("",end=...)标准 
from __future__ import print_function 
 
import os 
import sys 
import time 
import random 
 
#输入检测 
 
while 1: 
  os.system('cls') 
  print ("hello , welcome to guess_number games...the number is between 1 - 10...") 
  print ("please input the level you want(1~10): ",end = '') 
  level = raw_input("") 
  diff = 11-int(level) 
  if diff > 10 or diff <1: 
    print ("invalid input...") 
    time.sleep(0.3) 
  else: 
    break 
 
#猜数字流程 
 
count_num = 0 
ran = random.randint(1,10) 
while count_num < diff: 
  count_num += 1 
  print (str(count_num)+": "+"please input the number you guess: ",end = '') 
  number = raw_input() 
  number = int(number) 
  if number < ran: 
    print ("too little...") 
    continue 
  elif number > ran: 
    print ("too big...") 
    continue 
  else: 
    print ("congraduation! you win...") 
    break 
if count_num == diff: 
  print ("you lose...") 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。