Dec-27-2020, 09:22 PM
I'm creating a Leaderboard for my Two-Player Dice Rolling Game, I want the Data inside the File to be Sorted in order and neatly presented.
Objectives:
My problems are:
I need the data neatly as shown below:
The dots are the Spaces
Position.....Name.......Score
.....1..........John.........25
.....2..........Adam.........56
Objectives:
- Sorts the Scores High to Low
- Saves the Player's Name and Score in External File
- Prints out the Top 5 Winning Scores
My problems are:
- It prints out the first line which I don't want it to as it outputs the Headings (you can copy the code and try it yourselves) and outputs the name's and scoring which is good but not in the right position
- It overwrite the names and scores for each of the two players names and scores, every time I retry the program
I need the data neatly as shown below:
The dots are the Spaces
Position.....Name.......Score
.....1..........John.........25
.....2..........Adam.........56
# -------------- Leaderboard -------------- def leaderboard(): file = open("Leaderboard.txt",'w') file.write("Position " + "Name " + "Score" + "\n") #<----- Heading file.close() file = open("Leaderboard.txt",'a') file.write((username_1) + ":" + (str(playerScore1)) + "\n") #<---- Stores Player 1's Name and Score file.write((username_2) + ":" + (str(playerScore2)) + "\n") #<---- Stores Player 2's Name and Score file.close() file = open("Leaderboard.txt",'r') readthefile = file.readlines() sortedData = sorted(readthefile, reverse = True) #<---- Sorting the Data print("==============================") print(" Top 5 Winning Scores") print() for line in range (5): #<---- Outputs the Top 5 Players print(str(line + 1) + "\t" + str(sortedData[line])) leaderboard() #------------- OUTPUT ------------ ============================== Top 5 Winning Scores 1 John:25 2 Position Name Score 3 Adam:56