I'm setting up a basic hangman game and am trying to get the program to loop back to the beginning when the game is finished.
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
print("Play again? (y/n)")
Wrap your game in a function and throw it in a while loop.
After the play game function, they'll be asked to play again. If they respond with anything but 'y', the loop breaks.
while True:
# play_game()
if input("Play again?") != 'y':
break
print("Thanks for playing!")
You can use an user input and a while loop
play_again = "Y"
while play_again == "Y" or play_again == "y":
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
play_again = input("Play again? (Y/N)")
or in short just put in in a function:
play_again = "Y"
while play_again == "Y" or play_again == "y":
game()
play_again = input("Play again? (Y/N)")
You could put it all into a function and have it loop back like this:
def start():
replay = True
while (replay):
game_started()
inp = input("Play again? Y/n ")
if inp == 'n' or inp == 'N':
replay = False
def game_started():
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
break
start()
Edit:
Your check if a letter was guesses is also flawed:
If you guess "abcdefghijklmnopqrstuvwxyz", you always win.
I'd suggest checking the length of the input before appending it to guesses.
Also, to print it all into one line, you could use "print(char, end='')" (and "print('_', end='')", respectively). Just make sure to print a newline after the loop, to finish the line.
Hey friend here is what I came up with I hope it helps! Instead of using your turns to control the while loop you can use a "running" variable that is set to a boolean which you can use input statements for your replay feature to control when you want to exit (False) or continue through your loop (True).
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
running = True
while running:
failed = 0
for char in word:
if char in guesses:
print(char),
else:
print("_"),
failed += 1
if failed <= 0:
print("You won")
x = input("Play Again? (y/n) \n")
if x == "y":
turns = 10
else:
running = False
guess = input("Guess a character: \n")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
z = input("Play Again? (y/n) \n")
if z == "y":
turns = 10
else:
running = False
Related
So I'm trying to make a little hangman game in Python. I've managed it already, but I've seen lots of other people using functions to achieve this. Here's my code without using function:
from hangman_words import word_list
import random
def select_word():
return random.choice(word_list)
hidden_word = select_word()
char_lines = "_" * len(hidden_word)
guessed_letters = []
Lives = 8
game_start = input("Would you like to play HangMan? (Y/N)\n")
if game_start.upper() == "Y":
prompt_user = True
elif game_start.upper() == "N":
print("*Sad Python Noises*")
prompt_user = False
else:
print("You to say 'Yes'(Y) or 'No'(N)")
while (Lives > 0 and prompt_user == True):
user_input = input("Choose a letter!\n\n")
user_input = user_input.upper()
if user_input.upper() in guessed_letters:
print("\nYou have already guessed that letter. Choose something else!")
elif hidden_word.count(user_input) > 0:
for i, L in enumerate(hidden_word):
if L == user_input:
char_lines = char_lines[:i] + hidden_word[i] + char_lines[i+1:]
print("\nCorrect!")
print(char_lines)
else:
guessed_letters.append(user_input)
print("\nNope, that letter isn't in the word. Try again!")
Lives -= 1
if char_lines == hidden_word:
print("Well done! You won the game!")
print(f"You had {Lives} lives remaining and your incorrect guesses were:")
print(guessed_letters)
exit()
print(f"Lives remaining: {Lives}")
print(f"Incorrect guessed letters: {guessed_letters}")
print(char_lines)
if (Lives == 0 and prompt_user == True):
print("You have ran out of lives and lost the game!.....you suck")
if prompt_user == False:
print("Please play with me")
My current code for the version using functions is like this:
from hangman_words import word_list
import random
def select_word():
global blanks
selected_word = random.choice(word_list)
blanks = "_" * len(selected_word)
return selected_word, blanks
def game_setup():
global lives
global guessed_letters
global hidden_word
lives = 20
guessed_letters = []
hidden_word = select_word()
return lives, guessed_letters, hidden_word
def play_option():
game_start = (input("Would you like to play HangMan? (Y/N)\n")).upper()
if game_start == "Y":
global prompt_user
prompt_user = True
game_setup()
return prompt_user
elif game_start == "N":
print("*Sad Python Noises*")
exit()
else:
print("You need to say 'Yes'(Y) or 'No'(N)")
def user_input_check(user_input):
if type(user_input) != str: # [Want to check if unput is of tpye Str]
print("Please input letter values!")
elif user_input != 1:
print("Please only input single letters! (e.g. F)")
else:
pass
def game_board(user_input, hidden_word, guessed_letters, blanks, lives):
if user_input in guessed_letters:
print("You have already guessed that letter. Choose something else!")
elif hidden_word.count(user_input) > 0:
for i, L in enumerate(hidden_word):
if L == user_input:
blanks = blanks[:i] + hidden_word[i] + blanks[i+1:]
print("Correct!")
print(blanks)
else:
guessed_letters.append(user_input)
print("Nope, that letter isn't in the word. Try again!")
lives -= 1
print(f"Lives remaining: {lives}")
print(f"Incorrect guessed letters: {guessed_letters}")
print(blanks)
return
def win_check(blanks, hidden_word, lives, guessed_letters):
if blanks == hidden_word:
print("Well done! You won the game!")
print(f"You had {lives} lives remaining and your incorrect guesses were:")
print(guessed_letters)
exit()
def lives_check(lives, prompt_user):
if (lives == 0 and prompt_user == True):
print("You have ran out of lives and lost the game!.....you suck")
exit()
play_option()
while (lives > 0 and prompt_user == True):
user_input = (input("Choose a letter!\n\n")).upper()
user_input_check(user_input)
game_board(user_input, hidden_word, guessed_letters, blanks, lives)
win_check(blanks, hidden_word, lives, guessed_letters)
lives_check(lives, prompt_user)
I think I should be using classes instead of functions really, but I'd like to get it work with functions first, then try adapting it to work with classes. If I'm using functions, how does return actually work? Does returning variable names put those variables within the global name-space? Or does return only work when you assign the returned value to a global name-space variable? Like this:
def add_one(a):
return a + 1
b = add_one(3) # b = 4
You're correct, return works by setting the function to be equal to whatever you return it as.
I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+
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.
Beginner in Python. I've been attempting to make my game give the user a 'play again?' option once the initial game is complete. The replay works if I failed to guess the number after 6 tries, however if I managed to guess the number and try to replay nothing happens.
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Thanks in advance for any tips.
You can also define your game in a separate function. I'd do something like this:
import random
def play_game():
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
if __name__ == '__main__':
playGame = 'y'
while playGame == 'y':
play_game()
playGame = input('Would you like to play again? [y/n] ').lower()
print("Goodbye!")
Just add a break at the if where you're 'restarting' the game:
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
#Break here to exit while loop
break
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Hope this helps you!
I'm making a 2-player battleship game in python. I've made it so that each 'game' allows a total of 6 turns (3 from each player), after which a message will appear saying 'The number of turns has ended'.
Once this happens, they will be asked to play again. If they answer 'yes' or 'y', the game should reload. However it doesn't. The board loads but the program then exits. I believe the issue lies with my play_again() function but I'm not quite sure what it is.
I want to make it so that the players can play as many games as they want until they decide to answer 'no' or 'n'. How do I go about implementing this?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
}
player_two = {
"name": "Player 2",
"wins": 0,
}
colors = {"reset":"\033[00m",
"red":"\033[91m",
"blue":"\033[94m",
"cyan":"\033[96m"
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("Find and sink the ship!")
del board[:]
build_game_board(board)
print(colors['blue'])
show_board(board)
print(colors['reset'])
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
return player_two
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
break
elif answer in negative:
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('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
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" 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"
print(colors['cyan'])
show_board(game_board)
print(colors['reset'])
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
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 number of turns has ended.")
print(colors['red'])
show_board(game_board)
print(colors['reset'])
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
play_again()
if __name__ == "__main__":
main()
It also worked for me when I added an invocation to main in your play_again() function:
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
main()
break
elif answer in negative:
print("Thanks for playing!")
exit()
Try modifying main with:
turns = 0
while turns < 6:
# Process turn...
if turns == 5:
# Show endgame board
if play_again():
turns = -1
turns += 1
And have play_again return True on positive input ['y', 'yes'] and False otherwise.
The problem is that your play_again() call, upon receiving "Y" as answer, loads the board, but then simply returns. Where? Well, to the place it was called from - the for loop in main(). And unfortunately, it is the last iteration of said for loop, so the loop then ends and the program exits.
You should've put another loop around the for loop:
while True:
for turns in range(6):
...