Having a hard time figuring out how the while(True) function is supposed to be fitted in the code. Also no idea if that is the right thing to use as I am trying to loop the game until the computer or the user hits the desired amount of points ( which the user inputs as rounds in the beginning)
import random
def main():
print
print "----------------------------------"
print "Welcome to Rock, Paper, Sciccors! "
print "----------------------------------"
rounds = input("How many points to win?: ")
user_choice = input("Choose Rock = 1 , Paper = 2 or Sciccors = 3: ")
user_score = 0
computer_score = 0
if user_choice == 1:
print "You chose Rock"
elif user_choice == 2:
print "You chose Paper"
elif user_choice == 3:
print "You chose Sciccors"
else:
print " Wrong! Choose 1, 2 or 3!"
computer_choice = random.randrange(1, 4)
if computer_choice == 1:
print "Computer chose Rock"
elif computer_choice == 2:
print "Computer chose Paper"
elif computer_choice == 3:
print "Computer chose Sciccors"
def checkResults(computer_choice, user_choice):
checkResults = computer_choice - user_choice
if computer_choice - user_choice == 0:
print("Draw!")
user_score += 1
computer_score += 1
elif computer_choice - user_choice == 1 or computer_choice - user_choice == -2:
print("Computer wins")
computer_score += 1
elif computer_choice - user_choice == -1 or computer_choice - user_choice == 2:
print("You win!")
user_score += 1
print (" Computer {} , You {}" .format(computer_score, user_score))
while(True):
if computer_score == rounds or user_score == rounds:
main()
else:
break
You can make this a bit shorter:
while computer_score == rounds or user_score == rounds:
' Your code returning computer_score and user_score
Basically a while True is an infinite loop that can only be ended using a break statement or via keyboard interrupt.
while True: is an infinite loop that can only be stopped via the command break. In your example, you have created a loop that will infinitely run the main() method (which you defined earlier, by saying def main():). The only time the loop will end is if you kill the process (i.e. using task manager on Windows), or if computer_score and user_score both become unequal to rounds (which is what your else statement is implying on the second to last line). When this happens, the program calls break which forcibly ends the loop immediately and moves on... to the end of the file (which then ends the program).
It should be noted that using a while True ... break loop is sometimes frowned upon by programmers, because it is not seen as "elegant". It is totally fine code to do, but another way to re-write the last few lines is the following:
while computer_score==rounds or user_score==rounds:
main()
This achieves the same result by running the while loop until computer_score and user_score both do not equal rounds. At that point, the while loop ends itself cleanly and ends the program by getting to the end of the file.
Related
I'm trying to make a simple 2 player game on python 2.7 .
The program will determine the result of a rock, paper, scissors game, given Player 1 and Player 2’s choices. The program will print out the result, score by each player and the total number of game played.
My question is:
The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
1.The code doesn't work when "Rock" is the input.It works when "rock" is the input. Same goes to paper and scissors. How can I make it work?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? ")).lower()
player_2 = str(input(">>Player 2? ")).lower()
2.Both player must input their choices before the program can be terminated. That means when player 1's input "-1", the program doesn't terminate immediately. It will proceed to ask player 2 for input before it get terminated. How can I make the program terminate itself immediately when player 1's input is "-1"?
From:
player_1 = str(input(">>Player 1? "))
player_2 = str(input(">>Player 2? "))
Add:
player_1 = str(input(">>Player 1? "))
if (player_1=='-1'):
print 'End of game'
break
player_2 = str(input(">>Player 2? "))
3.My code is very long, any suggestions or tips on shortening it without sacrificing any of the function?
use function definitions. Sample:
if (player_1=='-1' or player_2=='-1'):
print 'End of game'
break
elif dif in [-1, 2]:
print ('Player 1 wins.')
score1 = score1 + 1
showScore()
elif dif in [1, -2]:
print('Player 2 wins.')
score2 = score2 + 1
showScore()
else:
print('Tie')
showScore()
continue
def showScore():
print '==================='
print 'Score:'
print 'Player 1: ' + `score1`
print 'Player 2: ' + `score2`
print 'Total game played: ' + `times`
print ''
Here's a good read
For starters, I converted your program to Python 3. It's better in every way. For one thing, it has a normal definition for input.
In general, if you have N of something, where N is greater than 1, it's better to use an array. If you see repetition, move the data into an array and call a function. When N is 2, you won't necessarily shorten the code (my version is longer than yours) but you'll avoid treating the players differently because they both pass through the same logic.
Put the main logic in a function, too, and reserve the "main" code for dealing with startup & command-line stuff.
When you see a string of elifs, that's also a use data instead indicator. In my victor function, I iterate over tuples of winning combinations. You might consider how to use a dict instead.
import sys, os
def print_results( msg, times, scores ):
print( (msg) )
print( '===================' )
print( 'Score:' )
print( 'Player 1: %d' % scores[0] )
print( 'Player 2: %d' % scores[1] )
print( 'Total game played: %d' % times )
print( '' )
def victor( inputs ):
results = ( ('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock') );
for (a, b) in results:
if a == inputs[0] and b == inputs[1]:
return 1
if b == inputs[0] and a == inputs[1]:
return 2
return 0
def play(times, scores):
inputs = ['', '']
for (i, choice) in enumerate(inputs):
prompt = '>>Player %d? ' % (i + 1)
choice = input(prompt).lower()
if choice == '-1':
return False
inputs[i] = choice
result = victor(inputs)
if result == 0:
print_results('Tie', times, scores)
else:
scores[result - 1] += 1
print_results('Player %d wins' % result, times, scores)
times += 1
return True
print('''Welcome to play Rock, Paper, Scissors game. Enter -1 to end''')
scores = [0, 0]
times = 0
while play(times, scores):
pass
if scores[0] == scores[1]:
player = 'Tie'
else:
if scores[0] > scores[1]:
i = 1
else:
i = 2
player = 'Player %d' % i
print( '*******************' )
print( 'Winner: %s' % player )
print( '*******************' )
I'm having this strange problem with a simple coin flip program where, instead of giving me some sort of error, whenever i run this code it just sort of crashes. I type in a yes or no answer and hit enter, but it does nothing. Then I hit enter again and it closes out completely.
import time
import random
constant = 1
FirstRun = True
def Intro():
raw_input("Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ")
def CoinToss():
print "You flip the coin"
time.sleep(1)
print "and the result is..."
time.sleep(1)
result = random.randint(1,2)
if result == 1:
print "heads"
if result == 2:
print "tails"
while constant == 1:
if FirstRun == True:
Intro()
FirstRun = False
else:
answer = raw_input()
if answer == "yes":
CoinToss()
raw_input("Do you want to flip again? (yes or no): ")
else:
exit()
As you simply ignore the return value of the raw_input method, you don't know what the user is entered in order to break out of the loop.
Here is a simplified version of your program, note how I store the result of the raw_input method in result and use that to control the execution loop:
import random
import time
result = raw_input('Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ')
while result != 'no':
print('You flip the coin....')
time.sleep(1)
print('...and the result is...')
toss_result = random.randint(1,2)
if toss_result == 1:
print('Heads')
else:
print('Tails')
result = raw_input('Do you want to flip again? (yes or no): ')
print('Goodbye!')
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I just want to start by saying i have only just started programing and am only interested in learning.
in a very simple turn-based fighting game, i give my player the choice to attack or defend but when i input a "d" for defend it will return the attack code.
import random
import time
play = 'y'
name = ' '
playerHp = 20
attack = 4
enemyHp = 0
enemyAttack = 0
def intro ():
global name
print('''
welcome to the scary forrest!
dangerous monsters live in this
area and you must destroy or
be destroyed! attack and defend
correctly and you may survive.''')
time.sleep (2)
print ('what is your name, adventurer?')
name = input()
def randomEnemy ():
x = random.randint (3,5)
global enemyHp
global enemyAttack
enemyHp = x * 5
enemyAttack = x
print('''A goblin has jumped out to attack you, prepare to fight!''')
def battle ():
global enemyHp
global enemyAttack
global playerHp
global attack
while enemyHp > 0 and playerHp > 0:
print ('you have ' + str(playerHp) + ' health left')
time.sleep (2)
print ('the goblin has ' + str(enemyHp) + ' health left')
time.sleep (2)
print ('(a)ttack or (d)efend)
choice = input()
if choice == 'a' or 'attack':
finalattack = attack + random.randint (-1,2)
print ('you swing at the goblin and do ' + str(finalattack) + ' damage')
time.sleep(2)
print ('the goblin strikes you for ' + str(enemyAttack) + ' damage')
playerHp = playerHp - enemyAttack
enemyHp = enemyHp - finalattack
choice = 0
elif choice == 'd' or 'defend':
print ('the goblin strikes at you!')
print ('but you block his attack')
heal = random.randint (5,6) - enemyAttack
playerHp += heal
print ('you heal for ' + str(heal) + ' Hp')
choice =0
if playerHp <= 0:
print('you lose... noone finds your body because the \ngoblin drags you into his cave')
if enemyHp <= 0:
print ('you stand victorious over your foe, but noone is \nreally impressed except yo\' momma')
intro()
randomEnemy()
battle()
is there a problem with my if statement?
if some one can help me and use small words that would be greatly appreciated.
Yes, you need to test their choice with:
if choice == 'a' or choice == 'attack':
and:
elif choice == 'd' or choice == 'defend':
Your original statement:
elif choice == 'a' or 'attack':
Will always yield True as the string 'attack' is effectively True (not to mention it should be if and not elif; thanks to #chepner for spotting that).
(I haven't checked all your code).
The problem is that
elif choice == 'a' or 'attack':
is not doing what you think. Python's parser evaluates it as:
elif bool(choice == 'a') or bool('attack'):
and the boolean value of a non empty string is True. What you want is:
if choice == 'a' or choice == 'attack':
Note that I have replaced elif by a simple if, as it is the first one. (elif is short for else if).
At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}
The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()
Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()