I just started learning python using tutorials on a website. One lab had me create this camel game which I know is still incomplete. Right now I am trying to figure out how to print the miles the natives are behind without the number being negative (since this makes no sense). I know there are probably other errors in the code but right now I am focusing on this problem.
Thanks in advance! Here is the code:
import random
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down! Survive your \n"
"desert trek and out run the natives.")
print()
done = False
# VARIABLES
miles_traveled = 0
thirst = 0
tiredness = 0
natives_travel = -20
canteen = 5
forward_natives = random.randrange(0, 10)
full_speed = random.randrange(10, 20)
moderate_speed = random.randrange(5, 12)
oasis = random.randrange(0, 21)
# MAIN PROGRAM LOOP
while not done:
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
choice = input("Your choice? ")
print()
if choice.upper() == "Q":
done = True
print("You quit!")
# STATUS CHECK
elif choice.upper() == "E":
print("Miles traveled: ", miles_traveled)
print("Drinks in canteen: ", canteen)
print("The natives are", (natives_travel + 20), "miles behind you.")
print()
# STOP FOR THE NIGHT
elif choice.upper() == "D":
tiredness = 0
print("The camel is happy")
natives_travel = natives_travel + forward_natives
print("The natives are", natives_travel, "miles behind you.")
print()
# FULL SPEED AHEAD
elif choice.upper() == "C":
if oasis == 1:
print("Wow you found an oasis")
canteen = 5
thirst = 0
tiredness = 0
else:
miles_traveled = miles_traveled + full_speed
print("You walked", full_speed, "miles.")
thirst += 1
tiredness = tiredness + random.randrange(1, 4)
natives_travel = natives_travel + forward_natives
print(forward_natives)
print("The natives are", natives_travel, "miles behind you.")
print()
# MODERATE SPEED
elif choice.upper() == "B":
if oasis == 1:
print("Wow you found an oasis")
canteen = 5
thirst = 0
tiredness = 0
else:
miles_traveled = miles_traveled + moderate_speed
print("You walked", moderate_speed, "miles")
thirst += 1
tiredness = tiredness + random.randrange(1, 3)
natives_travel = natives_travel + forward_natives
print("The natives are", natives_travel, "miles behind you.")
print()
# DRINK FROM CANTEEN
elif choice.upper() == "A":
if canteen >= 1:
canteen -= 1
thirst = 0
if canteen == 0:
print("You have no drinks in the canteen!")
print()
if miles_traveled >= 200:
print("You have won!")
done = True
if not done and thirst >= 6:
print("You died of thirst!")
done = True
print()
if not done and thirst >= 4:
print("You are thirsty.")
print()
if not done and tiredness >= 8:
print("Your camel is dead")
done = True
print()
if not done and tiredness >= 5:
print("Your camel is getting tired.")
print()
if natives_travel >= miles_traveled:
print("The natives have caught you!")
done = True
print()
elif natives_travel <= 15:
print("The natives are getting close!")
print()
Use the function abs() for absolute value. Or, if this distance is always negative, just... use a minus sign?
Related
This is a python code for Rock Paper Scissor game, played by the user and computer. The score of the user is the variable and the score of the computer is computer_score which are incremented if the conditions fulfilled. The incrementation is not working as player1_score remains 0 even after winning and computer_score is incrementing every five times the loop runs, even when it is losing.
Here is the whole code:
import random
hand = ["R","P","S"]
def game():
player1_score = 0
computer_score = 0
i=0
while (i<5):
print("Enter R for ROCK \nEnter P for PAPER\nEnter S for SCISOR")
your_hand = input(player1 + " picks: ").upper()
if your_hand not in hand:
continue
computer_hand = random.randint(0,2)
print("Computer picks: ", hand[computer_hand])
if your_hand == "R" and computer_hand == "S":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "P" and computer_hand == "R":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "S" and computer_hand == "P":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
else:
computer_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
i += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
print("\t\t\tWELCOME TO ROCK PAPER SCISORS!")
print("\t\t\tRemember this: \n\t\t\t\t SCISORS KILLS PAPER \n\t\t\t\t PAPER KILLS STONE \n\t\t\t\t STONE KILLS SCISORS")
player1 = input("Player 1 Enter your name: ")
print("Player 2: Hello! " + player1 +". I am your COMPUTER!")
print("SO SHALL WE : \n\t1. PLAY \n\t2. EXIT")
start = int(input("Enter the choice: "))
if start == 1:
game()
else:
exit()
Where should I make the change?
You failed to assign the expected value to computer_hand.
computer_hand = hand[random.randint(0,2)]
If you change both the print statement print("Computer picks: ", hand[computer_hand]) to print("Computer picks: ", computer_hand) and computer_hand = hand[random.randint(0,2)] then it should work.
I am trying to make it so that when the user or the bot wins the round they get a point but at the end of the game, it seems to not add when one or the other gets it right, i tried the other way ('x = x + 1'), also please rate my code and tell me what i could've done better.
import random
print('Lets play Rock Paper Scissors')
for tries in range (1,4):
try:
user_guess = input('Rock Paper Scissors? ')
choices = ['Rock','Paper','Scissors']
user_point = 0 #To keep track of the points
bot_point = 0
bot_guess = random.choice(choices) #Will randomly pick from the list 'choices'
while user_guess not in choices:#if the user tries to put in anything other then the choices given
print('Please enter the choices above!')
user_guess = input('Rock Paper Scissors? ')
except ValueError:
print('Please choose from the choices above ') #Just in case user tries to put a different value type
user_guess = input('Rock Paper Scissors? ')
DEBUG = "The bot did " + bot_guess
print(DEBUG)
if user_guess == bot_guess:
print('Tie!')
elif user_guess == "Rock" and bot_guess == "Paper":
print('The bot earns a point!')
bot_point += 1
elif user_guess == 'Paper' and bot_guess == "Rock":
print('The user earns a point!')
user_point += 1
elif user_guess == 'Paper' and bot_guess == 'Scissors':
print('The bot earns a point')
bot_point += 1
elif user_guess == 'Scissors' and bot_guess == 'Paper':
print('The user earns a point')
user_point += 1
elif user_guess == 'Rock' and bot_guess == 'Scissors':
print('The user earns a point')
user_point += 1
elif user_guess == 'Scissors' and bot_guess == 'Rock':
print('The bot earns a point')
bot_point += 1
print('After ' + str(tries) + ' tries. ' + ' The score is')
print('The User: ' + str(user_point))
print('The Bot: ' + str(bot_point))
if user_point > bot_point:
print('THE USER IS THE WINNER!!!')
else:
print('THE BOT IS THE WINNER!!!')
You need to initialize user_point and bot_point before you start the for loop. The way it is, those are reset to zero each time through the loop.
I'm a newbie of coding. I'm trying to create a guessing random number game by python. The thing is I get stuck at limited users by 5 turns guessing only. Here is my code so far. Thank you
print("""
WELCOME TO GUESSING NUMBER GAME!!!
You have 5 turns to guess a random number. Good luck!
""")
def play():
import random
random_numnber = random.randint(0, 20)
guess_count = 0
while True:
try:
guess = int(input("Please enter an integer from 1 to 20: "))
guess_count += 1
except ValueError:
print("Invalid Input\n")
continue
else:
break
while random_numnber != guess and guess_count < 5:
if int(guess) < random_numnber and int(guess_count) < 5:
print("Your number is too low\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) > random_numnber and int(guess_count) < 5:
print("Your number is too high\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) == random_numnber and int(guess_count) < 5:
print("Congratulation! You Win!\n")
break
else:
print("You have guessed 5 times and all Wrong. Good luck on next game!")
break
while True:
answer = input("Do you want to play? ")
if answer == 'yes' or answer == 'y':
play()
elif answer == 'no' or answer == 'n':
break
else:
print("I don't understand\n")
This is how I would go about doing this, I have modified your code and omitted some trivial error handling for non-integer inputs, etc.
The trick is that the code section between the # *** comments will be exited automatically if the guess_count value exceeds the maximum_tries, so we can actually remove a lot of the conditionals you were performing in-line which cluttered the real logic we care about.
You can also see that the only way that we can reach the line where we print "All out of guesses" is if the user has not already guessed the correct number.
Finally, since you mentioned you are just starting out I included a main() function as well as the Pythonic block at the end, which is just a special way to tell Python which part of the program you want to start with when you run the script. Happy coding!
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()
I'm a freshman in a computer science degree and I was given this assignment to complete this camel game. I can't seem to find a way for the variables to update when checking the status after moving. They always print miles traveled is 0 and the natives are -20 miles behind. Any help is greatly appreciated thanks!
Here is my code.
# The comments are from my friend who helped me fix the while loop from repeating over and over
def main ():
global executed
executed = 1
if executed == 1: # This will only show the intro once
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down!")
print("Survive your desert trek and out run the natives.")
global done # Add global next to a variable if you're calling it from outside the function
executed = 0
main()
done = False
while not done:
# Game variables
miles_traveled = int(0)
thirst = int(0)
camel_tiredness = int(0)
native_distance = int(-20)
canteen_drinks = int(3)
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = (input("What is your choice? "))
# Quit the game
if user_choice.upper() == "Q":
done = True
print("Quitting...")
# Status check
elif user_choice.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in Canteen:", canteen_drinks)
print("The natives are", native_distance, "miles behind you.")
# Stopping for the night
elif user_choice.upper() == "D":
camel_tiredness = int(0)
print("Your camel is happy.")
import random
native_distance += random.randint(7, 14)
print("The natives are", native_distance, "miles behind you.")
#Full speed
elif user_choice.upper() == "C":
thirst += int(1)
camel_tiredness += int(1)
import random
miles_traveled += random.randint(10, 20)
print("You have traveled", miles_traveled, "miles.")
import random
native_distance += random.randint(7, 14)
# Moderate speed
elif user_choice.upper() == "B":
import random
miles_traveled += random.randint(5, 12)
print("You have traveled", miles_traveled,"miles.")
thirst += int(1)
camel_tiredness += int(1)
import random
native_distance += random.randint(7, 14)
# Drinking from canteen
elif user_choice.upper() == "A":
if canteen_drinks >= 1:
print("You have taken a sip from your canteen")
print("You have", canteen_drinks - int(1), "sips left in your canteen.")
elif canteen_drinks == 0:
print("You are out of water.")
# The other stuff at the end
if thirst > 4 < 6:
print("You are thirsty.")
if thirst > 6:
print("You have died of thirst!")
done = True
if camel_tiredness > 5 < 8:
print("Your camel is tired.")
if camel_tiredness > 8:
print("Your camel has died.")
if native_distance >= 0:
print("The natives have caught you.")
done = True
if native_distance >= -15:
print("The natives are getting close!")
if miles_traveled >= 200:
print("You have won and got away from the natives!")
done = True
import random
oasis = random.randint(0, 20)
if oasis == 20:
print("You have found an oasis.")
thirst = 0
camel_tiredness = 0
Your variables should be out of the while loop in order not to get the same values over and over and also you should have update canteen_drinks variable eachtime.
Updated code
def main ():
global executed
executed = 1
if executed == 1: # This will only show the intro once
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down!")
print("Survive your desert trek and out run the natives.")
global done # Add global next to a variable if you're calling it from outside the function
executed = 0
main()
import random
done = False
miles_traveled = int(0)
thirst = int(0)
camel_tiredness = int(0)
native_distance = int(-20)
canteen_drinks = int(3)
while not done:
# Game variables
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = (input("What is your choice? "))
# Quit the game
if user_choice.upper() == "Q":
done = True
print("Quitting...")
# Status check
elif user_choice.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in Canteen:", canteen_drinks)
print("The natives are", native_distance, "miles behind you.")
# Stopping for the night
elif user_choice.upper() == "D":
camel_tiredness = int(0)
print("Your camel is happy.")
native_distance += random.randint(7, 14)
print("The natives are", native_distance, "miles behind you.")
#Full speed
elif user_choice.upper() == "C":
thirst += int(1)
camel_tiredness += int(1)
miles_traveled += random.randint(10, 20)
print("You have traveled", miles_traveled, "miles.")
native_distance += random.randint(7, 14)
# Moderate speed
elif user_choice.upper() == "B":
miles_traveled += random.randint(5, 12)
print("You have traveled", miles_traveled,"miles.")
thirst += int(1)
camel_tiredness += int(1)
native_distance += random.randint(7, 14)
# Drinking from canteen
elif user_choice.upper() == "A":
if canteen_drinks >= 1:
print("You have taken a sip from your canteen")
canteen_drinks = canteen_drinks - int(1) # you should update the centeen_drinks
print("You have", canteen_drinks, "sips left in your canteen.")
elif canteen_drinks == 0:
print("You are out of water.")
# The other stuff at the end
if thirst > 4 < 6:
print("You are thirsty.")
if thirst > 6:
print("You have died of thirst!")
done = True
if camel_tiredness > 5 < 8:
print("Your camel is tired.")
if camel_tiredness > 8:
print("Your camel has died.")
if native_distance >= 0:
print("The natives have caught you.")
done = True
if native_distance >= -15:
print("The natives are getting close!")
if miles_traveled >= 200:
print("You have won and got away from the natives!")
done = True
oasis = random.randint(0, 20)
if oasis == 20:
print("You have found an oasis.")
thirst = 0
camel_tiredness = 0
First of im sorry about bombarding my post with a bunch of code, but im putting it here hoping that it will help you guys understanding my question better.
I am trying to figure out why my IDE is unwilling to execute the first function of my code. Obviously im doing something wrong, but im to unexperienced to see it for myself. All help would be greatly appriciated.
If you have any further comments or tips on my code feel free contribute.
import random
print("Press '1' for New Single Player Game - Play against computer component: ")
print("Press '2' for New Two Player Game - Play against another person, using same computer: ")
print("Press '3' for Bonus Feature - A bonus feature of choice: ")
print("Press '4' for User Guide - Display full instructions for using your application: ")
print("Press '5' for Quit - Exit the program: ")
def choose_program():
what_program = int(input("What program would you like to initiate?? Type in the 'number-value' from the chart above: "))
if what_program == 1 or 2 or 3 or 4 or 5:
program_choice = int(input("Make a choice: "))
if (program_choice > 5) or (program_choice < 1):
print("Please choose a number between 1 through 5 ")
choose_program()
elif program_choice == 1:
print("You picked a New Single Player Game - Play against computer component")
def single_player():
start_game = input("Would you like to play 'ROCK PAPER SCISSORS LIZARD SPOCK'?? Type 'y' for YES, and 'n' for NO): ").lower()
if start_game == "y":
print("Press '1' for Rock: ")
print("Press '2' for Paper: ")
print("Press '3' for Scissors: ")
print("Press '4' for Lizard: ")
print("Press '5' for Spock: ")
elif start_game != "n":
print("Please type either 'y' for YES or 'n' for NO: ")
single_player()
def player_one():
human_one = int(input("Make a choice: "))
if (human_one > 5) or (human_one < 1):
print("Please choose a number between 1 through 5 ")
player_one()
elif human_one == 1:
print("You picked ROCK!")
elif human_one == 2:
print("You picked PAPER!")
elif human_one == 3:
print("You picked SCISSORS!")
elif human_one == 4:
print("You picked LIZARD!")
elif human_one == 5:
print("You picked SPOCK!")
return human_one
def computers_brain():
cpu_one = random.randint(1, 5)
if cpu_one == 1:
print("Computers choice iiiiiis ROCK!")
elif cpu_one == 2:
print("Computers choice iiiiiis PAPER!")
elif cpu_one == 3:
print("Computers choice iiiiiis SCISSORS!")
elif cpu_one == 4:
print("Computers choice iiiiiis LIZARD!")
elif cpu_one == 5:
print("Computers choice iiiiiis SPOCK!")
return cpu_one
def who_won(human, cpu, human_wins, cpu_wins, draw):
if human == 1 and cpu == 3 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 2 and cpu == 1 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 3 and cpu == 2 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 4 and cpu == 2 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 5 and cpu == 1 or cpu == 3:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == cpu:
print("Human & computer think alike, such technology")
draw = draw.append(1)
else:
print("Computer have beaten it's master, incredible..")
cpu_wins = cpu_wins.append(1)
return
def end_score(human_wins, cpu_wins, draw):
human_wins = sum(human_wins)
cpu_wins = sum(cpu_wins)
draw = sum(draw)
print("Humans final score is: ", human_wins)
print("Computers final score is: ", cpu_wins)
print("Total draws: ", draw)
def main():
human = 0
human_wins = []
cpu = 0
cpu_wins = []
draw = []
finalhuman_wins = 0
finalcpu_wins = 0
finaldraw = 0
Continue = 'y'
single_player()
while Continue == 'y':
human = player_one()
cpu = computers_brain()
who_won(human, cpu, human_wins, cpu_wins, draw)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
end_score(human_wins, cpu_wins, draw)
main()
elif program_choice == 2:
print("You picked a New Two Player Game - Play against another person, using same computer")
elif program_choice == 3:
print("You picked the Bonus Feature - A bonus feature of choice")
elif program_choice == 4:
print("You picked the User Guide - Display full instructions for using your application")
elif program_choice == 5:
print("You picked to Quit - Exit the program")
return program_choice
elif what_program != 1 or 2 or 3 or 4 or 5:
print("To initiate a program you need to type in the appropriate number to initiate this program, either 1, 2, 3, 4 & 5 ")
choose_program()
Outout in IDE:
Press '1' for New Single Player Game - Play against computer component:
Press '2' for New Two Player Game - Play against another person, using same computer:
Press '3' for Bonus Feature - A bonus feature of choice:
Press '4' for User Guide - Display full instructions for using your application:
Press '5' for Quit - Exit the program:
Process finished with exit code 0
Thank you in advance for your help :)