python猜数小游戏
用Python写了一个猜数的小游戏。很简单,电脑抽一个0到100的随机数,玩家猜电脑里的数字是什么,并视玩家所猜的数而给出太大或太小的提示,一直玩到猜中为止,程序将记录玩家所猜的次数。程序涉及了控制台输入输出,数据类型转换,随机数,异常捕捉等。
#!/usr/bin/python
''' this is a number guessing game.the computer make a random number and store
into the memory.the player guess what the number is.the computer will give
the tips.
'''
from random import Random
import sys
class GuessNumberGame:
def __init__(self,player):
self.player = player
rd = Random()
self.number = rd.randint(0,100)
def compare(self,guessNum):
if guessNum > self.number:
return 1
if guessNum < self.number:
return -1
return 0
if __name__ == '__main__':
game = GuessNumberGame('jeff')
print '''WOW!!!!let's start the game now.the computer now get a number in mind,the number is between 0 and 100,now what you guess?tell me by typing the number in your mind '''
count = 0
while True:
try:
guess = int(raw_input('the number you guess =>'))
except ValueError:
print 'wrong value format! NUMBER is accept.'
continue
except EOFError:
print 'good bye!'
count = count + 1
result = game.compare(guess)
if result == 0:
print 'grade!!you finally get the right number in %d times' % count
break
elif result == 1:
print 'the number you guess is grade then the real number,please try again :)'
elif result == -1:
print 'the number you guess is small then the real number ,please try again :)'
print 'Done!'
页:
[1]