This program is supposed to play the card game War. Okay so I need to be able to prompt the user to keep playing and have them respond by hitting the enter key. I'm not sure how to make this happen. Help?
import cards
# Create a deck of cards
the_deck = cards.Deck()
# Shuffle the deck, then display it in 13 columns
the_deck.shuffle()
print( "===== shuffled deck =====" )
the_deck.display()
def main():
'''This function deals out half the deck to each
player. It sorts the rank so as to solve the problem
with Aces causing an infinite game'''
player1_list=[]
player2_list=[]
for i in range( 26 ):
p1_temp= the_deck.deal()
player1_list.append( p1_temp )
p2_temp= the_deck.deal()
if (p2_temp.rank()==1):
player1_list.append(p2_temp)
player2_list.append(player1_list.pop(0))
else:
player2_list.append(p2_temp)
print()
# Card dealt to Player #1
player1_card = player1_list.pop( 0 )
print( "===== player #1 =====" )
print( "Card dealt to player #1:", player1_card )
print( player1_list )
print()
#Card dealt to Player #2
player2_card=player2_list.pop(0)
print( "===== player #2 =====" )
print("Card dealt to player #2:",player2_card)
print( player2_list )
# Compare the two cards using overloaded operators
print()
if player1_card == player2_card:
print( "Tie:", player1_card, "and", player2_card, "of equal rank" )
elif player1_card > player2_card:
print("Player #1 wins:",player1_card,"of higher rank than",player2_card)
else:
print("Player #2 wins:",player2_card,"of higher rank than",player1_card)
print()
main()
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
still_playing=input('Press "Enter" to continue playing')
Enter=1
while still_playing==Enter:
main()
keep_playing()
Assuming the rest of your main is working (and the imported Deck class): your two main problems are you forgot to call your main and the method you are using to test the variable Enter. Since your taking an input for Enter you just need to test this against an empty string or just test that it is empty - as input strips newlines by default.
def play_hand():
print ("all the play code goes here")
#just a simple exit here no return needed
'''This function deals out half the deck to each
player. It sorts the rank so as to solve the problem
with Aces causing an infinite game
player1_list=[]
player2_list=[] ... etc ...'''
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
return input('Press "Enter" to continue playing')
def main():
# the_deck = Card.Deck() # create deck instance (depending on how shuffle method is written this may need to go in while loop)
still_playing = "" #Set still_playing to empty string to more easily use input
while not still_playing: #this will keep going as long as still_playing is an empty string
print("hello main") # cause it fun :) - also as you can put an intro here or the shuffle so:
# the_deck.shuffle()
# print( "===== shuffled deck =====" )
# the_deck.display()
play_hand()
# Do all your other stuff here
still_playing = keep_playing() #Calls the function and stores returned value (can do this with just input but using return to show an option)
main()
As a secondary note, you need to learn how to isolate the problem within your code. To that end: the following shows a testable instance (and solution) of the enter to continue problem your having. Run this and it will only test (in this case solve) the enter problem, this is what Stack Overflow means by a minimal, complete, verifiable example.
As #IanAuld mentioned, you have not called your Keep_playing() function anywhere. Instead of calling main(), simply call Keep_playing(). If you'd like to just start the game without the "Press Enter to continue playing," just make the first line of the Keep_playing() function a call to main(), so that it runs and then keeps checking if the user wants to continue.
Also, you have an infinite loop in Keep_playing(). Put the input(...) part inside the while loop after you call main(). That way, it will reprompt every loop and change the still_playing variable.
It should look like this:
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
still_playing=""
Enter=""
while still_playing==Enter:
main()
still_playing=input('Press "Enter" to continue playing')
keep_playing()
You can read this SO question to figure out how to implement reading the "enter" key as input (it's quite simple, so don't worry)
Additionally, as a good practice in Python (and most other languages), make variables and function names lowercase, as uppercase names are typically reserved for class use. Even if this isn't going to be spread or maintained around, it's good to get into the habit.
Related
I am a beginner to python and coding in general and I was wondering how I can make a print statement run before a module I imported. I am making a number guessing game and in my main file where I combine all the modules, I have a general function for running all the code together. It would be best if I show my code so you guys will have a better understanding of what I am dealing with:
import random
import lvl1
import time
level1 = lvl1.Level_1_activated()
# This is the main file combining everything together to make this game playable
introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’.
"""
def start_game(time, lvl1):
print(introduction)
level1
start_game(time, lvl1)
This is just the code for the main module, I have the code for lvl1 (which is the first level of my 'game'), and I have a class which has all the functions which then take part in the while loop. I will also show that file:
import random
import time
# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long
S = 0.2
M = 0.7
L = 1.1
class Level_1_activated():
def get_name(self):
# This function simply asks the name of the player
name = input("Before we start, what is your name? ")
time.sleep(S)
print("You said your name was: " + name)
def try_again(self):
# This asks the player if they want to try again, and shows the progress of the level
answer = (input("Do you want to try again? "))
time.sleep(M)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(M)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
# Return statement for if the player wants to play again
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
# This is the return statement that stops the while loop
return False
def find_rand_num(self, random):
# This is the core of the level, where the player just chooses numbers between 1 and 10
time.sleep(S)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(L)
# The list of numbers for the level that the player is on at the moment
num_list = [1,10]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(S)
print("Congratulations! You got the number correct!")
# Yet another return statement for the while loop
return "Found"
elif input != number:
time.sleep(M)
print("Oops, you got the number wrong")
# This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop
tries = 1
while tries < 6:
if tries < 2:
Level_1_activated().get_name()
res = Level_1_activated().find_rand_num(random)
if res == "Found":
break
checker = Level_1_activated().try_again()
if checker is False:
break
tries += 1
If you go back to this function in the main file:
def start_game(time, lvl1):
print(introduction)
level1
I intentionally put the print statement before the module to make it run first, and I have tried different approaches to this and still can't seem to get a grasp on what I'm doing wrong here. Thank you for taking the time to read the code and I would be very grateful if any of you have a possible solution to this.
there are number of thing you can do, one is encapsulate your code into functions that only run when you ask for it
lvl1
... #all the previous code
def run_game():
tries = 1
while tries < 6:
...
tries += 1
you can also make a distinction between being executed directly vs being imported, to do that is simple, you include the following check (usually at the end of the file)
if __name__ == "__main__":
#if true it mean that you're executing this module directly, otherwise it was imported
#and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
run_game()
__name__ is a special variable and python will assigned the value "__main__" if executed directly, otherwise it will be the name of the file, like "lvl1" for example
And in your main you can import it and do stuff like
import lvl1
...
def start_game():
print(introduction)
lvl1.run_game()
I made a menu to play a game in python. (Please See Below). However, I can t use my lists when I call setup_game or init_trigger. I tried to put them into the while and to also add a variable play so I can avoid the user to press 2 if he never played before. my issues are the following:
Why setup_game(possible_answers, female_charactere, male_charactere) or init_trigger(possible_answers, charactere_attributes) does not work if I put the list out of the while?
why is play not defined?
Please also give me feedback on the code itself, I am a newbie and I want to improve. Thank you!
### create the menu
def menu():
print (30 * "-" , "MENU" , 30 * "-")
print ("1. Replay")
print ("2. Back to my first choice")
print ("3. Exit")
print (67 * "-")
## setup number of time player try the game
play=0
## lists needed to run setup_game and init_trigger
possible_answers= ["female","Female","F","girl","answer","Answer","a","yes","y","Yes","Y","kitchen","Kitchen","K","k","1","Leave","leave"]
female_charactere= ["boy","girl","he","his","him","prince"]
male_charactere= ["girl","boy","she","her","her","princess"]
loop=True
while loop: ## While loop which will keep going until loop = False
menu() ## Displays menu
choice = int(input("Enter your choice [1-3]: "))
if choice==1:
print ("Your story is about to start")
play=play+1 ##count number of time user play
setup_game(possible_answers, female_charactere, male_charactere) ## launch game
elif (choice==2 and play>=1):
print ("Your are back to your first choice")
play=play+1 ##count number of time user play
init_trigger(possible_answers, charactere_attributes) ##lauch game at first choice
elif (choice==2 and play==0):
print ("You have not played yet, you are starting a new story")
setup_game()
elif choice==3:
print("Thank you for playing!")
loop=False # This will make the while loop to end as not value of loop is set to False
else:
print("Thank you for playing!")
break
Why setup_game(possible_answers, female_charactere, male_charactere)
or init_trigger(possible_answers, charactere_attributes) does not work
if I put the list out of the while?
Here you're calling 2 functions you've yet to create. Unless you have more code that you did not share. Your app has no idea what to do with start_game() or init_trigger().
why is play not defined?
Python requires proper indentation, when you step into something like a function, loop, if statement, etc, you have to indent the code that belongs to it.
In your case, you've indented play = 0 under the menu() function. Because of this, play only exists in the scope of menu (). If you align play = 0 left, that warning will disappear.
I've been trying to make a basic text game in Python, and I'm using dictionaries to contain the player's information. I want to make it so that when a player's health reaches 0, the code will stop running. I've had trouble making that happen. My dictionary, which is at the beginning of my code, looks like this:
playerAtt = {}
playerAtt["Weapon"] = "Baseball bat"
playerAtt["Party"] = "Empty"
playerAtt["Health"] = 15
playerAtt["Cash"] = "$100"
print(playerAtt)
if playerAtt['Health'] <= 0:
exit()
The bottom section is what I wrote to try and make the code stop running when the player's health reached zero, but it doesn't seem to work. In one path of my game, your health gets set to zero and the game is supposed to end, but the program continues to run:
townChoice = raw_input("You met a traveler in the town. 'Yo. I'm Bob. Let's be friends.' Will you invite him to your party? Y/N\n")
if townChoice == 'y' or townChoice == 'Y':
print("That kind traveler was not such a kind traveler. He stabbed you with a machete. RIP " + Name + '.')
playerAtt['Health'] == 0
When you reach this part of the game, all it does is print the message, and moves on to the next decision. In this situation, I could just manually end the program by doing exit() under the print command, but there are circumstances where the player only loses a fraction of their health, and they would eventually reach zero. Sorry if this is a stupid question, I've only been working on Python for a few days.
You have two "=" when you set the player's health to 0
I had put 2 == instead of 1 = when defining
playerAtt["Health"].
Also, I needed to make sure it was constantly checking if the player's health was zero, so I used a while loop. I used
while playerAtt["Health"] = 0:
deathmsg()
exit()
to fix it. deathMsg was a function I made to display a random death message, for more information.
I am trying to make a Blackjack game in Python and I made a separate function for each option to hit stay etc... When I call each function, I pass it the players hand total so far:
def hit(PlayerHand):
PlayerCard3 = random.randint(2,10)
print("You got %s" %PlayerCard3)
PlayerHand = PlayerHand+PlayerCard3
return(PlayerHand)
And then I print the players total hand outside of the function but it returns the previous value of PlayerHand and not the new value. I'm not sure what to do.
Make sure you are saving the new value:
print("New value is: {}".format(hit(PlayerHand)))
or
PlayerHand=hit(PlayerHand)
print(PlayerHand)
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.