How do I make the leaderboard section of the code work? - python

So I'm relatively new to python and I'm having issues with fixing the leaderboard part of the code. I've spent a lot of time but I haven't been able to make it work. I know there are a few examples of answers to the same question on stack overflow but so far none of them have worked. Is there any way to make it work?
#task2
import random #When the user rolls the dice this will give them a random number
import time #It'll pause the sequence for a specific amount of time
enter = 0 #the number of times a user enters Username and Password
tries = 0 #this is the number of times a user fails to enter the correct verification
rolling = 0 #this is the number of rounds the game continues to loop, which is 5
i = 0 #required for for...loop
rounds = 0 #this is for last while statements where the winner is decided
p1sc = 0 #for total score of player 1 which is added or taken away each round
p2sc = 0 #for total score of player 2 which is added or taken away each round
while enter == 0: #if enter becomes anything other than 0, the game will start
try:
leaderboard_list = [0,0,0,0,0,'-','-','-','-','-']
file = open('leaderboard.txt', 'x')
for item in leaderboard_list:
file.write('%s\n' % item)
file.close
except:
print("")
code = input("Input the authorization code to play this game: ")
if code == ("password"): #Checking whether the input code is "dice" or not
print("You have entered authorization code correctly, enjoy the game!")
player1 = input("What would Player 1 like to be called? ") #asking user 1 to input the name they want to be called
player2 = input("What would Player 2 like to be called? ") #asking user 2 to input the name they want to be called
print(player1,"and",player2 +", prepare to play, the game will now start...")
time.sleep(1)
enter = 1
else:
print("\nIncorrect authorization code please try again!")
tries = 1 + tries #required for next if statement
if tries == 4: #If user enters wrong password or username 4 times than the user have to wait 1 minute and try again until the user gets username and password correct
print("You have entered incorrect authorization code too many times, please try again after 1 minute!")
time.sleep(60) #For 1 minute the user won't be able to try again
tries = 0
else:
print()
if enter == 1:
for i in range(0,5): #this will allow the upcoming code to be looped only 5 times
while rolling == 0: #if rolling is 1 then player 2 has to roll the dices this continues, until i is in range(0,5)
p1 = input("\n"+ str(player1) +", press r to roll the dice: ")
if p1!= "r":
print()
else:
p1dice1 = random.randint(1,6) #allows any number to be chosen from 1 to 6
p1dice2 = random.randint(1,6)
p1dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p1dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p1dice2)
p1total = p1dice1 + p1dice2
rolling = 1 #for next while loop statement which is for player 2
if p1dice1 == p1dice2: #if statements according to the game rule
print("You rolled a double.Well done! You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p1dice3)
p1total = p1total + p1dice3
else:
p1total = p1total
if p1total%2 == 0: #To check whether the number is odd or even
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p1sc,"as a total score.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5 #after it is subtracted from 5, elif statement is used as only after subtracting the number; the number can be less than, equal or greater than 0
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5. Now,you have",p1sc,"as a total score.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p1sc,"as a total score.")
else:
print()
while rolling == 1: #if rolling is 0 then player 1 has to roll the dices this continues, until i is in range(0,5)
p2 = input("\n"+ str(player2) +", press r to roll the dice: ")
if p2!= "r":
print()
else:
p2dice1 = random.randint(1,6)
p2dice2 = random.randint(1,6)
p2dice3 = random.randint(1,6)
print("Rolling dice 1...")
time.sleep(1)
print("Dice 1 rolled a", p2dice1)
print("Rolling dice 2...")
time.sleep(1)
print("Dice 2 rolled a", p2dice2)
p2total = p2dice1 + p2dice2
rolling = 0 #for player 1 to roll the dices again
rounds = rounds + 1 #for the game to loop 5 times and be checked by upcoming while rounds == 5
if p2dice1 == p2dice2:
print("You rolled a double.Well done!You get to roll one more die.")
time.sleep(1)
print("Rolling dice 3...")
time.sleep(1)
print("Dice 3 rolled a", p2dice3)
p2total = p2total + p2dice3
else:
p2total = p2total
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10. Now,you have",p2sc,"as a total score.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5. Now,you have",p2sc,"as a total score.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 and went below 0 but according to the game rule, the total score can't go below 0. So, your total score remains 0.")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5. Now,you have",p2sc,"as a total score.")
else:
print()
while rounds == 5:
while p1sc == p2sc:
print("\nAs you both have the same score, now you both will have to keep rolling 1 dice until someone wins!")
time.sleep(2)
p1 = input("\n"+ str(player1) +", press y to roll the dices: ")
if p1 != "y":
print()
else:
p1dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p1dice1)
p1total = p1dice1
if p1total%2 == 0:
p1sc = p1sc + p1total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p1total%2 == 1:
p1sc = p1sc + p1total - 5
if p1sc == 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted 5.")
elif p1sc < 0:
p1sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p1sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
p2 = input("\n"+ str(player2) +", press y to roll the dices: ")
if p2 !="y":
print()
else:
p2dice1 = random.randint(1,6)
print("Rolling the dice...")
time.sleep(1)
print("The dice rolled a", p2dice1)
p2total = p2dice1
if p2total%2 == 0:
p2sc = p2sc + p2total + 10
print("You have total score as an even number. So,according to the game rule;your new total score now will be added by 10.")
elif p2total%2 == 1:
p2sc = p2sc + p2total - 5
if p2sc == 0:
print("You have total score as an odd number. So,according to the rule;your new total score now will be subtracted 5.")
elif p2sc < 0:
p2sc = 0
print("Your total score was subtracted by 5 :(;(")
elif p2sc > 0:
print("You have total score as an odd number. So,according to the game rule;your new total score now will be subtracted by 5.")
else:
print()
if p1sc > p2sc:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player1)+" is the winner with "+str(p1sc)+" points.")
print(str(player2)+", better luck next time. Your total score is "+str(p2sc)+".")
rounds = 6 #to stop the loop
else:
time.sleep(1)
print("\nThe scores have been added up and....")
time.sleep(3)
print(str(player2)+" is the winner with "+str(p2sc)+" points.")
print(str(player1)+", better luck next time. Your total score is "+str(p1sc)+".")
rounds = 6 #to stop the loop
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
for x in range(0,4): #Shuffles the list down depending on how high the scoore was
curr = leaderboard_list[x]
if leaderboard >= curr:
for i in range(5, x + 1, -1):
leaderboard_list[i + 4] = leaderboard_list[i + 3]
leaderboard_list[i - 1] = leaderboard_list[i - 2]
leaderboard_list[x] = leaderboard
leaderboard_list[(x + 5)] = winner
break
else:
pass
file = open('score.txt', 'w+') #Writes the updated highscore list into the txt file
for item in leaderboard_list:
file.write('%s\n' % item)
file.close()
print("""The highscores for this game are """) #Prints the highscore list
for x in range(5):
print(x + 1,") ", leaderboard_list[x], " by ", leaderboard_list[x + 5])
The error message:
Traceback (most recent call last):
File "main.py", line 190, in <module>
leaderboard_list[j] = int(leaderboard_list[j])
IndexError: list out of range
Thanks! Any help would be appreciated!

The relevant part of your code is this:
leaderboard_list = [] # Reads the highscore list
with open('leaderboard.txt') as reader:
for line in reader:
leaderboard_list.append(line.rstrip("\r\n"))
for j in range(0,4): #Converts the scores from the list into integers
leaderboard_list[j] = int(leaderboard_list[j])
When posting a question here, it's probably best to keep it small like that.
Anyway, you are iterating over range(0,4). This gives you:
[0, 1, 2, 3] as values for j.
So essentially, your for-loop is doing the following:
leaderboard_list[0] = int(leaderboard_list[0])
leaderboard_list[1] = int(leaderboard_list[1])
leaderboard_list[2] = int(leaderboard_list[2])
leaderboard_list[3] = int(leaderboard_list[3])
And this crashes with an IndexError.
That means that one (or all) of these indexes do not exist. The list is probably either empty, or less than 4 lines long.
The easiest way to debug this is to simply print the list before you do this operation:
print(*leaderboard_list)
And the operation that you're trying to do (turn them all into int values) can be done like this:
leaderboard_list = map(int, leaderboard_list)
Good luck on your Python journey!

Related

Allowing my Python program to accept non-integer values

I am having trouble finding a way to allow my Python project to accept a non-integer value and not crash. My intention is that when the user inputs a non-integer value or any value other than the ones assigned by the random sampkle, the game will prompt the function "repeatr()" which will tell them to input the value again.
I've put in the entire solution, but the most relevant sections are in bold and it's that particular section that I want to allow to prompt the repeatr() function instead of crashing
import random
user_wins = 0
user_draws = 0
user_losses = 0
rounds = 0
def closr():
quit()
def repeatr():
print("That is not a valid input. Please input a correct value.")
**def promptr():
print("Please select an input from the following options.")**
options = [5, 4, 3, 2, 1]
randomlist = random.sample(range(1, 5), 3)
randomr = randomlist
x=1
while x == 1:
user_input = int(input("Type 5/4/3/2/1 or Q to quit."))
if user_input in options:
x=2
elif user_input != options:
repeatr()
continue
elif user_input == "q":
closr()
**y=1
while rounds < 10:
promptr()
player_choice = int(input(randomlist))
npc = random.randint(1,5)
if player_choice in randomr:
print("Your opponent has drawn: ", npc)
y=2
else:
repeatr()
continue**
if npc > int(player_choice):
print("You have been defeated this round.")
user_losses = user_losses + 1
print("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc < player_choice:
print ("You have won this round.")
user_wins = user_wins + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc == player_choice:
print ("You have drawn this round.")
user_draws = user_draws + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
rounds = 10
if user_losses < user_wins:
print("You have won the game!")
elif user_losses > user_wins:
print("You have lost this game. Better luck next time!")
elif user_losses == user_wins:
print("The game has ended in a draw.")
print("the number of wins you had was:" , user_wins)
print("the number of draws you had was:" , user_draws)
print("the number of losses you had was:" , user_losses)
print("The final score was (Player vs CPU):" , user_wins, ":" , user_losses)
u=1
while u == 1:
resu=input("Press Q to quit the game.")
if resu=="q":
closr()
I hope the question makes sense.

Dice rolling program with counter

I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")

How to fix "IndexError: list index out of range" on Python

I'm trying to debug some code I have written for homework, but I cannot fix an error that occurs no matter what I try.
I've tried copying some code from my friends, but no matter what code I try I keep getting this error.
#NEA 2019 DICE GAME
from time import sleep as wait
from random import randint as rand
#Here I have imported my modules that I will use later on.
Check1 = 0
#Here I create a check variable, for use in the usernames section.
print("welcome to Dice Game!")
print("Main Menu: \n 1. Play Game \n 2. Register User \n 3. View Leaderboard \n 4. Quit Game")
MenuChoice = int(input("Please enter the number of the option you would like to choose."))
#Nice greeting for the user, and a menu.
elif MenuChoice == 1:
while Check1 == 0:
Namae = input("Player One, Please enter your username: \n")
with open('Usernames.txt') as openfile:
if Namae in openfile.read():
print("Username",Namae, "Valid!")
Check1 = 1
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
#This 'if' statement allows the user to log in using a universal passkey, or allows an administrator to log in using a backdoor.
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username",Namae, "Invalid!")
#This block allows a user to log in as player 1.
while Check1 == 1:
Namae2 = input("Player Two, Please enter your username: \n")
if Namae == Namae2:
print("Both players can't have the same username!")
Namae2 = ''
with open('Usernames.txt') as openfile:
if Namae2 in openfile.read():
print("Username", Namae2, "Valid!")
Check1 = 0
Pass = input("Please enter the passkey:")
if Pass == 'VN467' or Pass == 'Backdoor':
print("User Authenticated!")
else:
print("Invalid Passkey!")
else:
print("Username", Namae2, "Invalid!")
#This block allows a user to log in as player 2.
P1total = 0
P2total = 0
for i in range (1,5):
print("Game starting!")
wait(1)
print("ROUND", i)
print(Namae, " Press 'Enter' to roll")
#This gives the player a message box to allow them to roll.
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This is the command to roll the dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This gives the player another dice if they roll a double.
else:
Roll3 = 0
#This sets the value of Roll3 to zero, to prevent a NameError later on.
TempTotal = Roll1 + Roll2 + Roll3
print("The total of the dice is", TempTotal)
#These lines add together all of the dice.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#These lines check if the dice total is even, then adds 10 if it is.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#These lines check if the dice total is odd, then subtracts 5 if it is.
P1total = P1total + TempTotal
if P1total < 0:
P1total = 0
#These lines make sure that the total cannot go below 0, and sets it to 0 if it does.
print(Namae, "Your total is", P1total)
#This prints the current total for player 1.
print(Namae2," Press 'OK' to roll")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This rolls the two dice.
if Roll1 == Roll2:
print("Double! You get an extra dice!")
Roll3 = rand(1,6)
#This adds another dice if the player rolls a double.
else:
Roll3 = 0
#This sets Roll3 to 0 to prevent a NameError later on in the code.
TempTotal = Roll1 + Roll2 + Roll3
#This adds up the dice to create a total.
print("The total of the dice is", TempTotal)
#This tells the player what the dice rolled.
if TempTotal%2 == 0:
print("Even total! +10 points!")
TempTotal = TempTotal + 10
#This adds 10 points to the total if they roll an even number.
else:
print("Odd total! -5 points")
TempTotal = TempTotal - 5
#This takes away 5 points from the total if they roll an odd number.
P2total = P2total + TempTotal
if P2total < 0:
P2total = 0
print(Namae2, "Your total is", P2total)
if P1total == P2total:
print("There is a draw! \n Both players will roll 1 die.")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that there cannot be a draw
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
while Roll1 == Roll2:
print("Another Draw!")
Roll1 = rand(1,6)
Roll2 = rand(1,6)
#This makes it so that if the first reroll ends in a draw, there will keep being rerolls until there is no longer a draw.
print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
if Roll1 > Roll2:
print(Namae, "Wins!")
#Prints a winning message.
else:
print(Namae2, "Wins!")
#This prints a winning message
elif P1total > P2total:
print(Namae, "wins!")
Winner = Namae
WinScore = P1total
#This prints a message if player 1 wins
else:
print(Namae2, "wins!")
Winner = Namae2
WinScore = P2total
#This prints a message if player 1 wins.
#Winscore and Winner are used to append the winner to a file later on.
LeaderboardFile = open("Leaderboard.txt", "a+")
#This opens the file to be appended
FullFileInput = Winner + "," + str(WinScore) + "\n"
#This combines the two variables from earlier into one, to make it easier to append.
LeaderboardFile.write(FullFileInput)
#This appends FullFileInput to the file.
LeaderboardFile.close
#Closes the File.
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
#Opens the file for reading.
Array = []
#Creates an empty array
FileLength = len(open("Leaderboard.txt").readlines())
#This reads how many lines the file has
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
#This splits the file every time there is a comma
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
#This sorts the list in descending order, using score.
x = 1
for counter in range(0,5):
print(len(SortedArray))
holder = SortedArray[(len(SortedArray)-x)]
#This causes an error, for seemingly no reason.
print(x, ":",holder[0], holder[1])
#This prints the leaderboard, one line at a time.
x = x + 1
#Increments x by 1.
elif MenuChoice == 3:
print("Top 5 Scores:")
LeaderboardFile = open("Leaderboard.txt", "r")
Array = []
FileLength = len(open("Leaderboard.txt").readlines())
for counter in range(FileLength):
record = LeaderboardFile.readline()
cells = record.split(",")
Array.append(cells)
SortedArray = sorted(Array, key = lambda x: x[1])
x = 1
for counter in range(5):
holder = SortedArray[(len(SortedArray)-x)]
print(x, ":",holder[0], holder[1])
x = x + 1
#Lines 198 to 211 are all copied and pasted from the leaderboard earlier.
#This code is a formatting disaster, I'm sorry.
After messing around with the game for a bit, with the error appearing every time it attempted to show the leaderboard, I have some files.
Leaderboard.txt:
Contains scored in the format:
Username1,score
Username2,score
And so on...
Usernames.txt:
Contains all valid usernames.
I would expect the result to be something along the lines of:
Top 5 Scores:
1: Alpha 100
2: Beta 91
3: Gamma 85
4: Delta 76
5: Epsilon 69
Instead, the code prints:
Top 5 Scores:
1: Alpha 1
2: Alpha 1
(this always prints the first value in the file twice, without sorting it.)
And then I get the error:
Traceback (most recent call last):
File "main.py", line 200 in <module>
holder = SortedArray[(len(SortedArray)-x)]
IndexError: list index out of range.
The 'IndexError: list index out of range' means that your list indices are out of range. You are trying to refer to some index that doesn't even exist.
holder = SortedArray[(len(SortedArray)-x)]
x = x + 1
For example if x becomes greater than (len(SortedArray) you will get a negative index that can trigger that error.
I hope you don't mind, but I rewrote a part of your code.
elif MenuChoice == 3:
print("Top 5 Scores:")
Array = []
try:
with open("Leaderboard.txt", "r") as LeaderboardFile:
for l in LeaderboardFile.readlines():
name, score = l.split(',')
name = name.strip()
score = int(score.strip())
Array.append([name, score])
except Exception:
print('FileNotFound')
Array = sorted(Array, key = lambda x: x[1], reverse=True)
for i in range(5):
print(f'{i+1}: {Array[i][0]} {Array[i][1]}')
Please, note for next time that because this question is very specific to your own code it is less suitable for SO, but more for https://codereview.stackexchange.com/.
Good luck with your homework assignment.

Python: Lucky sevens game (Average number of dice rolls)

I'm trying to write a count function, to calculate the number of rolls it takes to hit 0. And it is returning me the random integer of the diceroll + 1, how do I get it to count the number of times the myroll variable occurs.
import random
def luckysevens():
mypot = int(input("Please enter the amount of money you want to in the pot: "))
while mypot > 0:
diceroll = random.randint(1, 6)
print(diceroll)
myroll = (diceroll + diceroll)
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$", mypot)
else:
mypot = mypot - 1
print("Your roll was", myroll, "you lost 1$", mypot)
if mypot == 0:
print("Your out of money!")
sum = 0
for count in range(myroll + 1):
sum = sum + count
print(count)
luckysevens()
If you want to count how many rolls before the loop exits, simply add another counter variable. I also am assuming you're rolling a couple dice, so added different random calls for each one.
import random
mypot = int(input("Please enter the amount of money you want to in the pot: "))
num_rolls = 0
while mypot > 0:
die_1 = random.randint(1,6)
die_2 = random.randint(1,6)
myroll = die_1 + die_2
num_rolls += 1 # count rolls
if myroll == 7:
mypot = mypot + 4
print("Your roll was a 7 you earned 4$",mypot)
else:
mypot = mypot - 1
print("Your roll was",myroll,"you lost 1$",mypot)
if mypot == 0:
print("Your out of money!")
print 'Num rolls: {}'.format(num_rolls) # print rolls

Dice-rolling game doesn't change results

Doing a dice Rolling game in python, and whenever I start my second round I still end up getting the same dice results from the previous round.
import random
import time
#gets the dice side
def roll_dice(sides):
dice_results = list()
for side in sides:
roll_result = random.randint(1,side+1)
dice_results.append(roll_result)
return dice_results
#pulls a dice out from the list
def dice_fell(roll_result):
player1_dice = player1_dice_results
player2_dice = player2_dice_results
for item in player1_dice:
if item % 4 == 0:
player1_dice.remove(item)
return player1_dice
for item in player2_dice:
if item % 4 == 0:
player2_dice.remove(item)
return player2_dice
# variables
dice_set1=[4, 6, 8, 10, 12, 20, 100]
dice_set2=[4, 6, 8, 10, 12, 20, 100]
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit= input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
print("You are rolling...")
time.sleep(2)
print("You have rolled: ",player1_final_results)
if len(player1_final_results) < 7:
print("Sorry player 1, some of your dice have fallen off the table!")
print()
print("Your total is: ",player1_total)
print()
print("Player 2 is rolling...")
time.sleep(2)
print("Player 2 has rolled:" ,player2_final_results)
if len(player2_final_results) < 7:
print("Sorry player 2, some of your dice have fallen off the table!")
print()
print("Player 2's total is: ",player2_total)
print()
if player1_total > player2_total:
print()
print("You have won the round with,",player1_total,"!"),
player1_score += 1
print("Your score is: ",player1_score)
elif player2_total > player1_total:
print()
print("Player 2 has won the round with,",player2_total,"!"),
player2_score += 1
print("Player 2's score is: ",player2_score)
if player1_score == 3:
print("Congratulations, you won!")
elif player2_score == 3:
print("Player 2 wins! Better luck next time champ!")
I believe that I've fixed the indentation problems.
I have reproduced the problem.
As Kevin said, your immediate problem is that you roll the dice only once, before you enter your while loop. Here's what it looks like with the rolls inside the loop, but after the player decides whether to continue.
dice_set1=[4,6,8,10,12,20,100]
dice_set2=[4,6,8,10,12,20,100]
player1_score = 0
player2_score = 0
while player1_score < 3 or player2_score < 3:
# This part just announces what happens
exit = raw_input(str("Press Enter to start! Press 'q' to leave after each round! \n"))
if exit != "q":
print("Let's begin! Be careful for the small table!")
elif exit == "q":
quit()
player1_dice_results = roll_dice(dice_set1)
player2_dice_results = roll_dice(dice_set2)
player1_final_results = dice_fell(player1_dice_results)
player2_final_results = dice_fell(player2_dice_results)
player1_total= sum(player1_dice_results)
player2_total= sum(player2_dice_results)
print("You are rolling...")
... # remainder of code omitted
That said, do note that you have several other problems with the program. You won't terminate until both players have won three times -- use and instead of or in the while condition.
Most of my other comments are more appropriate for the codeReview group; you might post there when you're done debugging.

Categories

Resources