There seems to be an error in restarting the program, it does not restart properly. It asks if you want to play again then asks for name of players tells you the goal then restarts by itself.
import random, time
#Variables
die1 = 0
die2 = 0
goal = 0
tries1 = 0
tries2 = 0
sum = 0
sum2 = 0
choice = "y"
while choice == "y":
#Asking for the player's names
player1 = input("What is your name, player1?")
player2 = input("What is your name, player2?")
#The "goal"
goal = random.randrange(5) + 1
print("The goal is:", goal)
#First while loop for the first die rolled by the first player
while die1 != goal:
die1 = random.randrange(5) + 1
time.sleep(1)
print(player1, "Your roll is:", die1)
tries1 = tries1 + 1
sum = sum + die1
time.sleep(1.5)
print("Your sum is:", sum)
#Second while loop for the second die rolled by the second player
while die2 != goal:
die2 = random.randrange(5) + 1
time.sleep(1)
print(player2, "Your roll is:", die2)
tries2 = tries2 + 1
sum2 = sum2 + die2
time.sleep(1.5)
print("Your sum is:", sum2)
time.sleep(2)
#The statement at the end of the game
print("\n\n""Player", "\t\t", "Goal", "\t\t", "# of Rolls","\t\t", "Sum of Rolls", "\n", player1, "\t\t", goal, "\t\t", tries1,"\t\t\t", sum, "\n", player2, "\t\t", goal, "\t\t", tries2, "\t\t\t", sum2)
choice = input("Would you like to play again?: (y) or (n)")
goal = 0
tries1 = 0
tries2 = 0
sum = 0
sum2 = 0
break
It's probably because at the end of the program you are breaking out of the main while loop no matter what. You should surround it with an if statement using the choice variable. Also The Last Statement is inline with the while for when the second player rolls therefore it will be executed in that loop. To fix that you going to need to reduce the indentation so it is executed at the end of the game. Also the tries1 variable is indented out a space so python will probably throw some form of syntax error at that as well.
In place of your break statement, put:
if choice != 'y':
break
This will cause the outer while loop to go back to the beginning if the user has typed 'y'. Otherwise you'll break out of the loop and the script will exit.
Move ALL the variable declarations from die1 through sum2 inside the while loop; otherwise they won't get initialized for the replay.
Related
I created a game, in which there is a secret number, and you guess, then the computer guesses. The secret number changes every round. To win, either you or the computer needs to get a score of 2.
I don't know how many rounds it will take, so I loop the game 100 times in a while loop with the condition that the user_Score and computer_Score is not equal to 2,
However, when I run my code, it seems like it just skips the condition, and goes on 100 times, and I don't understand why.
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
The above code is the part which I am talking about, it is in the near bottom of my code
import random
computer_score = 0
user_score = 0
def game():
global user_score
global computer_score
secret_number = random.randrange(10)
while True:
user_guess = input("Guess a number from 0 - 10: ")
if user_guess.isdigit():
user_guess = int(user_guess)
if 0 <= user_guess <= 10:
break
else:
print("Enter a valid number from 0 - 10")
else:
print("Please enter a valid number from 0 - 10")
computer_guess = random.randrange(10)
if user_guess == secret_number:
print("Hooray! You guessed correctly")
user_score += 1
print(f"Your score is {user_score}")
else:
print("Sorry wrong guess")
print("Now Player 2's turn")
if computer_guess == secret_number:
print("Player 2 guessed the correct number!")
computer_score += 1
print(f"Player 2's score is {computer_score}")
else:
print("Player 2 guesed incorrectly")
print( f" Your score: {user_score}" + " " + f"Player 2 score: {computer_score}")
game()
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
if user_score == 2:
print(f"Hooray! You won with a score of {user_score} points")
print(f"Player 2 got {computer_score} points")
elif computer_score == 2:
print(f"Sorry, you lost. Your score is {user_score}, and Player 2 got {computer_score} points")
print( f" Your final score: {user_score}" + " " + f"Player 2 final score: {computer_score}" )
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
If a player gets a score of two, that will not stop the inner for loop. It's going to loop to 100, because that's what you told it to do.
I'm confused why you need the inner loop at all, though. Isn't the outer while loop enough?
while user_score != 2 or computer_score != 2:
game()
Also, wouldn't you want to use and here, instead of or? The way this is written, it will only stop if both scores are equal to 2. And if one of the players gets to a score of 3 while the other player has a score of 0 or 1, this loop will never exit.
It will always show this same fault. Because, at the beginning of the game when 1st round is over, the for loop starts iterating and it will continue for 100 times. Best way is to remove the for loop and just run the while loop.
while user_score != 2 or computer_score != 2:
game()
It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))
As you can see, I'm a complete beginner at Python so any help would be appreciated. My issue is that I'm trying to test the code for all the scenarios, but I'm unable to test the tiebreaker. Sure, I could just insert Player1Score = Player2Score (which I've hash tagged to show the location) but that would just send the program into an endless loop, which defeats the purpose of the tiebreaker. So is there any way that I can I can have the program only go through the tiebreaker segment once and then let a single player win?
(I apologize if I've made any errors with my question, I'm new to stackoverflow as well)
import random
def DiceGame():
Count = 0
Player1Score = 0
Player2Score = 0
while Count <= 4:
Count += 1
print ("\n It is Round",Count, "\n")
print ("It is Player 1's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player1Score += Score
print ("Player 1, your score so far is",Player1Score)
print ("It is Player 2's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player2Score += Score
print ("Player 2, your score so far is",Player2Score)
#Player1Score = Player2Score
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame()
elif Player1Score >= Player2Score:
print ("Player 1 wins!")
elif Player1Score <= Player2Score:
print ("Player 2 wins!")
def Rolls():
Roll1 = random.randint(1,6)
Roll2 = random.randint(1,6)
print ("You got a",Roll1)
print ("You got a",Roll2)
Score1 = Roll1 + Roll2
if Score1 == 2 or Score1 == 4 or Score1 == 6 or Score1 == 8 or Score1 == 10 or Score1 == 12:
print ("Your total is even so you get an extra 10 pts.")
Score2 = Score1 + 10
print ("Your score for this round is" ,Score2)
elif Score1 == 3 or Score1 == 5 or Score1 == 7 or Score1 == 9 or Score1 == 11:
print ("Your total is odd so you lose 5 pts.")
Score2 = Score1 - 5
if Score2 <= 0:
print ("Your score has gone below 0pts. It will therefore be reset to 0pts")
Score2 = 0
print ("Your score for this round is" ,Score2)
return Score2
DiceGame()
If you really want to, you can add temporary player scores to test the function, and then remove them again if you see they work. Usually running it would just be good enough, but as you mentioned it would loop forever. This does kinda show that it works though, I guess, but I agree it's not optimal.
def DiceGame(count, p1, p2):
Count = count
Player1Score = p1
Player2Score = p2
...
Then at the bottom of your file call it as DiceGame(5, 1, 1), and in your tiebreaker call it as DiceGame(0, 0, 0). This will force a tie on the first run, and will run it normally the second time.
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame(0, 0, 0)
... # code inbetween
# end of file
return score2
DiceGame(5, 1, 1)
I recently started learning python and am trying to make a simple game in python 2.7 where a computer randomly generates a number between 1 and 6 while the player enters a number between 1 and 6. The rule is that the bigger number wins except if one person has 6 and the other has 1 in which case the person with the 1 wins. The game should also ask a first question and if the player answers "yes" then the game would continue. Else it would do other processes. When I run the code however, even if the number the computer generated is higher, it doesn't add any points to the computer. Also if I enter no or something else, the code proceeds to start the game even though I am trying to get the code to print some other lines.
I have tried just using if else statements without try and except as well as changing the beginning prompt to be a boolean statement.
import random as r
score1 = 0
score2 = 0
start = raw_input("Would you like to start a new game")
if start == "yes" or " yes":
print "Choose a number between 1 and 6"
print "Enter stop to end game"
choice1 = raw_input("Pick a number")
choice2 = r.randint (1,6)
while choice1 != "stop":
try:
if choice1 > choice2:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
elif choice2 > choice1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
except:
if choice1 == 1 and choice2 == 6:
score1 = score1 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
else:
if choice1 == 6 and choice2 == 1:
score2 = score2 + 1
print "The computer picked: " + str(choice2)
choice1 = raw_input("Pick a number")
choice2 = r.randint(1, 6)
print "Final score is: " + str(score1) + " and Computer is: " + str(score2)
elif start == "no" or " no":
print "Maybe another time"
else:
print "Please enter yes or no"
start = raw_input("Would you like to start a new game")
Program output:
Would you like to start a new game no
Choose a number between 1 and 6
Enter stop to end game
Pick a number1
The computer picked: 2
Pick a number1
The computer picked: 4
Pick a number1
The computer picked: 5
Pick a number1
The computer picked: 3
Pick a numbersotp
The computer picked: 2
Pick a numberstop
Final score is: 5 and Computer is: 0
Process finished with exit code 0
Firstly, this statement
if start == "yes" or " yes":
Is evaluated as (start == 'yes') or ('yes'). Since ' yes' is a constant and always true, it will always evaluate as true. Instead try this, it will take spaces off the front or back before evaluating.
if start.strip() == 'yes':
I would also look at the other places where you if then with multiple conditions. Consider using parens to ensure the code is evaluating as you expect. For instance,
if (choice1 == 1) and (choice2 == 6):
Also, try\expect is intended for exception logging. I'm not sure what exceptions you expect to log here. Probably better to check the user input and make sure it's a number explicitly rather than relying on try\expect
I'm making a dice roller for the game Heroscape (So we can play with offshore friends). The dice for heroscape have 6 sides. 3 sides show skulls, 1 side has a symbol and 2 sides have a shield.
I've made it randomly generate 1 of those sides, but i'd like it to list off the results at the end (i.e. You rolled 6 skulls, 2 symbols and 4 shields).
Heres my current code:
loop = 1
while loop == 1:
diceChoose = raw_input('Pick your dice. (Press 1 for a D20 roll, and 2 for attack /defense dice.) ')
if diceChoose == ('1'):
import random
for x in range(1):
print random.randint(1,21),
print
raw_input("YOUR DICE ROLL(S) HAVE COMPLETED. PRESS ANY KEY TO CONTINUE.")
elif diceChoose == ('2'):
diceNo = int(raw_input('How many dice do you need? '))
testvar = 0
diceRoll = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']
from random import choice
while testvar != diceNo:
print choice(diceRoll)
testvar = testvar + 1
if testvar == diceNo:
print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")
else: loop = raw_input('Type 1 or 2. Nothing else will work. Press 1 to start the program again.')
What i've tried is a bunch of if statements, but i've realised that if I try print ('diceRoll') all I get is the whole array instead of the randomly selected dice roll.
I'm not sure how to save each diceRoll as it happens, so I can print that number later on.
(My thinking is something like
if diceRoll == 'skull' skullNo +1
print('skullNo'))
I think a good data structure for you to use for this problem would be the Counter from the collections module in the standard library. It works a little like a dictionary, mapping objects to an integer count. However, you can add values to it and that will increment their count.
So, I'd do this:
from random import choice
from collections import Counter
diceNo = int(raw_input('How many dice do you need? '))
diceValues = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']
counter = Counter()
counter.update(choice(diceValues) for _ in range(diceNo))
print("Rolls:")
for value, count in counter.items():
print("{}: {}".format(value, count))
print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")
The key line is counter.update(choice(diceValues) for _ in range(diceNo)). This calls counter.update with a "generator expression", which produces diceNo random roll results. If you haven't learned about generator expressions yet, I suggest checking them out, as they can come in really handy.
Welcome to SO. I changed a few parts of your code to make them more similar to my style - feel free to change them back if that helps.
Change your loop code to simply:
while True:
This accomplishes the same thing, except that it is more pythonic.
Then, tab in one and tell set number values for the skull, symbol and shield. In this case, we set it to 0.
skull = 0
symbol = 0
shield = 0
Next, change the code below the diceNo = int(raw_input('How many dice do you need? ')) to this. It should be indented by one.
for x in xrange(diceNo):
import random
choice = random.randint(1,6)
if choice == 1:
skull +=1
elif choice == 2:
skull +=1
elif choice == 3:
skull +=1
elif choice == 4:
symbol =+ 1
elif choice == 5:
shield += 1
elif choice == 6:
shield += 1
This code repeats for the number of dice rolls needed. I then adds 1 to the variable associated with that name.
Directly below that, we display the info to the user.
print "You rolled %d skulls, %d symbols, and %d shields. Congrats." % (skull, symbol, shield)
Since you seemed to be having issues with the code, I decided to post it in its entirety.
while True:
#Here we set the variables
skull = 0
symbol = 0
shield = 0
diceChoose = raw_input('Pick your dice. (Press 1 for a D20 roll, and 2 for attack / defense dice.) ')
if diceChoose == '1':
import random
for x in range(1):
print random.randint(1,21),
print
raw_input("YOUR DICE ROLL(S) HAVE COMPLETED. PRESS ANY KEY TO CONTINUE.")
elif diceChoose == '2':
diceNo = int(raw_input('How many dice do you need? '))
for x in xrange(diceNo):
import random
choice = random.randint(1,6)
if choice == 1:
skull +=1
elif choice == 2:
skull +=1
elif choice == 3:
skull +=1
elif choice == 4:
symbol =+ 1
elif choice == 5:
shield += 1
elif choice == 6:
shield += 1
print "You rolled %d skulls, %d symbols, and %d shields. Congrats." % (skull, symbol, shield)
raw_input("PRESS ANY KEY TO CONTINUE.")
else: loop = raw_input('Type 1 or 2. Nothing else will work. Press 1 to start the program again.')