Text input on a Turtle based Python Game - python

I am trying to create a turtle based, text adventure game with an interactive GUI. But I ran into a problem. In the image attached, you will see a ">" and then after that, I would like the user to be able to type a command, and submit it to determine the path of a game. I am relatively new to python, so I am not familiar with external libraries or modules that could help with this.
import os
import turtle
#SCREEN
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Untitled Game")
#Box
box = turtle.Turtle()
box.color("white")
box.speed(0)
box.penup()
box.setposition(-500, -200)
box.pensize(5)
box.pendown()
box.fd(900)
#TEXT IN TEXT BOX
text = turtle.Turtle()
text.speed(0)
text.color("white")
text.penup()
text.setposition(-350, 300)
text.write("This is a test", False, align="left", font=("Helvetica", 25, "normal"))
text.hideturtle()
#TEXT ARROW
arrow = turtle.Turtle()
arrow.speed(0)
arrow.color("white")
arrow.penup()
arrow.setposition(-360, -300)
arrow.pendown()
arrow.pensize(4)
arrow.write(">", False, align="left", font=("Helvetica", 60, "normal"))
screen.mainloop()
What it looks like right now

Related

Turtle Graphics-OnClick 'str' object is not callable error

I am making a calculator with turtle-graphics. I want the turtle to type something when I press a button. The code is below:
import turtle
wn = turtle.Screen()
wn.title("rob it")
wn.bgcolor("black")
wn.setup(width=500, height=600)
CURSOR_SIZE = 20
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'bold')
button = turtle.Turtle()
button.hideturtle()
button.shape('circle')
button.fillcolor('red')
button.penup()
button.goto(150, 650)
button.write("Click me!", align='center', font='arial')
button.sety(150 + + FONT_SIZE)
button.onclick('type_0')
button.showturtle()
#I think that's where the error occurs
def type_0(x, y):
turtle.penup
turtle.color('white')
turtle.goto(150, 650)
turtle.pendown
turtle.write('hello!', font='arial', align='center')
turtle.hideturtle
while True:
wn.update()
But I am getting this error. I have tried everything and I cannot fix it. Any solutions? For some reason I am not able to call the type_0 function.
So I am typing this because I don't know what other details to add and I am new to python so I will appreciate any comment or help.
The following is an implementation which will work but not an optimal/elegant solution. Okay to start with. As you learn more you can make your code much more elegant. One of the way is to use a class with methods. Also, please note that x,y arguments are not used in your function.
import turtle
wn = turtle.Screen()
wn.title("rob it")
wn.bgcolor("black")
wn.setup(width=500, height=600)
CURSOR_SIZE = 20
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'bold')
button = turtle.Turtle()
button.hideturtle()
button.shape('circle')
button.fillcolor('red')
button.penup()
button.goto(150, 650)
button.write("Click me!", align='center', font='arial')
button.sety(150 + + FONT_SIZE)
def type_0(x, y,turtle_in_fn=button ):
turtle_in_fn.penup
turtle_in_fn.color('white')
turtle_in_fn.goto(150, 150)
turtle_in_fn.pendown
turtle_in_fn.write('hello!', font='arial', align='center')
turtle_in_fn.hideturtle
# Note that type_0 is a function. type_0 should not be within single quotes ''
button.onclick(type_0)
button.showturtle()
while True:
wn.update()

Close python Turtle module game at keypress

I've been trying to make the Snake game using the Turtle module in Python3.
I want the program to close when the Esc key is pressed twice. Here's what i've tried so far, but I can't seem to get it working (i've previously imported the sys module):
def exitprogram():
sys.exit()
def close():
close = turtle.Turtle()
close.speed(0)
close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
Any help would be greatly appreciated!!
EDIT
Instead of using sys.exit(), i used window.bye() and that seemed to work just fine. Thanks!
Code works for me if I add mainloop() which gets key/mouse events from system and sends to turtle's window. You can also use window.bye() to exit mainloop()
import turtle
def exitprogram():
window.bye()
def close():
close = turtle.Turtle()
close.speed(0)
#close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window = turtle.Screen()
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
I generally agree with #furas (+1) but I would go simpler as some methods you invoke are effectively no-ops in the context in which they are used:
from turtle import Screen, Turtle
def close():
window.onkeypress(window.bye, "Escape")
close = Turtle()
close.hideturtle()
# close.color("white")
close.write("Press ESC again to exit", align="center", font=("Courier", 24, "normal"))
window = Screen()
window.onkeypress(close, "Escape")
window.listen()
window.mainloop()

How to randomly a select a file with pickle?

For a school project I have to make a program that randomly selects a song from a file and inputs the artist's name and song title and the player has to fill in the blank from the artist name and song title in order to earn points.
One of the requirements for the project is that it randomly selects the file from the folder for the song so I've tried using the pickle module and turtle module - for the tab and somewhere to output the program if that makes sense and ive worded it correctly.
Unfortunately nothing seems to be many things. The biggest I'm having is because I've got the songs in the code it overlaps them in the tab when its been run and I want the program to only show one song at a time and hide the rest until the user has guessed
Here's my code:
import turtle
import os
import pickle
import random
#Screem
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Main Screen")
#Border
border = turtle.Turtle()
border.speed(0)
border.penup()
border.color("white")
border.setposition(-300, -300)
border.pensize(3)
border.pendown()
for side in range(4):
border.fd(600)
border.lt(90)
border.hideturtle()
song1 = turtle.Turtle()
song1.color("white")
song1.penup()
song1.speed(0)
song1.setposition(-200, -200)
song1string = ("_ost malone _n god")
song1.write(song1string, False, align="Left", font=("Arial", "14", "normal"))
song1string2 = ("_minem _ap _od")
song1.write(song1string2, False, align="Left", font=("Arial", "14", "normal"))
song1.hideturtle()
song1.clear()
songs = []
songs.append(song1string)
songs.append(song1string2)
pickle.dump(songs, open("songs.py", "wb"))
songs = pickle.load(open("songs.py", "rb"))
final_song = random.choice("songs.py")
screen.mainloop()
Frankly I don't understand exactly what your code is doing, nor why you're even using pickle. Regardless, maybe the following changes with # ALL CAP comments indicating where they were amde will help:
import turtle
import os
import pickle
import random
#Screem
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Main Screen")
#Border
border = turtle.Turtle()
border.speed(0)
border.penup()
border.color("white")
border.setposition(-300, -300)
border.pensize(3)
border.pendown()
for side in range(4):
border.fd(600)
border.lt(90)
border.hideturtle()
song1 = turtle.Turtle()
song1.color("white")
song1.penup()
song1.speed(0)
song1.setposition(-200, -200)
song1string = ("_ost malone _n god")
song1.write(song1string, False, align="Left", font=("Arial", "14", "normal"))
song1.setposition(-200, -180) # ADDED SO NEXT ONE IS ON DIFFERENT LINE
song1string2 = ("_minem _ap _od")
song1.write(song1string2, False, align="Left", font=("Arial", "14", "normal"))
song1.hideturtle()
#song1.clear() # DISABLED
songs = []
songs.append(song1string)
songs.append(song1string2)
pickle.dump(songs, open("songs.pkl", "wb")) # Changed file name.
songs = pickle.load(open("songs.pkl", "rb")) # Changed file name.
final_song = random.choice(songs) # CHANGED TO SELECT ONE FROM UNPICKLED LIST.
print('final_song: {!r}'.format(final_song)) # ADDED
screen.mainloop()

Implement Python tkinter zoom with turtle and single/double click

I am trying to draw turtle in canvas and I am also trying to implement zoom in zoom out feature with single click and double click event. When I am not trying to implement tkinter the code works absolutely fine but when I am trying to perform zoom in zoom out feature, I am unable to execute it. I would greatly appreciate any suggestions or help.
Here is my code:
import turtle
import tkinter as tk
from tkinter import *
root = tk.Tk()
canvas = tk.Canvas(master = root, width = 2700, height = 2500)
canvas.pack(fill=BOTH, expand=1)
mb = Menubutton(None, text='Mouse Clicks')
mb.pack()
t = turtle.RawTurtle(canvas)
def parallel():
window= canvas
def zoomin(event):
d = event.delta
if d < 0:
amt=0.9
else:
amt=1.1
canvas.scale(ALL, 2700,2500 , amt,amt)
mb.bind('<Button-1>', zoomin)
def zoomout(event1, d1, amt1):
d1 = event1.delta
if d1 >0:
amt1=1.1
else:
amt1=0.7
canvas.scale(ALL, 2700,2500 , amt, amt)
mb.bind('<Double-1>', zoomout)
t.pu()
t.left(90)
t.forward(70)
t.rt(90)
t.pd()
t.width(8)
t.color("LightGray")
t.forward(1200)
t.back(1200)
t.pu()
t.left(90)
t.forward(25)
t.rt(90)
t.pd()
t.forward(1200)
t.back(1200)
t.pu()
t.setposition(-85, 45)
t.pd()
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.forward(80)
t.left(90)
t.penup()
t.goto(-200, 160)
t.write("Class", True, align="center", font=('TimesNewRoman', 20, 'normal'))
t.pendown()
t.penup()
t.goto(-45, 150)
t.write("1", True, align="center", font=('TimesNewRoman', 50, 'normal'))
t.pendown()
parallel()
t.mainloop()
Thank you.
Your program seems incomplete and structured incorrectly. Below is my minimalist example of what I believe you're trying to do. It draws a circle and then lets you use the mouse wheel to zoom it in and out:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
def zoom(event):
amount = 0.9 if event.delta < 0 else 1.1
canvas.scale(tk.ALL, 0, 0, amount, amount)
root = tk.Tk()
canvas = ScrolledCanvas(master=root, width=2000, height=2000)
canvas.pack(fill=tk.BOTH, expand=tk.YES)
screen = TurtleScreen(canvas)
turtle = RawTurtle(screen)
turtle.penup()
turtle.sety(-250)
turtle.pendown()
turtle.circle(250)
canvas.bind('<MouseWheel>', zoom)
screen.mainloop()
Note that certain turtle elements, like dot() and text generated with write() won't zoom, they'll remain fixed. You'll need to read about the .scale() method, and go deeper into tkinter, to potentially work around this. Or manually scale your fonts yourself.

How do I get data from tkinter and add it into turtle?

I've been trying to tkinters .Entry command and use the user input to put into turtle, but I keep getting an error:
In my case, I am trying to ask the user for a color that they want to use in turtle.
My code:
import tkinter
from turtle import Turtle
#Create and Format window
w = tkinter.Tk()
w.title("Getting To Know You")
w.geometry("400x200")
#Favorite Color
lbl3= tkinter.Label(w, text = "What's your favorite color?")
lbl3.grid(row = 10 , column = 2)
olor = tkinter.Entry(w)
olor.grid(row = 12, column = 2)
t = Turtle()
t.begin_fill()
t.color(olor)
shape = int (input ("What is your favorite shape?"))
w.mainloop()
My recommendation is you work within turtle completely and not drop down to the tkinter level:
from turtle import Turtle, Screen
# Create and Format window
screen = Screen()
screen.setup(400, 200)
screen.title("Getting To Know You")
# Favorite Color
color = screen.textinput("Choose a color", "What's your favorite color?")
turtle = Turtle()
turtle.color(color)
turtle.begin_fill()
turtle.circle(25)
turtle.end_fill()
turtle.hideturtle()
screen.mainloop()
If you must do this from tkinter, you need to read more about tkinter elements like Entry to know their capabilities. You also need to read more about turtle as it is invoked differently when embedded inside of a tkinter window. Here's a rough approximation of what you're trying to do:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
root = tk.Tk()
root.geometry("400x200")
root.title("Getting To Know You")
def draw_circle():
turtle.color(color_entry.get())
turtle.begin_fill()
turtle.circle(25)
turtle.end_fill()
# Favorite Color
tk.Label(root, text="What's your favorite color?").pack()
color_entry = tk.Entry(root)
color_entry.pack()
tk.Button(root, text='Draw Circle', command=draw_circle).pack()
canvas = ScrolledCanvas(root)
canvas.pack(fill=tk.BOTH, expand=tk.YES)
screen = TurtleScreen(canvas)
turtle = RawTurtle(screen, visible=False)
screen.mainloop()

Categories

Resources