How to make the game restart (python turtle snake game) - python

So I want to make the game restart after the player bumps a wall or itself(loses a game) I tried using tkinter but didn't know what to do with it now I'm just confused.
I also wanted to ask is there a way to ask the player how if he wants to play again after he loses or some feature like that.
And can I use buttons with turtle ?

Here is how:
import turtle
while True:
# Your game code
again = input("Do you want to play again? ")
if again == 'yes':
screen.clear()
else:
print('Bye!')
break
# If the player enters `yes`, the screen will be cleared, then the program will loop back to the top of this while loop

Related

The code skips a command in Python. Can anyone tell me why?

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')

Tkinter "intervention" in a logic loop

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

Python 2.7 turtle onkey event causing a loop?

from turtle import *
def PleaseStop():
SomeWord = input("Which word?")
Screen().onkey(PleaseStop,"a")
Screen().listen()
Pressing "a" will make the program ask "Which word?" forever.
No way to stop it besides closing the program. How do I get onkey to call the function only once?
You need to remove the event bindings by calling onkey with None as first parameter:
import turtle
def OnKeyA():
print 'Key "a" was pressed'
turtle.Screen().onkey(None, 'a')
turtle.Screen().onkey(OnKeyA, 'a')
turtle.Screen().listen()
turtle.mainloop()
Doesn't solve the problem. Print is fine either way, input() is
repeating itself forever, even with none.
I believe #Acorn was heading in the right direction with this but the example provided is incomplete. Here's what I feel is a more complete solution:
from turtle import Turtle, Screen, mainloop
def OnKeyA():
screen.onkey(None, 'a')
some_word = raw_input("Which word? ")
turtle.write(some_word, font=('Arial', 18, 'normal'))
screen = Screen()
turtle = Turtle()
screen.onkey(OnKeyA, 'a')
print("Click on turtle window to make it active, then type 'a'")
screen.listen()
mainloop()
Note that this approach is awkward, clicking the turtle graphics window to make it active, hitting 'a', going back to the console window to type your word. If/when you move to Python 3, you can use the turtle function textinput() to prompt for text from the user without having to use input() from the console.

How to make a dialogue box in turtle take an input?

I'm a beginner with python and turtle. I want to make a dialogue box that asks a yes or no question. While I can get the box to pop up, how would I code it so that a "no" would close the turtle program and "yes" would keep it up? The part below the screen.textinput is wrong but I had it before for the terminal, and I imported turtle above.
screen = turtle.getscreen()
screen.textinput("Welcome to Bowling!", "Are you readt to bowl?!")
if start.lower() == 'yes':
print("Start!")
else:
print("Goodbye!")
turtle.clear
turtle.bye()
This should get you started:
import turtle
screen = turtle.Screen()
answer = screen.textinput("Welcome to Bowling!", "Are you ready to bowl?")
if answer is None or answer.lower().startswith('n'):
print("Goodbye!")
screen.clear()
screen.bye()
else:
print("Start!")
The key thing to remember is that textinput() returns the string the user typed or None if the user hits Cancel.
This is an alternative to cdlane's solution:
import turtle
screen = turtle.Screen()
answer = turtle.simpledialog.askstring("Welcome to Bowling!", "Are you ready to bowl?")
if answer is None or answer.lower().startswith('n'):
print("Goodbye!")
screen.clear()
screen.bye()
else:
print("Start!")
Note: I have not tested this code yet, I just tweaked cdlane's code
There are other options to the simpledialog function.
There are the askinteger and askfloat for integers and floats respectively. I haven't fully understood these as I just found the function while exploring around with the code prediction of VSCode

How to create a "play again" option with Pygame

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

Categories

Resources