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.
Related
I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card of the dealer should be hidden).
o If the player has 21 he wins his bet; else if the dealer has 21 then the dealer wins and the player loses his bet.
o The player can only select to draw a new card (hit) or pass. Repeat until the player passes or busts. If the player goes above 21 then he busts.
o Then the dealer draws cards (automatically) until he either busts or reaches 17 or higher.
o Values of cards: A= 1 or 11 (the highest that does not bust you) and J=Q=K=10
o Note: in blackjack there are more actions: insurance, double, split; those are not required to be implemented as they would make the code you have to produce much, much longer and harder
I will show you my code below when I tried to run it, it said that the name "total" is not defined on the function game, but earlier on I have already defined it. I don't know how can i fix it.
import random
N=int(input("Please enter number of decks of cards used: "))
deck= [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
wins=0
losses=0
chip_pool = 100
bet = 1
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card=deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def play_again():
again = input("Do you want to play again? (Y/N) : ").lower()
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
game()
else:
print("Thank you for playing.")
exit()
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
def hit(hand):
card = deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def print_results(dealer_hand, player_hand):
clear()
print("\n WELCOME TO BLACKJACK!\n")
print("The dealer has a " + str(dealer_hand) + "for a total of" + str(total(dealer_hand)))
print("You have a" + str(player_hand) + "for a total of" + str(total(player_hand)))
def blackjack(dealer_hand, player_hand):
global wins
global losses
if total(player_hand) == 21:
print_results(player_hand,dealer_hand)
print("Congratulations! You got a blackjack.\n")
wins = wins + 1
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand,player_hand)
print("Sorry you lose. The dealer got a blackjack.\n")
chip_pool -= bet
loses = loses + 1
play_again()
def score(dealer_hand,player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print("Congratulations! You got a blackjack1\n")
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print("Sorry you lose. The dealer go a blackjack\n")
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print("Sorry, you busted. You lose.\n")
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print("Dealer busts. You win!\n")
chip_pool += bet
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Sorry, the score is not higher than the dealer. You lose.\n")
chip_pool -= bet
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Congratulations. Your score is higher than the dealer. You win.\n")
chip_pool += bet
elif total(player_hand) == total(dealer_hand):
print_results(playe_hand, dealer_hand)
print("There is a tie. In a tie dealer always wins!\n")
chip_pool -= bet
def make_bet():
global bet
bet = 0
print("What amount of chips would you like to bet? ")
while bet == 0:
bet_comp = input()
bet_comp = int(bet_comp)
if bet_comp >= 1 and bet_comp <= chip_pool:
bet = bet_comp
else:
print("Invalid bet, you only have" + str(chip_pool) + "remaining")
def game():
choice = 0
print("Welcome to Blackjack!\n")
dealer_hand = deal(deck)
player_hand = deal(deck)
print("The dealer is showing a " +str(dealer_hand[0]))
make_bet()
print("You have a " + str(player_hand))
blackjack(dealer_hand, player_hand)
quit = False
while not quit:
choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
if choice == 'h':
hit(player_hand)
print(player_hand)
if total(player_hand) > 21:
print("You busted")
chip_pool -= bet
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
print(dealer_hand)
if total(dealer_hand) > 21:
print("Dealer busts. You win!")
chip_pool += bet
play_again()
score(dealer_hand, playe_hand)
play_again()
elif choice == "q" :
print("Thank you for playing. Hope you enjoyed!")
quit = True
exit()
if __name__ == "__main__":
game()
You have not defined the function total that you call. Try adding this to your code
def total(array):
total = 0
for card in array:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
However I see some more issues in your code that will need fixing later on! Stand or Quit do nothing currently, and on busting there is an exception thrown since chip_pool never had a value assigned to it
EDIT 1:
You defined a function
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
Similar to what I suggested. Maybe it was just a typo but you need to do the following
Rename the function from total_hand to total OR call total_hand
Change the definition from total_hand() to total_hand(hand)
I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
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!
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")
I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break