您的位置:首页 > 编程语言 > Python开发

python小游戏——猜数字2.0

2010-07-14 19:40 453 查看
前天完成了首个python小游戏,今天给它升级了下,加入了排名功能。用的次数少,排名在前十的,可以排到排行榜中。没有用数据库,太小,还用不上,写到了个文本文件中。

====================================================
gameMain.py 文件:

#_*_ coding: utf-8 _*_
from gameStart import gameStart
from scoreList import *
def showMenu() :
print '''
[ 猜数字游戏菜单 ]
==================================

<1> 开始游戏
<2> 高分排行榜
<3> 退出游戏
'''

def selectAct() :
yourAct = raw_input(">> 请输入您想要执行的操作,并按回车键确认 :")
if yourAct == "1" :
gameStart()
elif yourAct == "2" :
showScoreList()
elif yourAct == "3" :
print ">> 游戏结束,谢谢您的参与。\n==================================="
else :
print ">> 没有指定的选项。"
selectAct()

def init():
showMenu()
selectAct()

init()

gameStart.py:

#_*_ coding: utf-8 _*_
import random,scoreList
def gameStart() :
>>print '''
[猜数字游戏开始]
==================================
'''
goalNum = random.randint(0,99)
tip = ">> 请您猜一个数字,此数字介于0~99之间:"
guessCount = 0
while True :
while True:
try:
yourNum = raw_input(tip)
yourNum = int(yourNum)
break
except:
print ">> 您输入的不是数字。"
tip = ">> 请您再猜:"
guessCount += 1
if yourNum < goalNum :
print ">> (您猜的数小了 T_T)"
elif yourNum > goalNum :
print ">> (您猜的数大了 T_T)"
else :
print ">> (恭喜您猜中了 ^0^ , 您共猜了 %s 次猜中了结果)" % guessCount
break

scoreList.updateScoreList(guessCount)
while True:
continueFlag = raw_input(">> 游戏结束。您还想再玩一次吗? y | n : ")
if continueFlag == "y" :
gameStart()
break
elif continueFlag == "n" :
print ">> 游戏结束,谢谢您的参与。\n==================================="
break
else :
print ">> 请您输入y或n"

scoreList.py:

#_*_ coding:utf-8 _*_
import os
scoreListFile = "scoreList.txt"
def showScoreList() :
print '''
[ 高分排行榜 ]
=================================

排名 姓名 次数
------------'''
if not os.path.exists(scoreListFile) :
for i in range(1,11) :
print "<%s> 暂缺 x" % formatNum(i)
else :
f = open(scoreListFile)
try :
lines = f.readlines();
for i in lines :
print i
finally :
f.close()

def updateScoreList(count) :
if os.path.exists(scoreListFile) :
f = open(scoreListFile,"r")
try :
lines = f.readlines()
i = 0;
for x in lines :
i += 1
if count < int(x.split()[2]) :
name = raw_input(">> 恭喜您进入前十的排名,请输入您的尊姓大名(不超过三个字): ")
name = name[:3]
string = "<%s> %s %s\n" % (formatNum(i),name,count)
lines[i-1] = string
f.close()
f = open(scoreListFile,"w")
f.writelines(lines)
f.flush()
break
else :
pass
finally :
f.close()
else :
name = raw_input(">> 恭喜您进入前十的排名,请输入您的尊姓大名(不超过三个字): ")
name = name[:3]
string = "<%s> %s %s" % (formatNum(1),name,count)
for i in range(2,11) :
string += "\n<%s> 暂缺 9999" % formatNum(i)
f = open(scoreListFile,"w")
f.write(string)
f.flush()
f.close()

def formatNum(n) :
n = int(n)
if n < 10 :
return "0" + str(n)
else :
return n
====================================================

一点心得:
1) python中对文件的读写操作是分开的,要么是读要么是写,不能又读又写,如果想写先读后写,需要先open(file),然后在close(),再然后open(file,"w"),要关闭以前是不能进行写操作的。

2) 用write()方法写,有的时候还要注意调flush()方法将缓冲区的内容写到磁盘上,不然有可能会产生问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: