How do you make a conditional loop with onkeypress()? - python

I'm working on a python project for my intro class where I want to make a blizzard with the turtle module. So far, I've been able to make a "snowflake" appear on each keypress but I'm not sure how to make it into a conditional loop where when I click, it becomes true and keeps looping without me having to click again.
Here's the code I have right now:
def snowing(x, y):
w.speed(0)
flake_size = randint(1, 5)
rx = randint(-250, 250)
ry = randint(-300, 300)
w.color(colours[5])
w.setposition(rx, ry)
w.pendown()
w.begin_fill()
w.circle(flake_size)
w.end_fill()
w.penup()
listen()
onscreenclick(snowing, add=None)

when I click, it becomes true and keeps looping without me having to
click again.
We can make a separate event handler that is a toggle, using a global to switch between on and off on subsequent clicks. We'll combine that with a timer event to keeps the flakes coming:
from turtle import Screen, Turtle
from random import randint, choice
COLOURS = ['light gray', 'white', 'pink', 'light blue']
is_snowing = False
def toggle_snowing(x, y):
global is_snowing
if is_snowing := not is_snowing:
screen.ontimer(drop_flake)
def drop_flake():
flake_radius = randint(1, 5)
x = randint(-250, 250)
y = randint(-300, 300)
turtle.setposition(x, y)
turtle.color(choice(COLOURS))
turtle.begin_fill()
turtle.circle(flake_radius)
turtle.end_fill()
if is_snowing:
screen.ontimer(drop_flake)
turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()
screen = Screen()
screen.setup(500, 600)
screen.bgcolor('dark blue')
screen.onclick(toggle_snowing)
screen.listen()
screen.mainloop()
When you click on the screen, the flakes will start appearing. When you click again, they will stop.

Related

Python screen displays coordinates , but won't stop when I click a specific x,y coordinate

Python screen displays the coordinates after every click, but it won't break the loop when I reach a specific x,y coordinate. It's important to my game and has to be precise. This is what I've put together so far:
import turtle
from turtle import *
from turtle import Turtle, Screen
import random
import time
screen = Screen()
screen.bgcolor("green")
tur = turtle
screen.setup(width=800, height=600)
x = xcor()
y = ycor()
pen = Turtle()
tur = Turtle()
tur = Turtle(shape="turtle")
tur.color("black")
tur.speed("fastest")
tur.color("black")
tur.goto(x=16, y=-132)
while True:
def get_mouse_click_coor(x, y):
print(x, y)
tur.clear()
tur.write((x, y))
if get_mouse_click_coor() == (16, -132):
print("win")
turtle.onscreenclick(get_mouse_click_coor)
turtle.mainloop()
You should make the while loop stop.
One way to do this, is by defining a global flag. Put the flag in the condition of the while. When the desired coordinates are met, set the flag to False.
I also recommend to define the get_mouse_click_coor function out of the while loop, because at each loop, this function gets defined, however using as it is, does not make any problem.
play = True
def get_mouse_click_coor(x, y):
print(x, y)
tur.clear()
tur.write((x, y))
if get_mouse_click_coor() == (16, -132):
print("win")
play = False
while play:
turtle.onscreenclick(get_mouse_click_coor)
turtle.mainloop()

How do I make a python turtle program wait a bit?

So I'm making a game where the two turtles race each other, but I want them to wait a bit before they start (to display a 3,2,1) screen. But I can't figure it out! I used time.sleep, and turtle.delay, but both did not work. What can I do? Here is the code :)
import turtle
import random
import time
turt = turtle.Turtle()
turt2 = turtle.Turtle()
turtle.Screen() .bgcolor("green")
turt.speed(10)
turt.penup()
turt.goto(200,100)
turt.pendown()
turt.right(90)
turt.width(10)
turt.forward(450)
turt.right(180)
turt.forward(800)
#position 1
turt.penup()
turt.goto(-400,200)
turt.pendown()
turt.right(90)
turt.forward(100)
#position 2
turt2.width(10)
turt2.penup()
turt2.goto(-400,-200)
turt2.pendown()
turt2.forward(100)
Contrary to the advice so far, I'd avoid sleep() in my turtle program and use ontimer() instead to countdown the start of the race:
from turtle import Screen, Turtle
from random import choice
FONT = ('Arial', 36, 'bold')
def race():
while turtle_1.xcor() < 200 > turtle_2.xcor():
choice([turtle_1, turtle_2]).forward(10)
def countdown(seconds=3):
pen.clear()
if seconds < 1:
screen.ontimer(race)
else:
pen.write(seconds, align='center', font=FONT)
screen.ontimer(lambda: countdown(seconds - 1), 1000)
screen = Screen()
screen.bgcolor('green')
marker = Turtle()
marker.hideturtle()
marker.speed('fastest')
marker.color('white')
marker.width(5)
marker.penup()
marker.goto(200, 300)
marker.pendown()
marker.right(90)
marker.forward(600)
pen = Turtle()
pen.hideturtle()
turtle_1 = Turtle()
turtle_1.shape('turtle')
turtle_1.color('red')
turtle_1.penup()
turtle_1.goto(-400, 200)
turtle_2 = turtle_1.clone()
turtle_1.color('blue')
turtle_2.goto(-400, -200)
countdown()
screen.exitonclick()

How to make multiple turtles move in a line at the same time

My goal is to be able to make a snake(three turtles next to each other) move at the same time and also make the snake turn using arrow keys. I have tried the ontimer method/function but it does not work as expected. Here is my code:
import make_snake
from turtle import Turtle, Screen
game_is_on = True
screen = Screen()
screen.setup(600, 600)
screen.bgcolor("black")
screen.title("Snake Game")
snake_seg1 = make_snake.snake_segments[0]
snake_seg2 = make_snake.snake_segments[1]
snake_seg2.setheading(snake_seg1.heading())
snake_seg3 = make_snake.snake_segments[2]
snake_seg3.setheading(snake_seg2.heading())
def move_forward():
snake_seg1.forward(20)
def move_backward():
snake_seg1.backward(20)
def turn_left():
snake_seg1.left(90)
def turn_right():
snake_seg1.right(90)
screen.onkey(move_forward, "Up")
screen.onkey(move_backward, "Down")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
while game_is_on:
for seg in make_snake.snake_segments:
seg.forward(20)
# def follow_head():
# snake_seg1.forward(20)
# snake_seg2.setheading(snake_seg1.heading())
# snake_seg2.forward(20)
# snake_seg3.setheading(snake_seg2.heading())
# snake_seg3.forward(20)
# screen.ontimer(follow_head, 0)
screen.exitonclick()
File make_snake:
from turtle import Turtle
start_positions = [0, 20, 40]
snake_segments = []
for position in start_positions:
snake_part = Turtle(shape="square")
snake_part.color("white")
snake_part.penup()
snake_part.backward(position)
snake_segments.append(snake_part)
What can I fix in my code to make it stop moving one turtle at a time?
Your program has at least one problem: you use onkey() but forgot to call listen() to allow key events.
Here's a minimalist rework of your code to get basic snake movement working, it just supports right and left turns:
from turtle import Turtle, Screen
SEGMENT_SIZE = 20
START_COORDINATES = [-SEGMENT_SIZE * count for count in range(5)]
def turn_left():
snake_segments[0].left(90)
screen.update()
def turn_right():
snake_segments[0].right(90)
screen.update()
def move_forward():
for index in range(len(snake_segments) - 1, 0, -1):
snake_segments[index].goto(snake_segments[index - 1].position())
snake_segments[0].forward(SEGMENT_SIZE)
screen.update()
screen.ontimer(move_forward, 250)
screen = Screen()
screen.setup(600, 600)
screen.title("Snake Game")
screen.tracer(False)
snake_segments = []
for position in START_COORDINATES:
snake_segment = Turtle(shape='circle', visible=False)
snake_segment.penup()
snake_segment.setx(position)
snake_segment.showturtle()
snake_segments.append(snake_segment)
snake_segments[0].color('red')
screen.onkey(turn_left, 'Left')
screen.onkey(turn_right, 'Right')
screen.listen()
screen.update()
move_forward()
screen.exitonclick()
Be careful, it's easy to lose the snake off the edge of the window and not be able to get it back again!
The thing you might be looking for here is called multiprocessing. There is an eponymous library to execute lines of code simultaneously in Python. For reference look at the following thread:
Python: Executing multiple functions simultaneously

Python turtle mouse does not follow directly

How do you make turtle move without using turtle.goto(x,y) but turtle.speed(speed) and turtle.heading(angle)? I need this for a game I am making. Where the mouse is, I want to make it go in that direction. But when I change it, it goes to that place then to my mouse:
import turtle
screen = turtle.Screen()
screen.title("Test")
screen.bgcolor("white")
screen.setup(width=600, height=600)
ship = turtle.Turtle()
ship.speed(1)
ship.shape("triangle")
ship.penup()
ship.goto(0,0)
ship.direction = "stop"
ship.turtlesize(3)
turtle.hideturtle()
def onmove(self, fun, add=None):
if fun is None:
self.cv.unbind('<Motion>')
else:
def eventfun(event):
fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale)
self.cv.bind('<Motion>', eventfun, add)
def goto_handler(x, y):
onmove(turtle.Screen(), None)
ship.setheading(ship.towards(x, y)) #this is where you use the x,y cordinates and I have seat them to got to x,y and set heading
ship.goto(x,y)
onmove(turtle.Screen(), goto_handler)
onmove(screen, goto_handler)
If you only setheading and speed it just turns that way and does not move. If you try this code it works -- it is just that I use ship.goto(x, y) which makes it go to (x, y). But when you change your mouse when it is moving, it first goes to (x, y) then to your new mouse position. I pretty much just want it to just follow the mouse but I can not do that.
I believe the code below gives you the motion you desire. It only uses onmove() to stash the target's position and uses an ontimer() to aim and move the turtle. It also stops when the target has been enveloped:
from turtle import Screen, Turtle, Vec2D
def onmove(self, fun, add=None):
if fun is None:
self.cv.unbind('<Motion>')
else:
def eventfun(event):
fun(Vec2D(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale))
self.cv.bind('<Motion>', eventfun, add)
def goto_handler(position):
global target
onmove(screen, None)
target = position
onmove(screen, goto_handler)
def move():
if ship.distance(target) > 5:
ship.setheading(ship.towards(target))
ship.forward(5)
screen.ontimer(move, 50)
screen = Screen()
screen.title("Test")
screen.setup(width=600, height=600)
ship = Turtle("triangle")
ship.turtlesize(3)
ship.speed('fast')
ship.penup()
target = (0, 0)
onmove(screen, goto_handler)
move()
screen.mainloop()

players not moving simultaneously

I am attempting to make a game in python with the turtle module, I have the square moving towards the player (the circle) and the aim is for the circle to jump over the square and not get hit.
The player can jump by pressing the spacebar,
but every time you hit the space bar to jump the player jumps, but the square stops moving and you are unable to jump over.
here is my code:
import turtle
import time
wn = turtle.Screen()
wn.bgcolor("white")
wn.title("dinosaur run")
wn.tracer(1,20)
floor = turtle.Turtle()
floor.fd(370)
floor.bk(370*2)
floor.ht()
player = turtle.Turtle()
player.shape("circle")
player.penup()
player.setpos(-370,14)
def jump():
player.lt(90)
player.fd(40)
time.sleep(0.5)
player.bk(40)
player.rt(90)
turtle.listen()
turtle.onkey(jump, "space")
class cactus(turtle.Turtle):
turtle.shape("square")
turtle.penup()
turtle.speed(0)
turtle.setpos(370,14)
cactusspeed = 2
while True:
x = turtle.xcor()
x -= cactusspeed
turtle.setx(x)
Thanks a lot,
all ideas welcome,
I've tried wn.update() at the end
As provided above, your code doesn't run at all as cactusspeed never gets defined. And your class cactus doesn't have a hope of working as currently laid out (reread about Python classes.) Finally, your while True: has no business in an event driven world like turtle.
Below is my rework of your code to use an ontimer() event to control the cactus independent of the player. I also eliminated the sleep() and simply made the player move slower and jump higher. I believe this should give you the dynamic you're looking for:
from turtle import Turtle, Screen
def jump():
player.forward(100)
player.backward(100)
def move():
if cactus.xcor() < -screen.window_width()/2:
cactus.hideturtle()
cactus.setx(370)
cactus.showturtle()
else:
cactus.forward(cactusspeed)
screen.ontimer(move, 40)
screen = Screen()
floor = Turtle(visible=False)
floor.speed('fastest')
floor.fd(370)
floor.bk(370 * 2)
player = Turtle("circle", visible=False)
player.penup()
player.setpos(-370, 14)
player.setheading(90)
player.speed('slowest')
player.showturtle()
cactusspeed = 4
cactus = Turtle("square", visible=False)
cactus.speed('fastest')
cactus.penup()
cactus.setpos(370, 14)
cactus.setheading(180)
cactus.showturtle()
screen.onkey(jump, "space")
screen.listen()
move()
screen.mainloop()

Categories

Resources