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
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
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
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.
import sys
import turtle
t=turtle.Pen
def what_to_draw():
print ("What to do you want to see a sketch of that may or may not be colored?")
what_to_draw=sys.stdin.readline()
if what_to_draw=="flower/n":
t.forward(90)
elif():
print ("What you typed isn't in the code. Try putting a letter or letters to lowercase or uppercase. If that doesn't work, what you typed has not been set to make something happen")
I typed in this code above. It says in the python shell "flower" isn't defined. Can someone figure this out for me?
Several lines of your code have errors of some sort:
t=turtle.Pen should be: t = turtle.Pen()
You should avoid functions and variables with the same name
def what_to_draw():
...
what_to_draw = sys.stdin.readline()
Use rstrip() to deal with "\n" and .lower() to deal with case:
if what_to_draw == "flower/n":
elif(): requires a condition of some sort otherwise use else:
Let's try a different approach. Instead of mixing console window input with turtle graphics, let's try to do everything from within turtle using the textinput() function that's new with Python 3 turtle:
from turtle import Turtle, Screen
def what_to_draw():
title = "Make a sketch."
while True:
to_draw = screen.textinput(title, "What do you want to see?")
if to_draw is None: # user hit Cancel so quit
break
to_draw = to_draw.strip().lower() # clean up input
if to_draw == "flower":
tortoise.forward(90) # draw a flower here
break
elif to_draw == "frog":
tortoise.backward(90) # draw a frog here
break
else:
title = to_draw.capitalize() + " isn't in the code."
tortoise = Turtle()
screen = Screen()
what_to_draw()
screen.mainloop()
Your indentations are wrong, so most of the statements are outside the function body of what_to_draw().
You don't actually call the function, so it won't do anything.
Also, don't use the what_to_draw as a function name and a variable name.
There shouldn't be () after elif:
Instead of print() and stdin, use input() . You don't get the \n that way as well.
Try this and let me know:
import sys
import turtle
t=turtle.Pen()
def what_to_draw():
draw_this = input("What to do you want to see a sketch of that may or may not be colored?")
if draw_this == "flower":
t.forward(90)
elif:
print ("What you typed isn't in the code. Try putting a letter or letters to lowercase or uppercase. If that doesn't work, what you typed has not been set to make something happen")
what_to_draw()