2007-07-13
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!'
发表评论
- 浏览: 83843 次

- 详细资料
搜索本博客
最近加入圈子
链接
最新评论
-
JBPM gop的四个模型
...
-- by protess123 -
另类的Jquery与Prototype ...
这个方案更合适现有Jquery的代码升级至Jquery + prototypt。 ...
-- by ayeah -
介绍ExtremeTable的下一代 ...
还是不喜欢用taglib
-- by baichinie -
Jmesa系列(三)开始使用 ...
也不算就很长了, WebContext webContext = new H ...
-- by spiritfrog -
介绍ExtremeTable的下一代 ...
不好意思,刚没注意有个附件就是demo的。
-- by spiritfrog






评论排行榜