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)
Related
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.
I can not get the right speed for bad and good players in this Minigame off YouTube called 'Falling Skies": GitHub Gist which uses the Python turtle module. How do I fix this? (I got stuck on Part 6 of the Minigame tutorial.)
import turtle # Our module's
import random
# Screen
ms = turtle.Screen()
ms.title("Falling Piece's mini_game by Rafa94")
ms.bgcolor("purple")
ms.setup(width=800, height=600)
ms.tracer(0)
#player
player = turtle.Turtle()
player.speed(0)
player.shape("turtle")
player.color("blue")
player.penup()
player.goto(0, -250) # y is postive in the up direction y is negative in the down direction
player.direction = "stop"
# create a list of good players # good represents good_player
goods =[]#Empty list
#Addgood players
for _ in range(20): # we are making a set of 20 players
good = turtle.Turtle() # we want the other player basically across from each other thats we copyed the code one on -y and one on +y (first player in the bottom, second player on top of Screen)
good.speed(0)
good.shape("circle")
good.color("red")
good.penup()
good.goto(0, 250) # y is postive in the up direction y is negative in the down direction
good.speed = random.randint(5,8)
goods.append(good)
# create a list of bad players # bad represents bad_players
bads = [] # Empty list
# Addbad players
for _ in range(20): # we are making a set of 20 players
bad = turtle.Turtle() # we want the other player basically across from each other thats we copyed the code one on -y and one on +y (first player in the bottom, second player on top of Screen)
bad.speed(10)
bad.shape("circle")
bad.color("yellow")
bad.penup()
bad.goto(0, 250) # y is postive in the up direction y is negative in the down direction
bad.speed = random.randint(5, 8)
bads.append(bad)
#Functions
def go_left():
player.direction = "left"
def go_right():
player.direction = "right"
#keyboard Binding
ms.listen() # it is bascally saying listen for keyboard input < ^ >
ms.onkeypress(go_left, "Left")
ms.onkeypress(go_right, "Right")
#Main game loop # while something is true it will repeat
while True:
# update screen
ms.update()
#Move player
if player.direction == "left":
x = player.xcor()
x -= + 3
player.setx(x)
if player.direction == "right":
x = player.xcor()
x += + 3
player.setx(x)
# Move Good Player
for good in goods:
y = good.ycor()
y -= good.speed # We want the ball to be falling at a smooth speed
good.sety(y)
# Check it off the Screen
if y < -300:
x = random.randint(-380, 380)
y = random.randint(300, 400)
good.goto(x, y)
# check for collision with player
if good.distance(player) < 20:
x = random.randint(-380, 380)
y = random.randint(300, 400)
good.goto(x, y)
# Move bad Player
for bad in bads:
y = bad.ycor()
y -= bad.speed # We want the ball to be falling at a slow speed
bad.sety(y)
# Check it off the Screen
if y < -300:
x = random.randint(-380, 380)
y = random.randint(300, 400)
bad.goto(x, y)
# check for collision with player
if bad.distance(player) < 20:
x = random.randint(-380, 380)
y = random.randint(300, 400)
bad.goto(x, y)
ms.mainloop()
If I understand your need, you want good guys and bad guys to move at different speeds. A key to this is understanding there are two concepts of speed at work in the program: turtle's speed() method:
player.speed(0)
good.speed(0)
bad.speed(10)
This one has to do with how fast the graphics are drawn, and not what we're interested in. And the game's own instance variable speed that the author hangs off of turtle instances:
good.speed = randint(5, 8)
bad.speed = randint(5, 8)
y -= good.speed
y -= bad.speed
Which probably shouldn't be called .speed since the turtle already has a .speed method. So we'll rename this to .velocity. This speed is how fast the object moves on the screen, and what we're interested in.
You changed the wrong one by setting good.speed(0) and bad.speed(10) which since they are not drawing, just moving turtle cursors, has little effect. What we want to do instead is change:
good.velocity = randint(1, 4) # was .speed
bad.velocity = randint(5, 8) # was .speed
And fix all our other uses of the .speed instance variable to be .velocity:
y -= good.velocity # was .speed
y -= bad.velocity # was .speed
I've made this change, among others, to the code below. You'll see that the good guys move about 2.5X faster than the bad guys:
# Our module's
from turtle import Screen, Turtle
from random import randint
# Functions
def go_left():
player.direction = 'left'
def go_right():
player.direction = 'right'
# Screen
screen = Screen()
screen.setup(width=800, height=600)
screen.title("Falling Piece's mini_game by Rafa94")
screen.bgcolor('purple')
screen.tracer(0)
# player
player = Turtle()
player.shape('turtle')
player.speed('fastest')
player.color('blue')
player.penup()
player.sety(-250) # y is positive in the up direction; negative in the down direction
player.direction = 'stop'
# Create a list of good players
# Good represents good_player
goods = [] # Empty list
# Add good players
for _ in range(20): # We are making a set of 20 players
# We want the other players basically across from each other
# thats we copyied the code one on -y and one on +y (first
# player in the bottom, second player on top of Screen)
good = Turtle()
good.shape('circle')
good.speed('fastest')
good.color('red')
good.penup()
good.goto(-100, 250) # y is positive in the up direction; negative in the down direction
good.velocity = randint(1, 4)
goods.append(good)
# Create a list of bad players
# Bad represents bad_players
bads = [] # Empty list
# Add bad players
for _ in range(20): # we are making a set of 20 players
# We want the other player basically across from each other
# thats we copyied the code one on -y and one on +y (first
# player in the bottom, second player on top of Screen)
bad = Turtle()
bad.shape('circle')
bad.speed('fastest')
bad.color('yellow')
bad.penup()
bad.goto(100, 250) # y is positive in the up direction; negative in the down direction
bad.velocity = randint(5, 8)
bads.append(bad)
# Keyboard Binding
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen() # Basically saying listen for keyboard input
# Main game loop
# While something is true it will repeat
while True:
# Move player
x = player.xcor()
if player.direction == 'left':
x -= 3
elif player.direction == 'right':
x += 3
player.setx(x)
# Move Good Player
for good in goods:
y = good.ycor() - good.velocity # We want the ball to be falling at a smooth speed
good.sety(y)
if y < -300:
# Check if it's off the Screen
x = randint(-380, 380)
y = randint(300, 400)
good.goto(x, y)
elif good.distance(player) < 20:
# Check for collision with player
x = randint(-380, 380)
y = randint(300, 400)
good.goto(x, y)
# Move bad Player
for bad in bads:
y = bad.ycor() - bad.velocity # We want the ball to be falling at a slow speed
bad.sety(y)
if y < -300:
# Check if it's off the Screen
x = randint(-380, 380)
y = randint(300, 400)
bad.goto(x, y)
elif bad.distance(player) < 20:
# Check for collision with player
x = randint(-380, 380)
y = randint(300, 400)
bad.goto(x, y)
# Update screen
screen.update()
screen.mainloop()
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
I have found a "flappy game" project and I am modifying it to my liking.
I would like to know how I can control the definition "tap" with the keyboard and not with the mouse (I have tried the online code "onkey" and it did not work) and I would like to know if I can add a score.
Next I attach the code that I have in possession at the moment and I would appreciate some feedback.
from random import *
from turtle import *
from freegames import vector
bird = vector(0, 0)
balls = []
def tap(x, y):
"Move bird up in response to screen tap."
up = vector(0, 30)
bird.move(up)
def inside(point):
"Return True if point on screen."
return -200 < point.x < 200 and -200 < point.y < 200
def draw(alive):
"Draw screen objects."
clear()
goto(bird.x, bird.y)
if alive:
dot(10, 'green')
else:
dot(10, 'red')
for ball in balls:
goto(ball.x, ball.y)
dot(20, 'black')
update()
def move():
"Update object positions."
bird.y -= 5
for ball in balls:
ball.x -= 3
if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
balls.append(ball)
while len(balls) > 0 and not inside(balls[0]):
balls.pop(0)
if not inside(bird):
draw(False)
return
for ball in balls:
if abs(ball - bird) < 15:
draw(False)
return
draw(True)
ontimer(move, 50)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()
I've tried all kinds of functions and none has worked.
I would like to know how I can control the definition "tap" with the
keyboard and not with the mouse
That should be as simple as replacing:
onscreenclick(tap)
with
onkey(tap, "Up")
listen()
and dropping the x and y arguments to tap(). I've reworked your code below to make this change as well as eliminate:
from freegames import vector
and make it run just with what's available in turtle. I also changed the logic of keeping vectors and having the default turtle draw dots in their locations to instead making the balls and bird all turtles and just moving them as needed. Since turtles aren't garbage collected normally, I keep a list of balls that have gone off screen to reuse again:
from random import randrange
from turtle import Turtle, Screen
BIRD_RADIUS = 10
BALL_RADIUS = 20
CURSOR_SIZE = 20
WINDOW_WIDTH, WINDOW_HEIGHT = 420, 420
GALLERY_WIDTH, GALLERY_HEIGHT = WINDOW_WIDTH - BALL_RADIUS, WINDOW_HEIGHT - BIRD_RADIUS
def click():
"Move bird up in response to screen key click."
bird.forward(min(BIRD_RADIUS * 3, WINDOW_HEIGHT/2 - bird.ycor())) # flying higher
def is_ball_inside(turtle):
"Return True if point on screen."
x = turtle.xcor()
return -GALLERY_WIDTH/2 < x
def is_bird_inside(turtle):
"Return True if point on screen."
y = turtle.ycor()
return -GALLERY_HEIGHT/2 < y < GALLERY_HEIGHT/2
def draw(is_alive):
"Draw screen objects."
if not is_alive:
bird.color('red')
screen.update()
def move():
"Update object positions."
if not is_bird_inside(bird):
draw(False) # flew or fell out of gallery
return
bird.backward(BIRD_RADIUS/2) # falling to earth
for ball in balls:
ball.forward(3)
for ball in balls:
if ball.distance(bird) < (BIRD_RADIUS + BALL_RADIUS) / 2:
draw(False)
return
while balls and not is_ball_inside(balls[0]):
ball = balls.pop(0)
ball.hideturtle()
spare_balls.append(ball) # reduce, reuse, recycle
if randrange(10) == 0:
ball = spare_balls.pop() if spare_balls else Turtle("circle", visible=False)
ball.shapesize(BALL_RADIUS / CURSOR_SIZE)
ball.setheading(180)
ball.penup()
ball.goto(GALLERY_WIDTH/2, randrange(BALL_RADIUS - GALLERY_HEIGHT/2, GALLERY_HEIGHT/2 - BALL_RADIUS))
ball.showturtle()
balls.append(ball)
draw(True)
screen.ontimer(move, 50)
screen = Screen()
screen.setup(WINDOW_WIDTH, WINDOW_HEIGHT + 10) # little bit added for title bar
bird = Turtle("circle", visible=False)
bird.shapesize(BIRD_RADIUS / CURSOR_SIZE)
bird.color("green")
bird.setheading(90)
bird.penup()
bird.showturtle()
balls = []
spare_balls = []
screen.tracer(False)
screen.onkey(click, "Up")
screen.listen()
move()
screen.mainloop()
To make the turtle window the keyboard listener, you need to touch it with the mouse, to make it active, before hitting the up arrow key.
Before adding the current score to the window, you need to define how one scores. (Is it the number of ball successfully dodged?) Here I would use an additional, invisible turtle stationed in a fixed position that just does undo() and write() to update the scrore.
I wanted to make a snake game in turtle but I can't seem to get the tail segments to follow the leader. As if to say I can't get the first body part to follow the head, and then the second body part to follow the first body, etc.
I tried using what maths I have but I can't seem to get it to calculate where the head just was or where the body in front of it just was.
here is my code:
#libraries
import turtle
import random
import math
#screen
the_screen = turtle.Screen()
the_screen.bgcolor("lightgreen")
the_screen.title("Catapillar")
#border
border_writer = turtle.Turtle()
border_writer.speed(0)
border_writer.color("green")
border_writer.penup()
border_writer.setposition(-275, -275)
border_writer.pendown()
border_writer.pensize(7)
for side in range(4):
border_writer.fd(550)
border_writer.lt(90)
border_writer.hideturtle()
#player
player = turtle.Turtle()
player.color("yellow")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(0,0)
player.setheading(0)
playerspeed = 2
#fruit
fruit = 1
fruit = turtle.Turtle()
fruit.color("red")
fruit.shape("circle")
fruit.penup()
fruit.speed(0)
fruit.shapesize(0.6, 0.6)
x = random.randint(-200, 200)
y = random.randint(100, 250)
fruit.setposition(x, y)
#moving and collision checker
def turnleft():
player.left(24.5)
def turnright():
player.right(24.5)
def increasespeed():
global playerspeed
playerspeed += 1
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(), 2) + math.pow(t1.ycor()-t2.ycor(), 2))
if distance < 24:
return True
else:
return False
#making the tail(s) and hiding them
tail1 = turtle.Turtle()
tail1.hideturtle()
tail1.color("yellow")
tail1.shape("circle")
tail1.penup()
tail1.speed(0)
tail1.setposition(+700,700)
tail1.shapesize(0.6, 0.6)
tail1state = 'off'
#key presses
turtle.listen()
turtle.onkeypress(turnleft, "Left")
turtle.onkeypress(turnright, "Right")
turtle.onkeypress(increasespeed, "Up")
#main loop player always moves forward, out of bound set, reset fruit
#randomly when collided, create tail1...
while True:
player.forward(playerspeed)
#gameovers'
if (player.xcor() > 275) or (player.xcor() < -275):
playerspeed += 7
print("GAME OVER")
if (player.ycor() > 275) or (player.ycor() < -275):
playerspeed += 7
print("GAME OVER")
#collision check between fruit and head
if isCollision(player, fruit):
#resets the fruit, moves it randomly
fruit.hideturtle()
if tail1state == 'off':
uuu = player.xcor()
vvv = player.ycor()
tail1.setposition(uuu,vvv)
tail1.showturtle()
tail1state = 'on'
#reset the fruit
x = random.randint(-200, 200)
y = random.randint(-100, 250)
fruit.setposition(x, y)
fruit.showturtle()
#playerspeed +=1
If you have any idea on how you think I should approach it, please let me know what you think.
Thank you.
Since this comes up over and over (but effort to effect it is rarely shown) here's my minimal, generic, slithering around a screen effect that you should be able to adapt for your own purposes:
from turtle import Turtle, Screen
SNAKE_LENGTH = 10
SNAKE_SIZE = 15
WIDTH, HEIGHT = 375, 375
CURSOR_SIZE = 20
def slither():
segment = snake[-1].clone() if len(snake) < SNAKE_LENGTH else snake.pop(0)
screen.tracer(False) # segment.hideturtle()
segment.setposition(snake[-1].position())
segment.setheading(snake[-1].heading())
segment.forward(SNAKE_SIZE)
while not -WIDTH/2 < segment.xcor() < WIDTH/2 or not -HEIGHT/2 < segment.ycor() < HEIGHT/2:
segment.undo()
segment.right(95)
segment.forward(SNAKE_SIZE)
screen.tracer(True) # segment.showturtle()
snake.append(segment)
screen.ontimer(slither, 100)
boundary = Turtle(shape='square', visible=False)
boundary.shapesize(HEIGHT / CURSOR_SIZE, WIDTH / CURSOR_SIZE)
boundary.fillcolor("white")
boundary.stamp()
head = Turtle("circle")
head.shapesize(SNAKE_SIZE / CURSOR_SIZE)
head.penup()
snake = [head]
screen = Screen()
slither()
screen.exitonclick()