Python实现猜数字小游戏

yipeiwu_com6年前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...") 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python TCPServer 多线程多客户端通信的实现

Python TCPServer 多线程多客户端通信的实现

最简单、原始的TCP通信demo 服务端Http请求: import socket # 创建一个servicesocke serviceSocket = socket.socket...

numpy排序与集合运算用法示例

numpy排序与集合运算用法示例

这里有numpy数组的相关介绍/post/130657.htm 排序 numpy与python列表内置的方法类似,也可通过sort方法进行排序。 用法如下: In [1]: imp...

python 接收处理外带的参数方法

在执行python 代码的时候,有时候需要传递外面的参数进行处理 这个该怎么实现呢? 需要一个模块 from sys import argv 当然也可以直接只导入 sys im...

Python学习笔记之open()函数打开文件路径报错问题

Python学习笔记之open()函数打开文件路径报错问题

要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符,标示符'r'表示读。 >>> f = open('D:/test.tx...

Python3中的2to3转换工具使用示例

python3与python2的还是有诸多的不同,比如说在2中: 复制代码 代码如下: print "Hello,World!"  raw_input()  在...