Whenever an output should result in a change of shield, the program just says 'You have 5 shields' followed by 'You Win'. I think I might have made a mistake when passing over the variables from one function to the next. Thank you in advance for the help!
def main():
while TakeTurn(word,shield) == False:
if shield == 1:
word1 = "shield"
else:
word1 = "shields"
print ("You have", shield, word1,)
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
#This function is the actual 'game' and will deterine what happens to the character
def TakeTurn(word1,shield1):
time.sleep(1.5)
#This means that when the user reaches 0 shields, they lose.
if shield1 < 1:
return True
#Whatever the user inputs will not actually affect the outcome
print ("You have reached", word1 ,"junction.\nDo you want to turn left (L), turn right (R) or go straight ahead(S)?")
turning = input()
#This is a simple instruction that means that the first time you come to a junction, it will say 'a junction' but the second time it will say 'another junction'
word1 = "another"
#This 'if' statement means that the program will only continue if the user has inputed the letters 'L', 'R' or 'S'
elif turning not in ["L","R","S","l","r","s"] :
time.sleep (0.7)
print ("Sorry, I didn't understand that")
TakeTurn()
else:
choice = randint (1,10)
#This is just going to display a random message which will affect the outcome
time.sleep (1)
if choice == 1:
print ("You have found the exit!")
return True
elif choice == 2:
print ("You have found a shield!")
time.sleep(1)
shield1 = shield1 +1
return False
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 +2
return False
elif choice == 4:
print ("You have found three shields!")
time.sleep(1)
shield1 = shield1 +3
return False
elif choice == 5:
print ("A fairy has jumped into your pants!")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
elif choice == 6:
treasurechest(shield1)
return False
elif choice == 7:
print ("You have tripped over a log!")
time.sleep(2)
print ("You lose a shield")
time.sleep(1)
shield1 = shield1 -1
return False
elif choice == 8:
print ("An angry teenager is staring at you in the eye.")
time.sleep(2.5)
print ("He uses laziness...")
time.sleep(1.5)
print ("It's super effective!")
time.sleep(1)
print ("You lose three shields")
time.sleep(1)
shield1 = shield1 -3
return False
elif choice == 9:
print ("You have encountered an ogre...")
time.sleep(1.5)
print ("He bashes you over the head with a steel bar")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
else:
print ("A goblin aproaches and says the following:")
time.sleep(2)
goblin(shield1)
return False
You should refactor main and TakeTurn to make shield and word explicit arguments and return values. This prevents relying on scope for access to variables, without having to use global (which is usually a bad sign):
def main(shield, word):
while True:
shield, word, finished = TakeTurn(shield, word)
if finished:
break
word1 = "shield" if shield == 1 else "shields"
print ("You have {0} {1}".format(shield, word1))
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
And have TakeTurn return multiple values accordingly, e.g.:
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 + 2
return shield1, word1, False
You could make things neater by making choices a list of dictionaries and picking randomly from it:
choices = [{"texts": [("You have found two shields!", 1)],
"shield change": 2, "return": False},
{"texts": [("You have encountered an ogre...", 1.5),
("He bashes you over the head with a steel bar", 2),
("You lose two shields", 1)],
"shield change": -2, "return": False},
...]
Then your main section, instead of all the elifs, becomes simply:
choice = random.choice(choices)
for text, sleep_time in choice['texts']:
print(text)
time.sleep(sleep_time)
shield1 += choice['shield change']
return shield1, word1, choice['return']
Related
def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.
I'm trying to create a simple two player game like the classic Battleship. Hence I'm beginning to learn Python and I'm keeping it simple. I have created a 5x5 grid and I want the players (2) to be able to place one ship 1x1 anywhere on the board. Then they take turns guessing where the other person placed their ship.
When I compiled my code I got an indent error on line 61 "else: ". I'm aware that the "H" and "M" for hit and miss will overlap since I'm outputting it to the same playing board.
I guess what I need help with is the while loops in my code.
import sys
#////////////////////////////Setting up board////////////////////////////////////
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#///////////////////////////Getting input//////////////////////////////////////////
def user_row():
get_row = raw_input("Enter ship row between 1 and 5")
#Not shure if this is the best way of checking that the input is an int
if int(get_row) == False:
print "You must enter an integer between 1 and 5"
get_row = raw_input("Enter ship row...")
if int(get_row) == False:
sys.exit()
def user_col():
get_col = raw_input("Enter ship col between 1 and 5")
if int(get_col) == False:
print "You must enter an integer between 1 and 5"
get_col = raw_input("Enter ship col...")
if int(get_col) == False:
sys.exit()
#/////////////////////////Intro//////////////////////////////////////////////////////
print "Let's play Battleship!"
print "This is your ocean"
print_board(board)
#////////////////////////Placing ships//////////////////////////////////////////////
print "Player 1 your up!"
print "Player 2 look away!"
print "Place your ship..."
#Not shure if this will call the two functions chronologic and store them as index 0 and 1 in my array. That is what I want it to do
user1_ship = [user_row(), user_col()]
print_board(board)
print "Player 2 your up!"
print "Player 1 look away!"
print "Place your ship..."
user_2 = [user_row(), user_col()]
#///////////////////////guesswork?//////////////////////////////////////////////////
#Maybe while loops inside while loops is not the best way of running the code over and over until someone sinks the other persons ship
#What Im expecting is the first inside while loop to break the outer loop if the player hits the other players ship otherwise break itself. Likewise with the second inner loop.
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
else:
board[user1_guess[0]][user1_guess[1]] == "M"
print "You missed"
break
while True:
print "Player 2 your turn"
user2_guess = [user_row(), user_col()]
if user2_guess == user1_ship:
board[user2_guess[0]][user2_guess[1]] == "H"
print "PLAYER 2 WINS!"
break
else:
board[user2_guess[0]][user2_guess[1]] == "M"
print "You missed"
break
Your indentation is incorrect... Look at this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
The break statement must have the same indentation as the print statement like this:
while True:
while True:
print "Player 1 your turn"
user1_guess = [user_row(), user_col()]
if user1_guess == user2_ship:
board[user1_guess[0]][user1_guess[1]] == "H"
print "PLAYER 1 WINS!"
break
If you have some time, please read a Python Styleguide to improve the quality of your code.
Whenever I say "no" to the "would you like to attempt the puzzle?" thing, nothing comes up. I even just put a print ("test") after all of that code once and it didn't execute the test.
puzzle1 = raw_input ("The cave has a small golden inscription on the door with a dial for imputting numbers. A puzzle! Would you like to attempt the puzzle?")
#Puzzle 1
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
print ("You press the button on the door. A small dial turns quickly and picks a random number between 1 and 50. Now you must guess the number being told to go 'higher' or 'lower'. You have only 5 tries to guess the random number.")
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
from random import randrange
puzzle1number = randrange(1,51)
puzzle1number2 = raw_input ("What is the first guess? You have 5 tries left.")
if int(puzzle1number2) == puzzle1number:
print ("You did it first try! Lucky you!")
if int(puzzle1number2) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) < puzzle1number:
print ("Higher!")
if int(puzzle1number2) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number3 = raw_input ("What is the second guess? You have 4 tries left.")
if int(puzzle1number3) == puzzle1number:
print ("You did it second try! Great guessing!")
if int(puzzle1number3) < puzzle1number:
print ("Higher!")
if int(puzzle1number3) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) == puzzle1number or int(puzzle1number3) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number4 = raw_input ("What is the third guess? You have 3 tries left.")
if int(puzzle1number4) == puzzle1number:
print ("You did it third try! Great guessing!")
if int(puzzle1number4) < puzzle1number:
print ("Higher!")
if int(puzzle1number4) > puzzle1number:
print ("Lower!")
if int(puzzle1number4) == puzzle1number or int(puzzle1number4) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number5 = raw_input ("What is the fourth guess? You have 2 tries left.")
if int(puzzle1number5) == puzzle1number:
print ("You did it fourth try! That came kind of close.")
if int(puzzle1number5) < puzzle1number:
print ("Higher!")
if int(puzzle1number5) > puzzle1number:
print ("Lower!")
if int(puzzle1number5) == puzzle1number or int(puzzle1number5) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number6 = raw_input ("What is the fifth and final guess? This is your last try!")
if int(puzzle1number6) == puzzle1number:
print ("Finally! Got it on the last go!")
else:
print ("Blast! The small dial clicks and becomes unmovable. Whatever treasure was in there is now locked inside. I wonder why that was a lock?")
breakhold2 += 1
break
if path1 == "2":
while breakhold2 == "0":
if puzzle1.lower in ["No", "no", "n", "N"]:
print ("You decide not to attempt the puzzle.")
breakhold2 += 1
break
puzzle1.lower in ['yes', 'no', 'whatever', ...] will always be False.
Use instead puzzle1.lower() in [....].
Check:
answer = 'Yes'
print(answer.lower)
print(answer.lower in ['yes', 'y'])
versus:
answer = 'Yes'
print(answer.lower())
print(answer.lower() in ['yes', 'y'])
I just started learning Python, and I am trying to write a basic Rock Paper Scissors program for my assignment. The game is intended to go on for 10 rounds, while keeping track the score between the player and the computer. I have two specific problems with it.
import random
def welcome_prompt():
print ("ROCKER PAPER SCISSORS in PYTHON Assignment")
print ("Rules: Rocks beats Scissors, Scissors beats Paper, Paper beats Rock")
def get_player_move():
print ('Round ' + str(round))
print ("Please play one of the following")
get_player_move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
if get_player_move == ("R"):
print ("You used Rock!")
return 1
elif get_player_move == ("P"):
print ("You used Paper!")
return 2
elif get_player_move == ("S"):
print ("You used Scissors!")
return 3
else:
print "Invalid input, please use capitalized initial (R,P,S)"
return get_player_move()
def get_computer_move():
get_computer_move = random.randint(1,3)
if get_computer_move == 1:
print ("Computer used Rock!")
return 1
elif get_computer_move == 2:
print ("Computer used Paper!")
return 2
elif get_computer_move == 3:
print ("Computer used Scissors!")
return 3
def compare_moves(get_player_move, get_computer_move):
# Rock = 1
# Paper = 2
# Scissors = 3
if (get_player_move == 1 and get_computer_move == 1) or (get_player_move == 2 and get_computer_move == 2) or (get_player_move == 3 and get_computer_move == 3):
print ("It's a tie!")
return 0
elif (get_player_move == 1 and get_computer_move == 3) or (get_player_move == 2 and get_computer_move == 1) or (get_player_move == 3 and get_computer_move == 2):
print ("You win the round!")
return 1
elif (get_player_move == 1 and get_computer_move == 2) or (get_player_move == 2 and get_computer_move == 3) or (get_player_move == 3 and get_computer_move == 1):
print ("You lose the round!")
return -1
elif (get_player_move == 4):
print ("You didn't put in correct input, computer gets a free win")
return -1
# Game Program
player_score = 0
comp_score = 0
round = 0
welcome_prompt()
('Round ' + str(round))
while round< 10:
round = round + 1
get_player_move()
get_computer_move()
compare_moves(get_player_move, get_computer_move)
if compare_moves == 1:
player_score = player_score + 1
print 'Player Score'+ str(player_score)
print 'Computer Score'+ str(player_score)
elif compare_moves == -1:
comp_score = comp_score + 1
print 'Player Score'+ str(player_score)
print 'Computer Score'+ str(player_score)
print "Game Over"
Firstly, I can't get the compare_move function to recall the returned values from both get_player_move and get_computer_move. The game can run without any error, but it just skips the comparison/ score component completely. I am still a bit iffy with the basics, so not exactly sure what is missing.
Secondly, in the get_player_move function, when I enter an invalid input (example: blah) to test the raw_input, it gives an error.
Traceback (most recent call last):
File "C:\Python27\Rock Paper Scissors.py", line 85, in <module>
get_player_move()
File "C:\Python27\Rock Paper Scissors.py", line 32, in get_player_move
return get_player_move()
TypeError: 'str' object is not callable
So how do you make a function to asks for the correct raw_input again after entering invalid input, without interrupting the while loop?
Explanation is greatly appreciated, thank you
You have a local variable get_player_move inside the function get_player_move(); you cannot then still use the function name (a global).
Rename the get_player_move local variable.
So, instead of:
get_player_move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
use:
move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
perhaps.
To get user input, it's best not to rely on recursion, however. The user could hit 'C' forever and then your program would crash with an RuntimeError: maximum recursion depth exceeded. It's easier to use a loop instead:
while True:
move = raw_input(" 1) [R]ock, 2) [P]aper, 3) [S]cissors:")
if move == "R":
print ("You used Rock!")
return 1
# etc.
else:
print "Invalid input, please use capitalized initial (R,P,S)"
Because you return from the function when a correct choice is made, the loop automatically is exited as well. If however you get to the end and Invalid input is printed, the while True loop starts at the top again and the user is asked once more to enter a choice.
Next: although your function returns a choice (an integer), you never store that return value. You must store it where you called the function:
player_move = get_player_move()
computer_move = get_computer_move()
result = compare_moves(player_move, computer_move)
if result == 1:
Note that it's not the function name that holds the return value; it's a separate variable. player_move is assigned whatever the get_player_move() returned, for example.
You can then pass these returned values to compare_moves(); it also returns a result, here stored in result for further comparisons.
I was just introduced to python less than a week ago and I'm trying to make a simple game of blackjack. I've written out the core of the program and it seems that it's ignoring the raw input, and just continually looping through the for conditional. It doesn't matter if what I type, hit, stay, whatever. Here's the code:
def main_game():
number = random.randint(1,13)
card_type_number = random.randint(1,4)
total = 0
dealer = random.randint(1,21)
input = raw_input("Would you like to Hit or Stay? \n")
if input == "hit" or "Hit":
card_number = numberConverter(number)
card_type = typeConverter(card_type_number)
new_amount = number
print "You got a %s of %s. You currently have %s. \n" % (card_number, card_type, number)
total += number
number = random.randint(1,13)
card_type_number = random.randint(1,5)
main_game()
elif input == ("Stay" or "stay") and total == 21:
print "Holy Cow! A perfect hand!"
main_game()
elif input == ("Stay" or "stay") and total < dealer:
print "Sorry, the dealer had %s" % (dealer)
maingame()
elif input == ("Stay" or "stay") and total > 21:
print "Sorry, you have more than 21"
main_game()
else:
print "Could you say again?"
main_game()
I'm at a loss and would appreciate any help.
Thanks!
if input == "hit" or "Hit":
That means if (input == "hit") or ("Hit"), which is always true.
Try
if input == "hit" or input == "Hit":
Or
if input in ("hit", "Hit"):
Or, even better:
if input.lower() == "hit"
(same for all the other elifs)