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.
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 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.
can't repeat the loop after the "else statement" (googled it and did'nt find a solid resault)
example:
I'm trying to make a dice game
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
user_input = input("Roll the Dice? [Y/N] ")
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while user_input:
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
else:
print('Invalid')
continue
user_input = input("Roll again? [Y/N] ")
print(user_input)
Your while loop needs a condition. While x == 1: or while 1:
If you use x = 1. When the value of x is other than 1, the while loop will stop or when a break is used.
If you use while 1, it will continue to loop until you use break.
Another point, you want to have the user_input within the while loop so that it can ask the user if they would like to roll again.
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
x = 1
while x == 1:
user_input = input("Roll the Dice? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
Answer: As noted by Klaus, removing the continue in the while user_input will fix the loop, to only re-roll when the user responds 'y'
Changing print(dice_roll()) to just dice_roll() (function call without printing it's return value) will keep this program from printing 'None' after dice rolls.
If you want it to print the return, you can change the
print(" The sum is", dices_sum) to
return(" The sum is", dices_sum)
try this
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while 1:
user_input = input("Roll? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input == 'y':
dice_roll()
elif user_input == 'N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
There are two problems that you need to fix.
Since your function dice_roll ends without return syntax, python interpreter will add return None at the end of the function. I change 'print(dice_roll())' to 'dice_roll()'.
In your while loop, if elif else syntax has covered all situations, the code will never go to
user_input = input("Roll again? [Y/N] ")
print(user_input)
So, I just put these two lines in front of 'if elif else'. and remove ' again'.
I'm making a 2-play Battleship game in python and have been struggling with this for a while now:
I apologise if the question is poorly worded but I was to know how I can make my game log the match score at the end of the three games with something like:
print('Match score is' + score + 'Player' + (whoever) + 'wins!)
I'm not entirely sure how to implement this myself I have a range for games in range(3), but I don't know how to log the final score.
Also, how can I change the symbol for player_two so that I am not using an 'X' for both players? I've tried changing the input_check() but I get more errors than I did before.
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
else:
return player_two
# Allows new game to start
def play_again():
global ship_points
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns(turns) == player_one:
# print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
You can use style string formatting to print the log.
print('Match score is %d : %d(Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
For more information about string formatting, check this link.
To change the symbol for Player 2, you can change the following code.
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"
In the below code, why doesn't it stop looping when fighting is set to False?
I know it does not stop looping, because it won't get to the loot part when fighting is set to False. Here is the whole while loop:
while fighting:
cls()
print("The enemy has", opponent.HP, "HP!")
input()
if int(opponent.HP) <= 0:
print("Yep yep")
winner = True
fighting = False
elif int(ownedCreatures[activeCreature].HP) <= 0:
winner = False
fighting = False
showFight(opponent, activeCreature)
allowed = ["a", "i", "r"]
choice = input(">>")
while not choice in allowed:
choice = input("Try again please >>")
if choice.lower() == "a":
if previousTurn == "Not defined":
num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
if num <= ownedCreatures[activeCreature].support:
attacker = "player"
previousTurn = "player"
else:
attacker = "opponent"
previousTurn = "opponent"
else:
if previousTurn == "player":
attacker = "opponent"
previousTurn = "opponent"
else:
attacker = "player"
previousTurn = "player"
attack(attacker, activeCreature, opponent)
#if choice.lower() == "i":
if choice.lower() == "r":
num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
if num <= ownedCreatures[activeCreature].support:
cls()
print("-------------------------------------------")
print("You succesfully escaped this horrible fight!")
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")
winner = "Not defined"
fighting = False
else:
cls()
print("-------------------------------------------")
print("Think you can run that easily?")
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")
#After the fight
if winner == True:
cls()
loot()
elif winner == False:
cls()
print("-------------------------------------------")
print("You have lost the fight!")
print("You lost 50 Serra!")
serra = serra - 50
if serra < 0:
serra = 0
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")
You have three places inside the loop where you set fighting to False and all of them coming with an if condition:
int(opponent.HP) <= 0
int(ownedCreatures[activeCreature].HP) <= 0
num <= ownedCreatures[activeCreature].support
The first and the second conditions are constant inside the loop, so if they start False, the change of fighting will never be accessible.
The third: num is a random number greater than 1 so if ownedCreatures[activeCreature].support is 0, the condition will never be accessible.
Print the values of conditions to check if they are fulfilled or not.