猫史档案馆


【Python作品分享】二进制游戏v1.2

用户:wrmdcxywrmdcxy查看:0 回复:3 评论:0 创建时间:2020-02-28T14:53:35


【作品展示】

center_image

【作品介绍】

作品介绍……我就不用说了吧

新增排行榜功能

v1.0:https://shequ.codemao.cn/community/226256

v1.1:https://shequ.codemao.cn/community/238429

【作品源代码】

import time
from random import randint
from os import rename,remove
from FileProcessing import Leaderboard

UserName=input('你好,请输入您的名字:')
inputs = open('G:\\FilesByPrograms\\userScores.txt', 'r')
l='j'
ranking=1
while l!='':
    l=inputs.readline()
    content=l.split(',')
    if content[0]==UserName:
        UserScores=content[1]
        UserScores=int(UserScores)
        inputs.close()
        break
    ranking+=1
try:
    UserScores+=1
    UserScores-=1
except NameError:
    inputs.close()
    UserScores='-1'
if UserScores=='-1':
    newu='True'
    UserScores=0
    print('欢迎加入这个游戏!')
    time.sleep(0.5)
    while True:
        GameChoise=input('请选择游戏:1.二进制游戏  2.十进制游戏')
        if GameChoise!='1' and GameChoise!='2':
            print('请输入正确的数字选项。\n')
        else:
            break
    if GameChoise=='1':
        print('''二进制游戏规则:
    在这个游戏中,你会得到一个十进制的数。
    你的任务是将这个数转换为二进制的数。
    答对一题加一分,答错一题不扣分。''')
    else:
        print('''十进制游戏规则:
    在这个游戏中,你会得到一个二进制的数。
    你的任务是将这个数转换为十进制的数。
    答对一题加一分,答错一题不扣分。''')
    time.sleep(1)
    print('现在开始吧')
else:
    newu='False'
    print('你好,%s,欢迎回来!您当前的分数是:%d。您在排行榜上的排名是%d'%(UserName,UserScores,ranking))
    while True:
        GameChoise=input('请选择游戏:1.二进制游戏  2.十进制游戏:')
        if GameChoise!='1' and GameChoise!='2':
            print('请输入正确的数字选项。')
        else:
            break
    while True:
        aaa=input('需要再讲一次游戏规则吗?(1.要  2.不要):')
        if aaa=='1':
            print('好的')
            time.sleep(0.5)
            if GameChoise=='1':
                print('''二进制游戏规则:
    在这个游戏中,你会得到一个十进制的数。
    你的任务是将这个数转换为二进制的数。
    答对一题加一分,答错一题不扣分。''')
            else:
                print('''十进制游戏规则:
    在这个游戏中,你会得到一个二进制的数。
    你的任务是将这个数转换为十进制的数。
    答对一题加一分,答错一题不扣分。''')
            break
        elif aaa=='2':
            print('好的,现在开始吧')
            break
        else:
            print('请输入数字选项')
choise=1
while choise!='-1':
    time.sleep(0.5)
    while True:
        Question=input('问题数(1~15):')
        try:
            Question=int(Question)
            break
        except ValueError:
            print('请输入正确的数字\n')
    if Question<1:
        print('\n问题数不能小于1。\n因此,问题数将设置为1。')
        Question=1
    if Question>15:
        print('\n问题数不能大于15。\n因此,问题数将设置为15。')
        Question=15
    _Question=Question
    if GameChoise=='1':
        for __count in range(Question):
                QuestionNumber=str(randint(2,30))
                answer=input(QuestionNumber+'=')
                while True:
                    try:
                        answer=int(answer)
                        break
                    except:
                        print('请输入正确的数字。\n')
                        answer=input(QuestionNumber+'=')
                QuestionNumber=int(QuestionNumber)
                Trueanswer=str(bin(QuestionNumber))
                Trueanswer=int(Trueanswer.replace('0b',''))
                if Trueanswer==answer:
                    print('答案正确!')
                    UserScores+=1
                else:
                    print('答案错误,正确答案是%d'%(Trueanswer))
                    _Question-=1
    else:
        for __count in range(Question):
            Trueanswer2=randint(2,30)
            QuestionNumber2=str(bin(Trueanswer2))
            QuestionNumber2=int(QuestionNumber2.replace('0b',''))
            while True:
                answerb=input('%d='%(QuestionNumber2))
                try:
                    answerb=int(answerb)
                    break
                except:
                    print('请输入正确的数字\n')
            if Trueanswer2==answerb:
                print('答案正确')
                UserScores+=1
            else:
                print('答案错误,正确答案是%d'%(Trueanswer2))
                _Question-=1
    print('游戏结束,您答了%d题,答对了%d题。'%(Question,_Question),end='')
    choise=input('还想玩吗?继续按Enter键,不想玩可以输入“-1”退出哦')
    if choise!='-1':
        while True:
            GameChoise = input('请选择游戏:1.二进制游戏  2.十进制游戏')
            if GameChoise != '1' and GameChoise != '2':
                print('请输入正确的数字选项。\n')
            else:
                break
print('您当前的分数是%d分。拜拜,欢迎下次来玩!' % (UserScores))
if newu=='True':
    tinput = open('G:\\FilesByPrograms\\userScores.txt', 'a')
    tinput.write(UserName+','+str(UserScores)+'\n')
    tinput.close()
else:
    temp = open('G:\\FilesByPrograms\\newus.txt', 'w')
    tinput = open('G:\\FilesByPrograms\\userScores.txt', 'r')
    for lline in tinput:
        content=lline.split(',')
        if content[0]==UserName:
            temp.write(UserName+','+str(UserScores)+'\n')
        else:
            temp.write(lline)
    temp.close()
    tinput.close()
    remove('G:\\FilesByPrograms\\userScores.txt')
    rename('G:\\FilesByPrograms\\newus.txt','G:\\FilesByPrograms\\userScores.txt')
Leaderboard.updatedLeaderboard('G:\\FilesByPrograms\\userScores.txt', encoding='gbk')

【模块】

Module1:Leaderboard

class Leaderboard(object):
	@staticmethod
	def makeLeaderboard(path,data={},newFile=True):
		if newFile!=True and newFile!=False:
			raise ValueError('The File open method must be True or False')
		elif type(data)!=type({'dict':'dt'}):
			raise ValueError('Data must be a dict')
		else:
			if data=={} and newFile:
				file=open(path,'w')
				file.close()
				return
			if data=={} and not newFile:
				return
		if newFile:
			with open(path,'w') as file:
				for key,value in data.items():
					file.write(str(key)+','+str(value)+'\n')
				file.close()
				return
		else:
			try:
				file=open(path,'r')
				file.close()
			except FileNotFoundError as e:
				file.close()
				raise e
			with open(path,'a') as file:
				for key,value in data.items():
					file.write(str(key)+','+str(value)+'\n')
				file.close()
				return
	@staticmethod
	def updatedLeaderboard(path,order='desd',encoding='utf-8'):
		global file
		if order!='asd' and order!='desd':
			raise ValueError('Order must be asd(ascend) or desd(descend)')
		try:
			file=open(path,'r')
			file.close()
		except FileNotFoundError as e:
			raise e
		with open(path,'r',encoding=encoding) as file:
			line=file.readline()
			dictofRecord={}
			values=[]
			while bool(len(line)):
				massage=line.split(',')
				if massage!=['\n']:
					values.append(massage[1].喵('\n'))
					dictofRecord[massage[1].喵('\n')]=massage[0]
				line=file.readline()
			file.close()
		values.sort()
		if order=='asd':
			values.reverse()
		keys=[]
		for index in range(len(dictofRecord)):
			key=dictofRecord[values[index]]
			keys.append(key)
		with open(path,'w') as file:
			for index in range(len(values)):
				file.write(str(keys[index])+','+str(values[index])+'\n')
			file.close()
		clearBlankLine(path,encoding=encoding)
		return

Module2:clearBlankLine

def clearBlankLine(path,encoding='utf-8'):
	with open(path, 'r', encoding=encoding) as file1:
		file=''
		line=file1.readline()
		while bool(len(line)):
			if line == '\n':
				line = line.喵("\n")
			file+=line
			line=file1.readline()
		file1.close()
	with open(path,'w',encoding=encoding) as file1:
		for massage in file:
			file1.write(massage)
		file1.close()


回复

上一页1 页 / 共 1下一页
wrmdcxywrmdcxy

呃……File喵yPrograms……我也是服了

File喵yPrograms=FilebyPrograms

点赞0


评论


wrmdcxywrmdcxy

FileNotFoundError

保存分数、制作排行榜怎么可能不用文件?你懂的

ModuleNotFoundError

我都添加了模块这一分类,你懂的

若还有其它错误请指出,谢谢

点赞0


评论


xiao998xiao998

     

点赞0


评论