|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
做数字逻辑设计工程师一枚,经常用perl写些脚本处理信号数据文本,感觉perl比较丑陋,听说python美观简洁,花了几个小时看了下基本语法,编了个小时候用纸牌算24点得游戏,感觉比perl写得好看。
- #! /usr/bin/python
- """
- This script's function is calculate 24 point.
- rules:
- 1. Use four random numbers to calc 24
- 2. The legal operators:+,-,*,/
- 3. U can change numbers with 'c'
- 4. Quit game use 'q'
- 5. When game over,a report will be generate
- """
- import os #if use from os import * then the open func will be covered
- from random import *
- from sys import *
- #global counters for report
- genDataCnt = 0
- rightCnt = 0
- wrongCnt = 0
- changeCnt = 0
- if __name__ == '__main__':
- print __doc__
- else:
- pass
- #random number def
- def randomNumber():
- x=0
- a=[]
- while True:
- if x < 4:
- b = choice([1,2,3,4,5,6,7,8,9,10])
- a.append(b)
- x += 1
- else:
- break
- return a
- #enter opterator
- while True:
- commond = raw_input('Are you ready?(yes or no):')
- if commond == 'no':
- exit(0)
- elif commond == 'yes':
- break
- else:
- print 'Please enter "yes" or "no"!'
- continue
- #random number
- while True:
- arryNum = randomNumber()
- print arryNum
- genDataCnt += 1
- commond = raw_input('This is Ok?("yes" or "c" or "q"):')
- if commond == 'c':
- changeCnt += 1
- continue
- elif commond == 'q':
- all = [genDataCnt,changeCnt,rightCnt,wrongCnt]
- try:
- fp = open("gameReport",'w')
- except IOError,e:
- print "File open error:",e
- else:
- #fp.write("GenCnt=%-20d\nRight=%-20d"%(all[0],all[2]))
- fp.write("GenCnt =%2d\n"%all[0]) # == print handld "" in perl
- fp.write("ChangeCnt =%2d\n"%all[1])
- fp.write("RightCnt =%2d\n"%all[2])
- fp.write("WrongCnt =%2d\n"%all[3])
- fp.close()
- exit()
- elif commond == 'yes':
- gram = raw_input('Just do it:')
- result = eval(gram)
- #print "DEBUG %d"%result
- if result == 24:
- print "Result is right!^V^"
- print "Try next numbers!^_^"
- rightCnt += 1
- else:
- print "wrong"
- wrongCnt += 1
- while True:
- retry = raw_input('Retry?("yes" or "no"):')
- if retry == 'yes':
- gram = raw_input('come on:')
- result = eval(gram)
- if result == 24:
- print "Congratulations u did it!^@^"
- print "Try next numbers!^_^"
- break
- else:
- continue
- elif retry == 'no':
- break
- else:
- print 'Please enter legal charactor:'
- else:
- print "please enter legal charactor!"
- continue
-
复制代码 |
|