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.
Related
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
I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.
import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
money = money + 250000
else:
print("you lose")
money = money - 250000
print ("your balance is",money)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
game()
if replay == "n":
sys.exit("goodbye")
This is the output:
do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
you need to call game() at the end of the code once more.
import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
fact=1
else:
print("you lose")
fact=-1
print ("your balance is",money+fact*step)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
print("welcome again")
game()
if replay == "n":
sys.exit("goodbye")
game()
Add this up in your game function:
global money, flip
I was given an assignment for my computer science class with the goal of creating a number guessing game. I have created the program but I cannot seem to solve some problems that I came across while making it.
The code I wrote is....
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
i = 10
tries = 0
Random_Number = random.randint(1,100)
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Some of the problems I have with this code is that the randomly generated number stays the same even after you have played one game and are on your second. At first, I thought of putting the random.randint(1,100) inside the while loop, but that just creates a random number every time you guess. The second problem is that the 'i' and 'tries' values continue to go down but I need them to reset to their original value every time the user plays a new game.
By a new game I mean when the user answers 'yes' to Play_again.
Just a quick fix, create a 'reset' function, that updates all necessary variables:
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
def reset():
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
i = 10
tries = 0
Random_Number = random.randint(1,100)
return (i, tries, Random_Number)
i, tries, Random_Number = reset()
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Output:
...
Your guess was too low. You have 0 guesses left.
Sorry you have no more guesses left.
Would you like to play again (N/Y)?y
A random number between 1 and 100 has been generated.
You have 10 tries to guess the number.
Whats your guess?:2
Your guess was too low. You have 9 guesses left.
...
I made full code for you check this out:
import random
import sys
def menu():
Play_again = input("Would you like to play again (N/Y)?").lower()
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
game()
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
sys.exit()
else:
print("You have entered an invalid input.")
menu()
def game():
i = 10
tries = 0
Random_Number = random.randint(1,100)
#print(Random_Number)
while i>0:
try:
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
menu()
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
except:
print('Please Enter Numbers only')
print("Sorry you have no more guesses left.")
menu()
if __name__=='__main__':
print("Welcome to the Number Guessing Game!")
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
game()
In addition, I made it to get only numbers.
If there is an error in this code, tell me I'll fix it for you.
I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.
I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()