Collision Detector Decoding Issues - python

I can move the turtle to the FINISH, but my collision detector isn't working when the turtle crosses the finish line. It will cross the white boundary lines, but I need it to stop when it hits the word FINISH. Also need to keep the turtle within the boundaries. Maybe I need to decode the xcor() algorithm? Please help!
import turtle as trtl
background = trtl.Screen()
background.screensize(canvwidth =1, canvheight=1)
boundary = trtl.Turtle()
#draw square boundary
def squareDraw(boundary):
boundary.speed(0)
boundary.pu()
boundary.goto(-175,160)
boundary.pd()
for i in range(4):
boundary.color("white")
boundary.forward(315)
boundary.right(90)
boundary.ht()
squareDraw(boundary)
boundary.pu()
boundary.goto(-40,160)
boundary.color("red")
boundary.pd()
boundary.write("FINISH!", font=40)
#moving square coordinates
turtleCoordinate = (-25,-120)
turtleShape = trtl.Turtle()
turtleShape.left(90)
turtleShape.shape("turtle")
turtleShape.color("orange")
turtleShape.shapesize(1.75)
turtleShape.pu()
turtleShape.goto(turtleCoordinate)
#boundarys for answers
obstacles = trtl.Turtle()
obstacles.speed(0)
obstacles.pu()
obstacles.goto(-120,90)
obstacles.color("white")
for i in range(4):
obstacles.pd()
obstacles.forward(50)
obstacles.right(90)
obstacles.ht()
obstacles.pu()
obstacles.goto(0,12)
obstacles.color("white")
for i in range(4):
obstacles.pd()
obstacles.forward(40)
obstacles.right(90)
obstacles.ht()
obstacles.pu()
obstacles.goto(68,125)
obstacles.color("white")
for i in range(4):
obstacles.pd()
obstacles.forward(30)
obstacles.right(90)
obstacles.ht()
#1st math problem
firstProblem = []
secondProblem = [8,2,1]
#steps = 0
#while steps < 100:
for turtleShape in firstProblem:
turtleShape.forward(4)
if turtleShape.xcor() > 140:
turtleShape.right(180)
elif turtleShape.xcor() > -175:
turtleShape.left(180)
if turtleShape.ycor() > 160:
turtleShape.right(180)
elif turtleShape.ycor() < -155:
turtleShape.right(180)
#actions to move turtle
move_speed = 15
def left():
turtleShape.left(move_speed)
def right():
turtleShape.right(move_speed)
def forward():
turtleShape.forward(move_speed)
def backward():
turtleShape.backward(move_speed)
background.onkey(forward, "Up")
background.onkey(backward, "Down")
background.onkey(left, "Left")
background.onkey(right, "Right")
background.listen()
steps = 0
for turtleShape in firstProblem:
stepMax = 15
if steps > stepMax:
turtleShape.forward(3)
background = trtl.Screen()
background.mainloop()

Move the boundary checking in the left(), right(), forward(), backward() functions. Example: In the forward function, you would check if you are hitting the boundary and only do a forward by min(move_speed, boundary - y position). That will make you stop exactly at the boundary.

Related

How to stop turtle movement when two turtles are in proximity of each other?

I'm making a game when the user has to move the car to dodge obstacles, Everything working except I can't get the game to and end. My goal is to end the game when the block hits the turtle.
The issue is I can't get the game to detect the turtles to detect their proximity and the exit or quit command doesn't work. Also I don't think the code pasted properly so adjust the indents if it doesn't work.
import turtle as trtl
import random as rand
import sys
#initialize turtles
turtle = trtl.Turtle(shape = "turtle")
block = trtl.Turtle(shape = "square")
drawer = trtl.Turtle()
blockList = []
wn = trtl.Screen()
#game configuration
turtle.pu()
turtle.goto(0,-150)
drawer.pu()
drawer.goto(0,-160)
drawer.pd()
drawer.pensize(10)
drawer.pencolor("blue")
drawer.forward(180)
drawer.left(90)
drawer.forward(300)
drawer.left(90)
drawer.forward(350)
drawer.left(90)
drawer.forward(300)
drawer.left(90)
drawer.forward(180)
drawer.hideturtle()
def turtleRight():
turtle.setheading(0)
turtle.pu()
turtle.forward(15)
def turtleLeft():
turtle.setheading(180)
turtle.pu()
turtle.forward(15)
#actions
wn.onkeypress(turtleRight, 'Right')
wn.onkeypress(turtleLeft, 'Left')
wn.listen()
for i in range(5):
app = block
blockList.append(app)
#functions
def draw_blocks(index):
blockList[index].penup()
blockList[index].shape("square")
wn.tracer(False)
blockList[index].setx(rand.randint(-150,150))
blockList[index].sety(rand.randint(0,125))
blockList[index].showturtle()
wn.tracer(True)
wn.update()
def drop_block(index):
blockList[index].penup()
blockList[index].clear()
blockList[index].speed(2)
blockList[index].sety(-150)
blockList[index].hideturtle()
draw_blocks(index)
xDistance = abs(turtle.xcor()-block.xcor())
yDistance = abs(turtle.ycor()-block.ycor())
if (xDistance < 20 and yDistance < 20):
sys.exit()
else:
drop_block(i)
for i in range(5):
drop_block(i)
wn.mainloop()
trtl.done()
Can anyone help..!?
The problem is that you're re-drawing the block and thus resetting its position before you're testing the distance.
Alter the function like so:
def drop_block(index):
blockList[index].penup()
blockList[index].clear()
blockList[index].speed(2)
blockList[index].sety(-150)
blockList[index].hideturtle()
xDistance = abs(turtle.xcor()-block.xcor())
yDistance = abs(turtle.ycor()-block.ycor())
print(xDistance, yDistance)
if (xDistance < 20 and yDistance < 20):
sys.exit()
else: # redraw blocks _after_ calculating distance
draw_blocks(index)
drop_block(i)

Turtle layering (probably)

I'm making a rip-off game that's based on those magic tile games where you tap your finger at one of 4 sections at the bottom to play a note. It is always sideways instead. Right now I"m working on letting the player (the black square on the left) move while the animation for the colored tiles is moving. Right now it is just before the functions that draw the tiles, and I have tried putting the functions within the function that makes the tiles.
import turtle as trtl
import random as rand
leader_colors = []
wn = trtl.Screen()
player = trtl.Turtle()
player.speed(150)
player.penup()
player.shape("square")
player.shapesize(7.5)
player.goto(-850,0)
player.speed(50)
def goUp():
y = player.ycor()
player.goto(-850, y + 150)
def goDown():
y = player.ycor()
player.goto(-850, y - 150)
def tileMaker1(many):
distance = 0
length = 0
postion = 1420
for i in range(many):
i = trtl.Turtle()
i.hideturtle()
i.penup()
i.pensize(145)
i.pencolor("white")
i.shapesize(175)
i.pensize(145)
i.penup()
i.setheading(180)
i.penup()
i.shape("square")
i.shapesize(7.2)
i.hideturtle()
i.goto(postion, 0)
i.showturtle()
i.penup()
while distance < 51:
i.color("blue")
i.forward(50)
distance += 1
length += 50
wn.onkeypress(goUp, "Up")
wn.onkeypress(goUp, "w")
wn.onkeypress(goDown, "Down")
wn.onkeypress(goDown, "s")
tileMaker1(4)

I want a bouncing ball on the wall in turtlegraphics, but they stop and they wander and send an error

i draw some triangles and they should bounce on the wall,but they don't bounce, they don't go straight, they print an error message after a few seconds.
When I let the triangles move only in the shape of a cross, the triangles faltered and an error message came out.
import turtle
import random
def draw_sq(t,distance=400):#Draw a box
t.penup()
t.goto(-200,200)
t.pendown()
t.forward(distance)
t.right(90)
t.forward(distance)
t.right(90)
t.forward(distance)
t.right(90)
t.forward(distance)
t.penup()
t.goto(0,0)
t.pendown()
def add_tri():
global l_tri
t=turtle.Turtle()
t.shape("triangle")
x=-200
y=random.randint(-200,200)
t.penup()
t.goto(x,y)
t.setheading(random.randint(-89,89))
# make triangle and start
l_tri.append(t)# add a triangle to list
def successMan():#write word succes
global playing
if playing==True:
t.write("success")
def turn_right():
global right
right = True
def turn_left():
global left
left = True
def turn_up():
global up
up = True
def turn_down():
global down
down = True
def _turn_right():
global right
right = False
def _turn_left():
global left
left = False
def _turn_up():
global up
up = False
def _turn_down():
global down
down = False
def is_touch(x,y,triangle,threshold=20):
global playing
if((x-triangle.position()[0])**2+(y-triangle.position()[1])**2<=threshold**2):
playing=False#if triangle touches the turtle make playing False
def timer_go():
global heading
global l_tri
global t
global playing
global up
global left
global down
global right# heading is where turtle heads
if up:
if right:
heading=45
elif left:
heading=135
elif down:
heading = heading
else:
heading=90
if down:
if right:
heading=315
elif left:
heading=225
elif up:
pass
else:
heading = 270
if left:
if right:
heading = heading
elif up:
pass
elif down:
pass
else:
heading = 180
if right:
if left:
pass
elif up:
pass
elif down:
pass
else:
heading = 0
t.setheading(heading)
t.forward(10)
# turtle controller
for i in range(3):#triangles move
if (l_tri[i].position()[0]<-200):
l_tri[i].setheading(180-l_tri[i].heading())
l_tri[i].forward(10)
if (l_tri[i].position()[0]>200):
l_tri[i].setheading(180-l_tri[i].heading())
l_tri[i].forward(10)
if (l_tri[i].position()[1]<-200):
l_tri[i].setheading(-l_tri[i].heading())
l_tri[i].forward(10)
if (l_tri[i].position()[1]>200):
l_tri[i].setheading(-l_tri[i].heading())
l_tri[i].forward(10)#triangle bounces on the wall
l_tri[i].forward(10)
is_touch(t.position()[0],t.position()[1],l_tri[i],threshold=20)
# check triangle and turtle
if (playing==False):
t.write("FAIL")
#Fail
up = False
down = False
right = False
left = False
playing = True
heading = 0
l_tri = []
t = turtle.Turtle()
t.shape('turtle')
t.speed(0)
draw_sq(t)
screen = t.screen
screen.onkeypress(turn_right, 'Right')
screen.onkeypress(turn_left, 'Left')
screen.onkeypress(turn_up, 'Up')
screen.onkeypress(turn_down, 'Down')
screen.onkeyrelease(_turn_right, 'Right')
screen.onkeyrelease(_turn_left, 'Left')
screen.onkeyrelease(_turn_up, 'Up')
screen.onkeyrelease(_turn_down, 'Down')
for i in range(3):
add_tri()
for i in range(1,200):
time = i*100
screen.ontimer(timer_go, time)
screen.ontimer(successMan,20000)
screen.listen()
screen.mainloop()
This should be a game where the player avoids triangles in the box.
When I run it I see error
RecursionError: maximum recursion depth exceeded while calling a Python object
but I don't see recursion in code.
Maybe problem is
for i in range(1,200):
time = i*100
screen.ontimer(timer_go, time)
Probably it creates too many functions.
You can run it once
screen.ontimer(timer_go, 100)
and use it again at the end of timer_go()
def timer_go():
# ... rest of code ...
screen.ontimer(timer_go, 100)
and it will repeat it all time.
You can see this method even in official documentatiton: turtle.ontimer
I agree with #furas (+1) about how to set up your ontimer(timer_go, 100), but I see other issues with your code. I've reworked it below and I hope you find some of the changes useful.
Specific issues: you need to (re)read about global as half the time you're using it incorrectly; you don't need to reinvent turtle.distance() (e.g. in is_touch()); you need to separate playing == False from failure as you need to stop play on either success or failure; You should only need to specify the number of triangles in one place:
from turtle import Screen, Turtle
from random import randint, choice
FONT = ('Arial', 16, 'normal')
def draw_square(turtle, distance=400): # Draw a box
turtle.speed('fastest')
turtle.penup()
turtle.goto(-200, 200)
turtle.pendown()
for _ in range(4):
turtle.forward(distance)
turtle.right(90)
def add_triangle():
triangle = Turtle("triangle")
triangle.penup()
triangle.goto(choice([(choice([-150, 150]), randint(-150, 150)), (randint(-150, 150), choice([-150, 150]))]))
triangle.setheading(randint(-89, 89))
# make triangle and start
triangles.append(triangle) # add a triangle to list
def successMan(): # write word success
global playing
if playing:
player.write("Success!", font=FONT)
playing = False
def turn_right():
global right
right = True
def turn_left():
global left
left = True
def turn_up():
global up
up = True
def turn_down():
global down
down = True
def _turn_right():
global right
right = False
def _turn_left():
global left
left = False
def _turn_up():
global up
up = False
def _turn_down():
global down
down = False
def is_touch(player, triangle, threshold=20):
return player.distance(triangle) < threshold
def timer_go():
global playing
heading = player.heading()
if up:
if right:
heading = 45
elif left:
heading = 135
elif down:
pass
else:
heading = 90
if down:
if right:
heading = 315
elif left:
heading = 225
elif up:
pass
else:
heading = 270
if left:
if right:
pass
elif up:
pass
elif down:
pass
else:
heading = 180
if right:
if left:
pass
elif up:
pass
elif down:
pass
else:
heading = 0
player.setheading(heading)
player.forward(10)
# turtle controller
for triangle in triangles: # triangles move
x, y = triangle.position()
if not -200 < x < 200:
triangle.setheading(180 - triangle.heading())
triangle.forward(10)
if not -200 < y < 200:
triangle.setheading(-triangle.heading())
triangle.forward(10)
triangle.forward(10)
# check triangle and turtle
if is_touch(player, triangle, threshold=20):
playing = False
player.write("FAIL!", font=FONT) # Fail
if playing:
screen.ontimer(timer_go, 100)
up = False
down = False
right = False
left = False
playing = True
triangles = []
draw_square(Turtle(visible=False))
for _ in range(3):
add_triangle()
player = Turtle('turtle')
player.speed('fastest')
screen = Screen()
screen.onkeypress(turn_right, 'Right')
screen.onkeypress(turn_left, 'Left')
screen.onkeypress(turn_up, 'Up')
screen.onkeypress(turn_down, 'Down')
screen.onkeyrelease(_turn_right, 'Right')
screen.onkeyrelease(_turn_left, 'Left')
screen.onkeyrelease(_turn_up, 'Up')
screen.onkeyrelease(_turn_down, 'Down')
screen.ontimer(successMan, 20_000)
timer_go()
screen.listen()
screen.mainloop()
I suspect your RecursionError is due to your key events as your model seems to be that multiple keys can go down at a time. But if a key is held too long, it can cause a key event inside a key event and this looks like recursion. You can usually fix this by disabling the key event handler as the first thing inside the event hander, do your work, and then reenable the key event handler.
However, you may also have the OS-controlled automatic key repeat logic working against you. If your key handling turns out to be a problem, consider using a simpler approach.

Make the snake in game move piece by piece instead of as a whole

My game is a snake game where you have to get the fruit. This is the code:
#Importing random and turtle module
import random
import turtle as t #Shortening the turtle module to t
#Adding a orange background
t.bgcolor("orange")
#Creating a turtle to become the snake
snake = t.Turtle() # Creates a new turtle for the snake
snake.shape("square") # Making the snake square shaped
snake.color("green") # Making the snake green
snake.speed(0) # Making the snake not move before the game starts
snake.penup() # Disables the turtles pen allowing the turtle to move around the screen without drawing a line along the way
snake.hideturtle() #This command hides the turtle
#Creating a turtle to draw the leaves
fruit = t.Turtle() # Creates a new turtle for the fruit
fruit.shape("circle") # Making the fruit circular
fruit.color("red") # Making the fruit red
fruit.penup() # Disables the turtles pen allowing the turtle to move around the screen without drawing a line along the way
fruit.hideturtle() #This command hides the turtle
fruit.speed(0) # Making the fruit not move
#Adding more turtles to display the text for the game and the score
gamestarted = False #To know if the game has started
writeturtle = t.Turtle()# Creates a new turtle for the text
writeturtle.write("Press SPACE to play!", align="center", font=("Calibri", 16, "bold")) #This line draws text on the screen
writeturtle.hideturtle() # Hides the turtle but not the text
#Adding a score turtle
scoreturtledude = t.Turtle()# Creates a new turtle for the score
scoreturtledude.hideturtle()#This command hides the turtle
scoreturtledude.speed(0)#Make sure the turtle stays where it is so it can update the score
def outsidewindow(): #Defining the outside window function
leftwall = -t.window_width() / 2 #Calculates the left wall
rightwall = t.window_width() / 2 #Calculates the right wall
topwall = t.window_height() / 2 #Calculates the top wall
bottomwall = -t.window_height() / 2 #Calculates the bottom wall
(x, y) = snake.pos() #Then it asks the snake for its current position
outside = x< leftwall or x> rightwall or y< bottomwall or y> topwall #Comparing the snakes coordinates with the wall position
return outside #If any of the four conditions above is true then outside is true
def gameover(): #Defining gameover
snake.color("orange")#CHANGES THE COLOR OF THE SNAKE TO ORANGE(the same color as the background) so it can't be seen
fruit.color("orange")#CHANGES THE COLOR OF THE SNAKE TO ORANGE(the same color as the background) so it can't be seen
t.penup() # this disables the turtles pen
t.hideturtle() #This hides the turtle
t.write("YOUR SNAKE CRAWLED INTO THE GARDEN. GAME OVER!", align="center", font=("Calibri", 20, "normal"))#This line writes a text for when the game is over
def showscore(currentscore):
scoreturtledude.clear()# This clears the score
scoreturtledude.penup()# Disables turtle pen
x = (t.window_width() / 2) -75 # 75 pixels from the right
y = (t.window_height() / 2) -75 # And 75 pixels from the top
scoreturtledude.setpos(x, y)#Sets the turtles position
scoreturtledude.write(str(currentscore) , align="right", font=("Calibri", 40, "bold"))# WRITES THE SCOre in calibri font
def placefruit():
fruit.hideturtle()
fruit.setposition(random.randint(-200, 200), random.randint(-200, 200))
fruit.showturtle()
def startgame():
global gamestarted
if gamestarted: #If the game has already started, the return command makes the function quit so it doesn't run a second time
return
gamestarted = True
score = 0 #Sets the score to 0
writeturtle.clear() # Clears the text from the screen
snakespeed = 2
snakelength = 3
snake.shapesize(1, snakelength, 1)#This makes the snake turtle stretch from a square shape into a snake shape
snake.showturtle() #This shows the snake
showscore(score) #This uses the showscore function we defined earlier
placefruit()
while True: #This puts it in a forever loop
snake.forward(snakespeed)
if snake.distance(fruit) < 20:# Makes the snake eat the leaf when it is less than 20 pixels away
placefruit() #This line places another fruit on the screen
snakelength = snakelength + 1 #This line line and the next line together will make the snake grow longer
snake.shapesize(1, snakelength, 1)
snakespeed = snakespeed + 1 #This increases the speed of the snake
score = score + 100 #This increases the score
showscore(score) #This shows the score
if outsidewindow():
gameover()
break
def up():
if snake.heading() == 0 or snake.heading() == 180: #checks if the snake is heading left or right
snake.setheading(90)#Heads the snake straight up
def down():
if snake.heading() == 0 or snake.heading() == 180:#checks if the snake is heading left or right
snake.setheading(270)#Heads the snake straight down
def left():
if snake.heading() == 90 or snake.heading() == 270:#checks if the snake is heading up or down
snake.setheading(180)#Heads the snake straight right
def right():
if snake.heading() == 90 or snake.heading() == 270:#checks if the snake is heading up or down
snake.setheading(0)#Heads the snake straight left
t.onkey(startgame, "space") # The onkey() function binds yhe space bar to the startgame () so the game will not start until the player presses space
t.onkey(up, "Up") #The onkey() function binds the up key to the startgame
t.onkey(down, "Down")#The onkey() function binds the down key to the startgame
t.onkey(right, "Right")#The onkey() function binds the right key to the startgame
t.onkey(left, "Left")#The onkey() function binds the left key to the startgame
t.listen() # The listen function allows the program to recieve signals from the key board
t.mainloop()
This code makes a game where the snake turns altogether, but I want the snake to turn piece by piece. Could you help me?
Below I've merged your game with this short example of how to move a segmented snake around the screen that I wrote earlier -- I'm surprised your search of SO didn't turn this up.
I've also made some other changes to accomodate this motion. Your snake changes from a turtle to a list of turtles, with the final turtle in the list being the head of the snake. The keyboard arrow handlers no longer change the snake's direction directly, they merely set a new direction variable for when the next turtle movement occurs -- this prevents conflicts in adjusting the turtle.
Your while True: has no place in an event-driven world like turtle so it's been replaced with an ontimer() event -- otherwise you potentially lock out events:
from random import randint
from turtle import Turtle, Screen # force object-oriented turtle
SCORE_FONT = ("Calibri", 40, "bold")
MESSAGE_FONT = ("Calibri", 24, "bold")
SEGMENT_SIZE = 20
def outsidewindow():
(x, y) = snake[-1].pos() # Ask the snake head for its current position
return not (leftwall < x < rightwall and bottomwall < y < topwall)
def gameover():
for segment in snake:
segment.hideturtle()
fruit.hideturtle()
writeturtle.write("Your snake crawled into the garden! Game over!", align="center", font=MESSAGE_FONT)
def showscore(currentscore):
scoreturtledude.undo() # Clear the previous score
scoreturtledude.write(currentscore, align="right", font=SCORE_FONT)
def placefruit():
fruit.hideturtle()
fruit.setposition(randint(-200, 200), randint(-200, 200))
fruit.showturtle()
def startgame():
screen.onkey(None, "space") # So this doesn't run a second time
writeturtle.clear() # Clear the text from the screen
showscore(score)
for segment in snake: # Show the snake
segment.showturtle()
placefruit()
rungame()
def rungame():
global score, snakelength
segment = snake[-1].clone() if len(snake) < snakelength else snake.pop(0)
screen.tracer(False) # segment.hideturtle()
segment.setposition(snake[-1].position())
segment.setheading(snake[-1].heading())
segment.setheading(direction)
segment.forward(SEGMENT_SIZE)
if outsidewindow():
gameover()
return
screen.tracer(True) # segment.showturtle()
snake.append(segment)
if snake[-1].distance(fruit) < SEGMENT_SIZE: # Make the snake eat the fruit when it is nearby
placefruit() # Place another fruit on the screen
snakelength += 1
score += 100
showscore(score)
screen.ontimer(rungame, max(50, 150 - 10 * len(snake))) # Speed up slightly as snake grows
def up():
global direction
current = snake[-1].heading()
if current == 0 or current == 180: # Check if the snake is heading left or right
direction = 90 # Head the snake up
def down():
global direction
current = snake[-1].heading()
if current == 0 or current == 180: # Check if the snake is heading left or right
direction = 270 # Head the snake down
def left():
global direction
current = snake[-1].heading()
if current == 90 or current == 270: # Check if the snake is heading up or down
direction = 180 # Head the snake left
def right():
global direction
current = snake[-1].heading()
if current == 90 or current == 270: # Check if the snake is heading up or down
direction = 0 # Head the snake right
screen = Screen()
screen.bgcolor("orange")
leftwall = -screen.window_width() / 2 # Calculate the left wall
rightwall = screen.window_width() / 2 # Calculate the right wall
topwall = screen.window_height() / 2 # Calculate the top wall
bottomwall = -screen.window_height() / 2 # Calculate the bottom wall
# Creating a turtle to become the snake
head = Turtle("square", visible=False) # Create a new turtle for the snake
head.color("green") # Make the snake green
head.penup() # Disable the turtle's pen, allowing the turtle to move around the screen without leaving a trail
snake = [head]
snakelength = 3
score = 0
direction = 0
# Creating a turtle to draw the leaves
fruit = Turtle("circle", visible=False) # Create a turtle for the fruit
fruit.penup() # Raise the turtle's pen, allowing turtle to move around screen without leaving a trail
fruit.color("red")
# Add more turtles to display the text for the game and the score
writeturtle = Turtle(visible=False) # Create a new turtle for the text
writeturtle.write("Press SPACE to play!", align="center", font=MESSAGE_FONT)
# Add a score turtle
scoreturtledude = Turtle(visible=False) # Create a new turtle for the score
scoreturtledude.penup() # Disable turtle pen
x = screen.window_width() / 2 - 75 # 75 pixels from the right
y = screen.window_height() / 2 - 75 # And 75 pixels from the top
scoreturtledude.setpos(x, y) # Set the turtle's position
scoreturtledude.write('', align="right", font=SCORE_FONT)
screen.onkey(startgame, "space") # Bind space bar to startgame() so game will start when player presses space
screen.onkey(up, "Up") # Bind the up key to up()
screen.onkey(down, "Down") # Bind the down key to down()
screen.onkey(right, "Right") # Bind the right key to right()
screen.onkey(left, "Left") # Bind the left key to left()
screen.listen() # Allow the window to receive signals from the keyboard
screen.mainloop()
You've a number of issues in your code, e.g. little ones like what turtle is gameover() referring to when it does t.hideturtle()? But two major ones are:
Reread what speed(0) does -- you've misunderstood it.
You need to learn to write better comments. This is silly:
fruit.color("red") # Making the fruit red
This is pretty good:
t.listen() # The listen function allows the program to recieve signals from the key board

Snake Game Turtle Graphics in Python

So I have a project where I have to create a game in TURTLE graphics only without using any other modules except turtle and the random module. I am creating the traditional snake game except when the snake "eats" the object it doesn't get bigger. The problem with my game is that when the "snake" gets to the object, the object does not disappear and I want it to disappear and reappear in another position. Please Help. Here is the code:
from turtle import *
import random
setup(700, 700)
title("Snake Game!")
bgcolor("blue")
# Boundary
bPen = Pen()
bPen.color("Orange")
bPen.up()
bPen.goto(-300, -300)
bPen.down()
for i in range(4):
bPen.ht()
bPen.fd(600)
bPen.lt(90)
# Player
playerPen = Pen()
playerPen.color("Orange")
playerPen.up()
playerPen.width(4)
# Create Circle
circle = Pen()
circle.shape("circle")
circle.color("Red")
circle.up()
circle.speed(0)
circle.goto(-100, 100)
# Speed
speed = 2
# Movement functions
def left():
playerPen.lt(90)
def right():
playerPen.rt(90)
def speedBoost():
global speed
speed += 1
# Key Prompts
onkey(left, "Left")
onkey(right, "Right")
onkey(speedBoost, "Up")
listen()
# Infinity loop and player knockback
while True:
playerPen.fd(speed)
if playerPen.xcor() < -300 or playerPen.xcor() > 300:
playerPen.rt(180)
elif playerPen.ycor() < - 300 or playerPen.ycor() > 300:
playerPen.rt(180)
# Collision with circle
if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
circle.goto(random.randint(-300, 300), random.randint(-300, 300))
done()
The code works, but hitting the snake exactly on the center of the circle is difficult. To fix this, at the top of your code add a constant:
RADIUS = 10
That is roughly the radius of the circle. Then, change this line:
if playerPen.xcor() == circle.xcor() and playerPen.ycor() == circle.ycor():
to instead be:
if abs(playerPen.xcor() - circle.xcor()) < RADIUS and abs(playerPen.ycor() - circle.ycor()) < RADIUS:
And enjoy the game!
Or if you can't enjoy the game due not being able to use abs(), here's another way to write that same line without it:
if -RADIUS < playerPen.xcor() - circle.xcor() < RADIUS and -RADIUS < playerPen.ycor() - circle.ycor() < RADIUS:

Categories