Dice Game score and beginning doesn't work - python

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

Related

Why colorama make printing slower in python (Thonny)?

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>>> "))

Unsupported operand types (int)+(var) error

P1Roundx=int (0)
P2Roundx=int(0)
P1Scorex=int(0)
P2Scorex=int(0)
P1Total=int(0)
P2Total=int(0)
number=int(0)
P1R1=int(0)
P2R1=int(0)
P1R2=int(0)
P2R2=int(0)
import time
Username=input("what is player 1’s username")
Username=str(Username)
if Username == ("1"):
print ("hello",Username,)
elif Username == ("2"):
print ("welcome",Username,)
else:
print("LEAVE!")
exit()
# This module determines if player 1 is authenticated or if they are not. If they are not they are forced to exit the programme
Username2=input("what is player 2's username")
Username2=str(Username2)
if Username2 == ("2"):
print ("hello,",Username2,)
elif Username2 == ("1"):
print ("welcome",Username2,)
else:
print("LEAVE!")
exit()
# This module determines if player 2 is authenticated or not and exits the programme if they are not
import random
P1R1= random.randint(1,6)
P1R1=("Your first roll is",P1R1)
P1R2=random.randint(1,6)
P1R2=("Your second roll is",P1R2)
print("Your total is",P1R1+P1R2)
P1total=P1R1+P1R2
if P1Total % 2 == 0:
P1Total=(P1Total)+P1R1
else:
P1Total=(P1Total)-5+P1R1+P1R2
print("Player 1's total score is",P1Total)
import random
P2R1= random.randint(1,6)
P2R1=("Your first roll is",P2R1)
P2R2=random.randint(1,6)
P2R2=("Your second roll is",P2R2)
print("Your total is",P2R1+P2R2)
P2total=P2R1+P2R2
if P2Total % 2 == 0:
P2Total=(P2Total)+ P2R1+P2R2
else:
P2Total=(P2Total)-5+P2R1
print("Player 2's total score is",P2Total)
time.sleep(6)
as an error, but I don't understand where the var + int is. I need help.
BTW IM NOT VERY GOOD AT THIS SNAKEY TING
When your code does this
P1R1= random.randint(1,6)
P1R1 is a number between 1 and 6; let's imagine it is 4. But then the code does
P1R1=("Your first roll is",P1R1)
It appears your intent is to print this out as a message. But what it actually does is change the value of P1R1 to the tuple ("Your first roll is",4). Then your code carries on as if P1R1 still had the value 4 because it does addition on it.
If you look at the output of this line:
print("Your total is",P1R1+P1R2)
you will see that it is
Your total is ('Your first roll is', 4, 'Your second roll is', 1)
when it is clear that you are expecting
Your total is 5
It should be easy for you to see why the code goes wrong after that.
hi remove the below lines which are assigning tuple to P1R1 and P2R2
P1R1=("Your first roll is",P1R1)
P2R2=("Your second roll is",P2R2)

Self teaching python. Having trouble with score incrementing after each round

TL:DR Trying to set up a scoring system, it doesn't seem to go up when you get than answer right
As the title says I'm teaching myself python, thus this is only the second code I have written (hints in why I'm learning python). I'm more than happy to take criticism on everything from syntax to how to better comment. With that being said, let's get to my issue.
This is a small guessing game. The book I'm reading taught the "for guessTaken" and subsequent code. My problem is in one small aspect of my code. The scoring system won't increment.
I set up the code in the for loop called games then try to have it display at that start of each round and go up with each correct guess. However, it will display 0 for the first few rounds then it will show 2 ( or whatever your current score is I think...). I think the problem is I'm calling the score +1 int in an if statement but I've moved the code around and can't figure it out.
I am aware that it's not beautiful! There are also a few bugs (number of games played isn't what you enter.)Right now I'm only working on the scoring system.
#this is a guess the number game.
import random
#Get's user's name
print("Hello. Welcome to Print's guessing game. Please enter your name: ")
userName = input()
#askes if they are ready
print("Are you ready to play " + userName + "?")
ready = input().lower()
if ready == 'yes' :
print("Let's get started")
else:
while ready != 'yes':
print("Let me know when you are ready")
ready = input().lower()
#Game start
#number of games
games = int(input("How many games would you like to play?"))
if games >= 1:
print("Let's get started")
for games in range (int(games), 1, -1):
while games != 1:
print("I am thinking of a number between 1 and 20 ")
secretNumber = random.randint(1, 20)
score = 0
print("Current score: " + str(score))
print("Debug: " + str(secretNumber))
for guessTaken in range (7, 1, -1):
print("you have " + str(guessTaken - 1 ) + " guesses left")
guess = int(input())
if guess < secretNumber:
print("Your guess is to low. Please guess again")
elif guess > secretNumber:
print("Your guess is too high. Maybe something a little lower?")
else:
break # This conditon is for the right guess.
if guess == secretNumber:
print("good Job " + userName + "! you guessed the number right!")
score = int(score + 1)
print("your score is " + str(score))
games = int(games - 1)
else:
print("Nope, the number I was thinking of was " + str(secretNumber))
print("you have " + str(games) + " games left")
elif games == 0:
while games == 0:
print("Would you like to exit? Yes or No ")
exit = input().lower()
if exit == 'yes':
quit()
else:
games = int(input("How many games would you like to play?"))
else:
print("wtf")
Your score variable is being initialized to zero every time your code goes through the while loop. If you want it to track the total score for all of the games, initialize it right after your print("Let's get started"). This will reset their score whenever they tell you how many games they want to play.
If you don't want their score to reset until they quit your program, you will have to initialize it at the beginning of your program. Up by your import random would work well.

How can I make the program restart?

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.

PYTHON - Reverse Number Guessing Game -

So I've been trying to figure out a way to write a program where the computer tries to guess the number I am thinking of, instead of the other way around where you are guessing a computer's chosen number. It works most of the time however in some situations it does repeat numbers down the chain even though I've told it before that for example the value I am thinking of is higher than '7'. In some cases it also repeats the same number again even though I tell it its higher or lower. If someone more experienced could have a look at this and tell me what am I missing in these loops it would help a great deal.
#computer enters a value x
#lower - computer guesses lower than x
#higher - computer guesses higher than x
#when string "You got it!" - game over
import random
lowBound = 0
highBound = 100
randomNumber = random.randint(lowBound,highBound)
print ("Is it ", randomNumber, " ?")
response = input()
while response != "You got it!":
if response == "higher":
lowBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
elif response == "lower":
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
random.randint is inclusive, so:
if response == 'higher':
lowBound = randomNumber + 1
and
if response == 'lower':
highBound = randomNumber - 1
Also, if the user does not enter a valid response, input() will never be called again and the program will hang in an infinite loop.
Something more robust, but doesn't handle liars:
import random
lowBound = 0
highBound = 100
response = ''
randomNumber = random.randint(lowBound,highBound)
while response != "yes":
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "lower":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
elif response == "yes":
print ("Woohooo, I'm so bitchin'")
break
else:
print ('Huh? "higher", "lower", or "yes" are valid responses.')
random.randint(a, b) returns a number between and including a and b. When generating a new random number you should use random.randint(lowBound+1, highBound-1)
One of your problems, among the others mentioned, is on these lines:
highBound = randomNumber
randomNumber = random.randint (lowBound, highBound)
You're setting a new bound, which is good, but then you're choosing another random number!
What you should be doing, is halving the bound, and asking the user higher or lower from there. Have a look at binary search algorithms.
highBound = randomNumber
randomNumber = randomNumber / 2
Your program is still going to work (with the other changes mentioned here), but this will guess your number quicker most of the time.
There is actually an example of this game on Wikipedia.
Here is my version of this exercise from Michael Dawson's book, I was trying to minimize number of tries, that computer uses. I know code looks dodgy, it is just my 2nd day:)
answer=""
guess=50
counter=3
x=25
print("hi, guess the number from 1 too 100")
input("\n")
print ("i will try to guess it")
print ("is it ", guess, "?")
while answer not in ("y","l","s"):
print ("sorry, i didn't understand \n")
answer=input("type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
if answer in ("s","l"):
while answer!="y":
if answer=="l":
guess=int(guess-x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="s":
guess=int(guess+x)
print ("how about", guess,"?")
answer=input("\nis it? type in: (Y) for yes, or (L) if it is to large, or (S) if it is to small:")
x=100/2**counter
counter=counter+1
if x<1:
x=1
elif answer=="y":
break
else:
pass
print("\ngreat! the number that you guessed is", guess)
print("i can read your mind with no guesses!")
input("\n")
You get numbers twice because random.randint's boundaries are inclusive; random.randint(1, 3) can return 1,2, or 3. Note that you should also continue to ask the human if the response is neither "higher", nor "lower" nor "You got it!":
import random
lowBound = 0
highBound = 100
while True:
randomNumber = random.randint(lowBound, highBound)
print ("Is it ", randomNumber, " ?")
response = input()
if response == "higher":
lowBound = randomNumber + 1
elif response == "lower":
highBound = randomNumber - 1
if response == "You got it!":
print ("Woohooo, I'm so bitchin'")
break

Categories