如何从python中的文件创建排行榜

2024-09-30 03:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我从头到尾的代码,我希望有人告诉我下一步需要采取什么步骤来创建一个文件,以存储游戏中的最高分数。基本上,我需要最高的分数被采取并进入排行榜文件排序,这意味着我需要分数添加,删除和排序到文件中。我拥有的两个文件可以在下图中看到-

   ``` #This allows for my program to have pre-defined functions.
import time
import random
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
WinnersPoints = 0
#Allows the user to enter their profile details.
x = 1
#Creating the loop until the details are entered correctly.
while x == 1:
    Username1 = str(input("\nPlease enter your Username for player 1: "))
    Password1 = str(input("\nPlease enter your Password for player 1: "))
    Username2 = str(input("\nPlease enter your Username for player 2: "))
    Password2 = str(input("\nPlease enter your Password for player 2: "))
    #Validates the given infomation
    if Username1 == ("User1"):
        if Password1 == ("Password1"):
            print("\nWelcome User1, you are verified and may begin!")
    if Username2 == ("User2"):
        if Password2 == ("Password2"):
            print("\nWelcome User2, you are verified and may begin!")
            #Updates the loop to stop, becuase the correct information was entered.
            x += 1
    #If the details are incorrect, the user must retry.
    else:
        print(
            "\nSorry, but you are not verified to use this program. Please try again!"
        )
        #The program's loop will continue until details are entered correctly.
        x = 1
#Preperation for the dice game.
print("\nThe game shall begin in 3 seconds!")
time.sleep(1)
print("\n3")
time.sleep(1)
print("\n2")
time.sleep(1)
print("\n1")
time.sleep(1)
print("\nThe game has begun, User1 rolls first.")


#Dice rolling definition code.
def roll():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    change = 10 if (die1 + die2) % 2 == 0 else -5
    points = die1 + die2 + change
    if die1 == die2:
        points += random.randint(1, 6)
    return points

for i in range(0,5):
    Player1Points += roll()
    time.sleep(1.5)
    print("\nThe total score for ",Username1, "is:",Player1Points," Points")
    print("\nRolling...")
    Player2Points += roll()
    time.sleep(1.5)
    print("\nThe total score for ",Username2, "is:",Player2Points," Points")
    print("\nRolling...")
    
#Tiebreaker code is from Stack Overflow from a user named "Amir A. Shabani".
if Player1Points == Player2Points:
    while Player1Tiebreaker == Player2Tiebreaker:


        Player1Tiebreaker = random.randint(1,6)
        Player2Tiebreaker = random.randint(1,6)

    if Player1Tiebreaker > Player2Tiebreaker:
        Player2Points = 0
    elif Player2Tiebreaker > Player1Tiebreaker:
        Player1Points = 0
#This code declares the winner.
if Player1Points > Player2Points:
    WinnersPoints = Player1Points
    winner_User = Username1
    winner = (WinnersPoints, Username1)
elif Player2Points > Player1Points:
    WinnersPoints = Player2Points
    winner = (WinnersPoints, Username2)
    winner_User = Username2
#This is where the code stops from "Amir A. Shabani".
print('\nCongrats,', winner_User,'you won with',WinnersPoints,'Points')
#Uploads data to a file.
if Player1Points < Player2Points:
    with open('scores.txt', 'a') as f:
            f.write("Total Score For Player 2 is:" + str(Player2Points)+ ("\n"))
            f.close
else: Player1Points > Player2Points
with open('scores.txt', 'a') as f:
            f.write("Total Score For Player 1 is:" + str(Player1Points)+ ("\n"))
            f.close
#Displays the leaderboard file data.
f = open('leaderboard.txt', 'r')
file_contents = f.read()
print (file_contents)
f.close()```

Tags: thetoforiftimeissleeprandom
1条回答
网友
1楼 · 发布于 2024-09-30 03:25:28

您可以这样保存一个文本文件:

“排行榜=['username1',1996,12.8],'username2',3245,13.9],'username3',1228,11.9]]

并使用命令:

exec(打开('path/to/this/file.txt').read()) 将成为排行榜的一个变量

要保存排行榜的更改版本,请使用:

file=open('path/to/your/file.txt','w') file.write(str(leadboard.append([player.name,player.score,player.time]))

那就行了

相关问题 更多 >

    热门问题