Arrow Simulator Highest score and its holder - python

from multiprocessing.resource_sharer import stop
import random
import math
play_again = 'y'
while play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('please input your name:')
name = input(str())
if name == 'Quit':
break
print('Your current score:',current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer = str(input())
if answer == 'Quit':
break
while remaining_attempts > 0:
if answer == 'y':
target_location_x = random.uniform(30, 150)
target_location_y = random.uniform(0,15)
print('The target is at location:', target_location_x, ',', target_location_y)
print('Input the arrows initial velocity:')
initial_velocity = float(input())
if initial_velocity == 'Quit':
stop
while initial_velocity <= 0:
print('Error: Only values greater than 0')
initial_velocity = float(input())
if initial_velocity == 'Quit':
break
print('Input the angle the arrow is fired:')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
while arrow_angle >= 90:
print('Error: Only values >=0 and <90')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
X0 = 0
Y0 = 1
g = 9.8
t = 0.5
#to calculate where x and y ends up for the arrow
angle_x = math.cos(arrow_angle)
arrow_x = X0 + ((t*initial_velocity)*angle_x)
angle_y = math.sin(arrow_angle)
arrow_y = Y0 + ((t*initial_velocity)*angle_y)-(((1/2)*g)*(t**2))
#to get the distance from the bullseye
def distance_bullseye (arrow_x, arrow_y):
distance_bullseye = ((arrow_x-target_location_x)**2)+((arrow_y-target_location_y)**2)
distance_centre = math.sqrt(distance_bullseye)
return distance_centre
distance_centre = distance_bullseye(arrow_x, arrow_y)
print('Arrow ends up at:',arrow_x,',',arrow_y)
if distance_centre > 10:
print('You missed! Distance from centre', distance_centre)
current_score = current_score
remaining_attempts = remaining_attempts - 1
print('Your current score:', current_score)
if remaining_attempts == 0:
current_score
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('Please input your name:')
name = str(input())
elif play_again == 'Quit' or 'n':
stop
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 10 >= distance_centre > 5:
print('You hit the outer ring!')
current_score = current_score+50
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 5 >= distance_centre > 1:
print('You hit the inner ring!')
current_score = current_score+200
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 1 >= distance_centre >= 0:
print('You hit the bullseye!')
current_score = current_score +500
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
#don't know how to get highest score holder or highest score
elif answer == 'n':
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'Quit' or 'n':
stop
else:
print('Input y or n')
answer = str(input())
if answer == 'Quit':
break
Tried making a list but couldn't get the one variable to stay the same through the code loops it keeps resetting to the new name and new score. is there any way I could keep the highest score and its holder throughout the loops?
it should keep the name from the start if that name has the highest score and the program runs again and that player has a lower score should print the first name and first score, if it's higher it should print the second name with the second score.

Related

Turn/chance feature in following code is not working

I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.

Python -- 3 dices game question by using while loop

I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass

How to Show scores/ save Game/ load game Python?

I am struggling with this code, I have my menu working to make the game run and to collect scores up to 18 for each player. But I think I have gotten lost in my code and I am frustrated beyond belief.
I need to have the Player scores loaded to a list that can be saved (save game), displayed(show scores) and list current winner, and then load (load game)
Player_1 = []
Player_2 = []
def main():
choice = 0
while choice != 6 :
print("1: New Game")
print("2: Play Round")
print("3: Show Scores")
print("4: Save Game")
print("5: Load Game")
print("6: Exit Game")
choice = input ("Option Select: ")
if choice == "1":
print("New Game // Reset Game")
ResetGame()
elif choice == "2":
print("Play Play Round")
PlayRound()
elif choice == "3":
print("Show Scores")
ShowScores()
elif choice == "4":
print("Save Game")
SaveGame()
elif choice == "5":
print("Load Game")
LoadGame()
elif choice == "6":
print("Thanks for playing!")
else:
print("I don't understand your choice.")
def PlayRound():
holes = 0
index = 0
endRound = 0
while holes <= 18 and endRound != 1:
Player_1Score = int(input("Player 1 Stroke: "))
Player_2Score = int(input("Player 2 Stroke: "))
endRound = int(input("Would you like to Continue 0= YES 1= NO"))
if Player_1Score > 5:
Player_1Score = 5
if Player_2Score > 5:
Player_2Score = 5
Player_1.insert (index,Player_1Score)
Player_2.insert (index,Player_2Score)
holes += 1
index += 1
print (Player_1)
print (Player_2)
def ShowScores():
total1 = sum(Player_1)
total2 = sum(Player_2)
if total1 < total2:
print("The Current Winner is Player 1")
elif total1 > total2:
print("The Current Winner is Player 2")
elif total1 == total2:
print("The Players are Tied")
def SaveGame():
with open("score1.txt","w") as P1:
for S1 in Player_1:
P1.writelines(str(S1)+' ')
with open("score2.txt", "w") as P2:
for S2 in Player_2:
P2.writelines(str(S2)+ ' ')
print('Your Scores have been saved.')
def LoadGame():
with open("score1.txt", "r") as P1:
for S1 in Player_1:
P1.split(' ')
print(P1)
with open("score2.txt", "r") as P2:
for S2 in Player_2:
P2.split(' ')
print(P2)
print('Game Loaded')
def ResetGame():
Player_1.clear()
Player_2.clear()
print('Scores():', Player_1, Player_2)
main()

Boolean does not control while loop for me

All of this code does not get affected by a SIGKILL command and my while loop continues no matter what condition
Code:
if Play == False:
signal.SIGKILL(0)
if gameplayint == "N":
print("What are you doing here then?")
Play == False
if gameplayint == "Y":
Play == True
time.sleep(0.5)
print("We will start now.")
#Start the game.
print("")
#Actual gameplay block of code
#game start
while Play == True:
pcNum = random.randint(1,19)
anotherNum = True
total = 0
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
again = input("Try again? <Y or N>")
if again == "Y":
Play = True
else:
Play = False
print("Goodbye now.")
Output:
What's your name? Y
Very well then Y, do you want to play 13? <Y or N> N
What are you doing here then?
Your number is 3.
You have 3 in total.
The issue here is that despite N being outputted on the gameplayint variable, the while loop still continues instead of stopping the output entirely.

fruit machine GSCE challenge

I'm sure you have all heard of the GCSE fruit machine challenge. Well I am having issues with that, you see, when the user spins 3 skulls it doesn't deduct all their credits and when they only spin 2 skulls it doesn't deduct 1 credit. If anyone can help please do.
credit = 1
import time
t = 1
while True:
import random
symbols = 'Star' , 'Skull'
spin = random.choices(symbols,k=1)
spin2 = random.choices(symbols,k=1)
spin3 = random.choices(symbols,k=1)
ask = input('do you want to spin? ')
if ask == 'yes':
credit = (credit - 0.2)
credit = (round(credit, 2))
print('You now have... ' +str(credit) + ' credit(s).')
time.sleep (t)
print('** NOW ROLLING **')
time.sleep (t)
print('You rolled... ' +str(spin) +str(spin2) +str(spin3))
time.sleep (t)
if (spin == spin2 == 'Skull' or spin == spin3 == 'Skull' or spin2 == spin3 == 'Skull'):
credit = (credit - 1)
credit = (round(credit, 2))
print('Uh Oh! you rolled 2 skulls.... you lost 1 credit sorry!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == 'Skull' and spin2 == 'Skull' and spin3 == 'Skull':
credit = (credit - credit)
print('You rolled 3 Skulls!! You lost all your credits!')
break
elif spin == spin2 and spin2 == spin3:
credit = (credit + 1)
print('You won 1 credit!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == spin2 or spin == spin3 or spin2 == spin3:
credit = (credit + 0.5)
credit = (round(credit, 2))
print('You won 0.5 credits!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
else:
print('Sorry you didnt win anything.')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif ask == 'no':
print('Your total winnings are.... ' +str(credit))
break
else:
print('please say yes or no..')
continue
The problem is you are comparing list to string where "Skull" is a string and the variable "spin" is a list of one element. To solve this you can turn "spin" to a string using spin = random.choice(symbols) which will make one choice as a string.
You seem new to python so I also rewrote your code. You are more than welcome to ask questions about it :)
import time
import random
t = 1
credit = 1.0
while True:
symbols = "Star", "Skull"
spins = random.choices(symbols, k=3)
ask = input("Do you want to spin? ")
if ask == "yes":
credit -= 0.2
print(f"You now have... {credit} credit(s).")
time.sleep(t)
print("** NOW ROLLING **")
time.sleep(t)
print("You rolled... " + " ".join(spins))
time.sleep(t)
if sum(spin == "Skull" for spin in spins) == 2:
credit -= 1
print("Uh Oh! you rolled 2 skulls.... you lost 1 credit, sorry!")
elif sum([spin == "Skull" for spin in spins]) == 3:
credit = 0
print("You rolled 3 Skulls!! You lost all your credits!")
elif all(spin == spins[0] for spin in spins):
credit += 1
print("You won 1 credit!")
elif len(set(spins)) != len(spins):
credit += 0.5
print("You won 0.5 credits!")
else:
print("Sorry you didn't win anything.")
credit = (round(credit, 2))
print(f"You now have a total balance of... {credit} credits!")
if credit >= 0.2:
continue
else:
print("Sorry! You don't have enough credits.")
break
elif ask == "no":
print(f"Your total winnings are.... {credit}")
break
else:
print("Please say yes or no..")
continue
Good Luck

Categories