I am trying to create a task based on the Dragon Realm game in the Invent your Own Games with Python book. The original allows one choice to be made and uses functions to set up those choices. I am trying to allow two separate choices to be made but can't figure out how to stop the task after the first choice if the def statement gives a specific result, ie. if the first choice is the wrong choice then the user does not get to make a second choice. Any help would be much appreciated. Thanks.
import random
import time
def displayIntro():
#introduction
def chooseDoor():
#user chooses door
def checkDoor(chosenDoor):
#checks user choice against random number
if chosenDoor == str(friendlyDoor):
#various good stuff happens
else:
#bad stuff happens
#at this point I would like to go back to the option to play again if they have chosen the wrong door
#but I can't make it work by putting a break here as it goes on to the next def statement (chooseBox)
#this is where the original game finished
def chooseBox():
#user chooses a box but only if they made the correct choice above
def checkBox(chosenBox):
#checks user choice against random number and good or bad stuff happens
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
doorNumber = chooseDoor()
checkDoor(doorNumber)
boxNumber = chooseBox()
checkBox(boxNumber)
#play again option
The checkDoor() function should return a True if a friendly door is chosen, False if not. Then, in your main loop, modify
checkDoor()
to
if not checkDoor():
continue
In this way, is the player chooses a non-friendly door, the function returns False, and the "continue" statement will reset the program to the next execution of the while loop. Otherwise, it goes on to chooseBox()
Related
So, basically, I was just coding so that if you write a game's name, it opens it.
print('You can play games here!')
time.sleep(1.5)
print('Snake')
time.sleep(0.5)
print('Maze')
time.sleep(1.5)
print('Type the name of one of the games to open it!')
game = input()
if game == 'Snake':
import Snake
else:
if game == 'Maze':
import Maze
print('This Program Is Still In Development')
When I choose "Snake", it works perfectly. But when I choose "Maze", it just skips to the print('This Program Is Still In Development') part.
Can anyone help, please? I am on MAC OS X btw
EDIT: If I do elif, it doesn't change. Neither does a function. For some reason the only game that works is Snake.
EDIT 2: The weird thing is that when I just open Maze.py separately, IT WORKS. HOW?
change this:
else:
if statement:
# code
into this:
elif statement:
# code
this works (added print to see its working):
import time
print('You can play games here!')
time.sleep(1.5)
print('Snake')
time.sleep(1.5)
print('Maze')
time.sleep(1.5)
game = input('Type the name of one of the games to open it!')
# lowercase the user input to have less conditions
# and to make sure that we skip conditions because of case sensitivity
game = game.lower()
if game == 'snake':
# do stuff
print("snake")
elif game == 'maze':
# do stuff
print("maze")
print('This Program Is Still In Development')
So, I'm not sure the title describes my issue in a comprehensive manner.
I have made a working "loop" code in Python (even with working recursive functions) for some sort of a card game "AI". See the following pseudo-code:
def move():
if Turn == "Computer":
if Computer cannot play:
return False
else:
Do some "AI" stuff... the computer plays
Turn = "Player"
move()
elif Turn == "Player":
if Player cannot play:
return False:
else:
in = input("Select Card: ")
****So here the loop stops and waits for the input from the player
...then the input is evaluated and "played" as a player move
Turn = "Computer"
move()
while continue:
continue = move()
So if the computer can play, it plays the card, the turn changes to Player and the move function is called again, otherwise false is returned and the PC-Player back and forth turn is over. In the Player's turn the loop stops to wait for the user input from terminal and then it continues...
So far everything works, but now I want to implement a GUI for player input. I have some basic knowledge with Tkinter and so far I created buttons on screen rapresenting the player's cards. The question is how can I "stop" the loop waiting for the user to click a button (corresponding to the card - or the PASS TURN). Maybe with some sort of threading but sounds complicated... there must be an easier solution like in the "Terminal input version" that I have already working.
Thanks
You can't use a loop in a GUI, because the GUI has it's own loop that needs to run. The mainloop() in tkinter. You need to shift your planning to "event driven" programming. It sounds like in your case the event would be the user choosing a card.
def player_chooses_card():
# graphic and logic updates for player's choice
# computer turn
if Computer cannot play:
trigger graphic for end of game
else:
Do some "AI" stuff... the computer plays
# function is done; back to idle state waiting for an event
FWIW making a loop with recursion is bad style in python.
I feel your pain on the Tkinter loops. It was a hard lesson for me to learn as well. Loops such as while and for DO NOT WORK in tkinter. The way I typically solve this problem is with "root.after." Take the code in your loop and define it as a command (adding root.after(1, name of your command) like so:
def myloop():
move()
root.after(1, myloop)
Then, call it for the first time right before 'root.mainloop', like so:
<your other code>
root.after(1, myloop)
root.mainloop()
Also keep in mind that Tkinter does not make nice nice with multiprocessing/threading within mainloops, so you have to set up each process/thread as its own canvas and root.
Finally, you could set up a series of if statements and variables to separate your loop into chunks so that it stops and starts based on player input. For example,
def myloop():
if playerhasdonething == True:
move()
else:
print("waiting on player")
root.after(1, my mainloop)
I apologize if I missed the point of your question, this is how I personally would try to solve your problem
I have tried to find what I am seeking before posting this. But I have a hard time formulating the question and finding an answer.
I wonder if there is any way of having a key, such as "b", that takes the user back to the main menu where ever he is while running my program.
I have a menu and sub-menus and I want the user to be able to go back to the menu wherever he is by just pressing "b". I wonder if there is any easy way of doing this instead of putting
if choice= b:
menu()
whenever I have an input()...
I hope this is not too confusing! Would really appreciate a answer!
Not recommended for making your code easy to read but...
You could make your 'b' input check a function, then run that function at the start of each input check
def b_check(option):
if option == 'b':
main_menu()
else:
return option
def main_menu():
#your main menu function goes here
#your active menu code goes here
#ask the user to make their selection
#Note: for Python 2.x use `raw_input`
option = input('Enter your choice')
b_check(option)
if option == 'a':
#do this
elif option =='c':
#do that
I am creating a trading game in Python, and want to know how to implement turns without pausing the gameloop. I know that I will have to change the way movement is implemented, but how would I do that?
Note: code can be reached here (May be old): http://pastebin.com/rZbCXk5i
This is usually done with something called a game state machine
What that is, is extremely simple. I can show you with an example.
def main_game_loop():
if state == "player_turn":
# logic for player's turn
elif state == "enemy_turn":
# logic for enemy's turn
# they can also be used for other things, such as where you are in the game
elif state == "paused":
# pause logic etc etc
I am new to programming with Python. I have been working through a tutorial book that I found, and got the game up and running, but then decided I wanted to have a "Play Again?" option at the end. I can get the game to quit out with a press of the "n" key, but cannot work out how to get the game to restart.
Here is the code I think is giving the trouble:
#player reaches treasure
if player_rectangle.colliderect(treasure_rectangle):
#display text
screen.blit(text,(screen_width/2-195,screen_height/2-25))
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_n:
exit()
elif event.key==pygame.K_y:
pygame.display.update()
I know something needs to go after the elif event, and I have tried all that I can think of. I tried to define the whole program, and call it but that stopped the whole thing running. I have looked around internet sites, but just cannot seem to come up with a answer.
Can some one help out in easy terms how to get the game to restart to the starting position when the y key is pressed? I know it has something to do with a loop, I just cannot place my finger on what.
Many thanks.
It's not entirely clear how your code is organized, so I'll be very general. Usually games are implemented with a "main loop" that handles all of the action. In "pseudo"-python:
def main_loop():
while True:
handle_next_action()
draw_screen()
if game_is_over():
break
Before you start the loop, you usually do some setup to get the game state how you want it:
def main():
setup()
main_loop()
shut_down()
Given those parts, you can reset the game by having the main loop code call setup again (it may need to be specifically designed to be runable more than once):
def main_loop():
while True:
handle_events()
draw_screen()
if game_is_over():
if play_again(): # new code here!
setup()
else:
break
You might want to split the setup code into two parts, one which only needs to be run when the program begins (to read configuration files and set up things like the window system), and a second that gets repeated for each new game (setting up the game's state).
To restart a game you normally need to reset all variables to their initial value (e.g. number of lives, score, initial position, ...).
The best way is to put all initialisations inside a procedure:
def init():
global score,lives # use these global variables
score=0
lives=3
init() # call init() to define and reset all values
while 1: # main loop
...
elif event.key==pygame.K_y:
init() # restart the game