Making snake in Python, can't get bodies to follow head etc - python

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()

Related

I am developing snake game, I write few code line , but speed of snake is to fast, I want to slow down the speed to normal, How to do that? In python

In python
import time
from turtle import Turtle, Screen
# screen height and width
height = 600
width = 600
# snake initial positinn
x_coordinate = 0
y_coordinate = 0
game_on = True
screen = Screen()
screen.bgcolor("black")
screen.setup(height=height, width=width)
screen.title("Snake Game")
full_snake = []
screen.tracer(0)
# create a snake 3X3
for _ in range(3):
snake = Turtle("square")
snake.color("white")
snake.penup()
snake.goto(x_coordinate, y_coordinate)
x_coordinate -= 20
full_snake.append(snake)
snake_head = full_snake[0]
# function to operate the snake
def up():
if snake_head.heading() != 270:
snake_head.setheading(90)
def down():
if snake_head.heading() != 90:
snake_head.setheading(270)
def right():
if snake_head.heading() != 180:
snake_head.setheading(0)
def left():
if snake_head.heading() != 0:
snake_head.setheading(180)
screen.listen()
screen.onkey(up, "w")
screen.onkey(down, "s")
screen.onkey(right, "d")
screen.onkey(left, "a")
# function for snakes part to attached
def attached():
for i in range(len(full_snake) - 1, 0, -1):
new_x = full_snake[i - 1].xcor()
new_y = full_snake[i - 1].ycor()
full_snake[i].goto(new_x, new_y)
snake_head.fd(20)
# to move the snake
while game_on:
snake_head.speed(1)
screen.update()
time.sleep(0.1)
for snake in full_snake:
attached()
screen.exitonclick()
in this code snake speed is fast, I want to slow down to normal where I can placed speed() method or any method
Turtle module from python
expected output : speed of snake to be normal without detaching other two blocks
.................................................................................................................................................................................................................................................................................................................................
You can try the ontimer() method instead to control the snake movement. I modified your code a bit. You can check if the snake hits the wall too and set game_on to false in the move_snake function.
import time
from turtle import Turtle, Screen
# screen height and width
height = 600
width = 600
# snake initial position
x_coordinate = 0
y_coordinate = 0
game_on = True
screen = Screen()
screen.bgcolor("black")
screen.setup(height=height, width=width)
screen.title("Snake Game")
full_snake = []
screen.tracer(0)
# create a snake 3X3
for _ in range(3):
snake = Turtle("square")
snake.color("white")
snake.penup()
snake.goto(x_coordinate, y_coordinate)
x_coordinate -= 20
full_snake.append(snake)
snake_head = full_snake[0]
# function to operate the snake
def up():
if snake_head.heading() != 270:
snake_head.setheading(90)
def down():
if snake_head.heading() != 90:
snake_head.setheading(270)
def right():
if snake_head.heading() != 180:
snake_head.setheading(0)
def left():
if snake_head.heading() != 0:
snake_head.setheading(180)
screen.listen()
screen.onkey(up, "w")
screen.onkey(down, "s")
screen.onkey(right, "d")
screen.onkey(left, "a")
# function for snake parts to attached
def attached():
for i in range(len(full_snake) - 1, 0, -1):
new_x = full_snake[i - 1].xcor()
new_y = full_snake[i - 1].ycor()
full_snake[i].goto(new_x, new_y)
snake_head.fd(20)
# New function to move the snake
def move_snake():
attached()
screen.update()
# updated the height and width variables to fit the actual screen size (useful when screen is resized)
height = screen.window_height()
width = screen.window_width()
# check if the snake head hits the wall (19 or 20 pixels away looks fine but can be ajusted) then set game_on to false and stop the function execution
if snake_head.xcor() >= width/2 - 20 or snake_head.xcor() <= -width/2 + 19 or snake_head.ycor() >= height/2 - 19 or snake_head.ycor() <= -height/2 + 20:
game_on = False
return
# timer to recursively call the move_snake function every 500 milliseconds
screen.ontimer(move_snake, 500) # adapt to your desired speed (the lower the faster)
# start moving the snake
move_snake()
screen.exitonclick()

Turtle window hanging

When I try to run my code, my python turtle window just hangs; I can't move also. I've tried removing the win_pen and it worked, but I don't know what inside the win_pen is making it hang.
It also gives me the spinning wheel since I am on Mac, and I am not sure if that is the problem for this. I'm on Big Sur 11.1 by the way.
edit: The indents are right on my screen, just a copy and paste problem
Code:
import turtle
import os
import math
import random
from random import randint
score = 0
# Set Up Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("test")
# Draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.hideturtle()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
# Draw Winning Area
win_pen = turtle.Turtle()
win_pen.hideturtle()
win_pen.shape("square")
win_pen.penup()
win_pen.setposition(0,267.7)
win_pen.shapesize(3,29.8)
# Show Score on Screen
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 303)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Ubuntu", 14, "normal"))
score_pen.hideturtle()
# Set up Player 1
player1 = turtle.Turtle()
player1.color("blue")
player1.shape("triangle")
player1.penup()
player1.speed(0)
player1.setposition(0, -250)
player1.setheading(90)
player1speed = 15
# Set Up Enemies
en = 8
enemies = []
for i in range(en):
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("square")
enemy.penup()
enemy.speed(0)
enemy.goto(randint(-280,280),randint(-280,280))
enemy.shapesize(2,2)
enemyspeed = 2
# Draw Winning Area
win_pen = turtle.Turtle()
win_pen.hideturtle()
win_pen.shape("square")
win_pen.penup()
win_pen.setposition(0,267.7)
win_pen.shapesize(3,29.8)
#Define bullet state
#ready - ready to fire
#fire - bullet is firing
bulletstate = "ready"
def left():
x = player1.xcor()
player1.setheading(180)
player1.forward(player1speed)
if x < -280:
x = - 280
player1.setx(x)
def right():
x = player1.xcor()
player1.setheading(0)
player1.forward(player1speed)
if x > 280:
x = 280
player1.setx(x)
def up():
y = player1.ycor()
player1.setheading(90)
player1.forward(player1speed)
if y > 280:
y = 280
player1.sety(y)
def down():
y = player1.ycor()
player1.setheading(270)
player1.forward(player1speed)
if y < -280:
y = 280
player1.sety(y)
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 15:
return True
else:
return False
turtle.listen()
turtle.onkey(left, "a")
turtle.onkey(right, "d")
turtle.onkey(up, "w")
turtle.onkey(down, "s")
# Main Game Loop
while True:
if isCollision(player1, win_pen):
player1.setposition(0, -250)
player1.setheading(90)
There are several problems with your code: don't use while True: in an event-driven world like turtle -- let the event handler do its job; your collision logic is incorrect as it measures from the center of the turtles whereas we're really only concerned with the y position of the two turtles; you seem to be resetting the player in the wrong direction; you implement the winning area twice.
I've rewritten, and simplified, your code below incorporating the above changes and some other tweaks:
from turtle import Screen, Turtle
from random import randint
ENEMY_COUNT = 8
PLAYER_SPEED = 15
def left():
player.setheading(180)
player.setx(max(-280, player.xcor() - PLAYER_SPEED))
check_collision(player, win_pen)
def right():
player.setheading(0)
player.setx(min(280, player.xcor() + PLAYER_SPEED))
check_collision(player, win_pen)
def up():
player.setheading(90)
player.sety(min(280, player.ycor() + PLAYER_SPEED))
check_collision(player, win_pen)
def down():
player.setheading(270)
player.sety(max(-280, player.ycor() - PLAYER_SPEED))
check_collision(player, win_pen)
def check_collision(player, win_pen):
if abs(player.ycor() - win_pen.ycor()) < 15:
player.sety(-250)
player.setheading(90)
score = 0
# Set Up Screen
screen = Screen()
screen.bgcolor('black')
# Draw border
border_pen = Turtle()
border_pen.hideturtle()
border_pen.pensize(3)
border_pen.color('white')
border_pen.speed('fastest')
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
for _ in range(4):
border_pen.forward(600)
border_pen.left(90)
# Draw Winning Area
win_pen = Turtle()
win_pen.shape('square')
win_pen.shapesize(3, 29.8)
win_pen.color('gray')
win_pen.penup()
win_pen.sety(267.7)
# Show Score on Screen
score_pen = Turtle()
score_pen.hideturtle()
score_pen.color('white')
score_pen.penup()
score_pen.setposition(-290, 303)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align='left', font=('Ubuntu', 14, 'normal'))
# Set up Player
player = Turtle()
player.shape('triangle')
player.color('blue')
player.speed('fastest')
player.setheading(90)
player.penup()
player.setx(-250)
# Set Up Enemies
enemies = []
for _ in range(ENEMY_COUNT):
enemy = Turtle()
enemy.color('red')
enemy.shape('square')
enemy.shapesize(2)
enemy.speed('fastest')
enemy.penup()
enemy.goto(randint(-280, 280), randint(-280, 280))
enemies.append(enemy)
screen.onkey(left, 'a')
screen.onkey(right, 'd')
screen.onkey(up, 'w')
screen.onkey(down, 's')
screen.listen()
screen.mainloop()

How to prevent Python Turtle from going through lines it has drawn?

I'm making a game using Turtle in Python 3.
My main problem is that the turtle can move through the "drawn" lines in the game. It's basically a randomized "flappy-bird" game, different each time you run the program.
Is it possible to prevent the Turtle from going through lines it has drawn?
The program creates both walls and holes the player should be able to get through, like flappy bird where it's a pipe-hole-pipe with different lengths on the pipes.
And if I run print(hole) at the end of the program it returns None. Why is this?
Here is my program:
import turtle
import random
GameOver=False
import math
import time
board = turtle.Screen()
board.screensize(50.50)
board.bgcolor("black")
board.title("Labyrinten")
Hast_på_ritande_av_bana= 0
TURTLE_SIZE = 20
playerspeed = 50
n=1 #variabeler som gör att den hoppar ett steg åt höger när den gör raderna t.ex. ((930/8)*n)
b=2 #
global player
#SÄTTER UPP SKÄRM
border = turtle.Turtle()
border.speed(Hast_på_ritande_av_bana)
border.hideturtle()
border.color("white")
border.shape("triangle")
border.penup()
border.goto(TURTLE_SIZE/2 - board.window_width()/2, board.window_height()/2 - TURTLE_SIZE/2)
border.pendown()
border.showturtle()
border.rt(90)
border.fd(780)
border.penup()
#ritar banan
for rader in range(4): #creating the maze
border.lt(90)
border.fd(930/8)
border.pendown()
border.lt(90)
wall_ett = border.fd(random.randint(50,630)) #lower wall on row 1
border.penup()
hole=border.fd(random.randint(30,70)) #hole on row 1
border.pendown()
wall_ett_ett = border.goto (TURTLE_SIZE/2 - board.window_width()/2 + (930/8*n), board.window_height()/2 - TURTLE_SIZE/2) #higher wall on row 1
border.rt(90)
border.fd(930/8)
border.rt(90)
wall_två_ett = border.fd(random.randint(50, 630)) #lower wall on row 2
border.penup()
hole2 = border.fd(random.randint(30, 70)) #hole on row 2
border.pendown()
wall_två_två = border.goto(TURTLE_SIZE/2 - board.window_width()/2 + (930/8*b), + TURTLE_SIZE/2 - board.window_height()/2 ) # higher wall on row 2
n = n + 2
b = b + 2
border.goto(TURTLE_SIZE/2 - board.window_width()/2 , TURTLE_SIZE/2 - board.window_height()/2 )
border.goto(TURTLE_SIZE/2 - board.window_width()/2, board.window_height()/2 - TURTLE_SIZE/2)
border.penup()
border.lt(90)
border.fd(930/8)
border.pendown()
border.goto(-TURTLE_SIZE + board.window_width()/2, board.window_height()/2 - TURTLE_SIZE/2)
border.hideturtle()
player=turtle.Turtle()
player.color("green")
player.shape("turtle")
player.hideturtle()
player.penup()
player.goto(TURTLE_SIZE/2 - board.window_width()/2, board.window_height()/2 - TURTLE_SIZE/2)
player.rt(90)
player.fd(30)
player.lt(90)
player.fd((930/8)/2)
player.rt(90)
player.showturtle()
coordinates = player.pos()
#Skapa spelaren (som går igenom banan)
def spawna_spelare():
spawn = turtle.Turtle()
spawn.color("green")
spawn.shape("turtle")
spawn.hideturtle()
spawn.penup()
spawn.goto(TURTLE_SIZE/2 - board.window_width()/2, board.window_height()/2 - TURTLE_SIZE/2)
spawn.rt(90)
spawn.fd(30)
spawn.lt(90)
spawn.fd((930/8)*(random.randint(1,8)))
spawn.rt(90)
spawn.showturtle()
#Gå med spelaren
def move_left():
x = player.xcor()
x -= playerspeed
if x < -460:
x = -460
player.setx(x)
def move_right():
x = player.xcor()
x += playerspeed
if x > 450:
x = 450
player.setx(x)
if x.distance(wall_ett) >20: #or wall_ett_ett or wall_två_ett or wall_två_två) == 1: #
player.shape("triangle")
def move_down():
y = player.ycor()
y -= playerspeed
if y < -375:
y = -375
player.sety(y)
def move_up():
y = player.ycor()
y += playerspeed
if y > 380:
y = 380
player.sety(y)
turtle.listen()
turtle.onkey(spawna_spelare, "space")
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_down, "Down")
turtle.onkey(move_up, "Up")
wall_ett = border.xcor()
wall_två_ett=border.xcor()
print(wall_ett)
print(wall_ett)
print(hole)
board.mainloop()
So you need to draw the walls in a way you can check afterwards if the move the player requested is crossing any wall (or border).
here is a suggestion:
SCREEN_WIDTH = 800
HOLE_HEIGHT = 50
SCREEN_HEIGHT = 600
NUM_WALLS = 8
board = turtle.Screen()
board.setup(SCREEN_WIDTH+10, SCREEN_HEIGHT+10)
board.screensize(SCREEN_WIDTH, SCREEN_HEIGHT)
board.setworldcoordinates(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
border = turtle.Turtle()
border.speed(10) # draw walls as fast as possible
border.color('white')
border.hideturtle()
# list of the drawn walls, each wall is represented by a tuple:
# (wall_x, wall_hole_lower_y, wall_hole_upper_y)
walls = []
for wall_ix in range(NUM_WALLS):
# compute coordinates of wall and store them
wall_x = int((1+wall_ix) * SCREEN_WIDTH / (1+NUM_WALLS))
wall_ybottom = random.randint(0, SCREEN_HEIGHT - HOLE_HEIGHT)
wall_ytop = wall_ybottom + HOLE_HEIGHT
walls.append((wall_x, wall_ytop, wall_ybottom))
# draw wall
border.penup()
border.goto(wall_x, 0)
border.pendown()
border.goto(wall_x, wall_ybottom)
border.penup()
border.goto(wall_x, wall_ytop)
border.pendown()
border.goto(wall_x, SCREEN_HEIGHT)
def move_right():
old_x = player.xcor()
new_x = old_x + playerspeed
y = player.ycor()
for wall_x, wall_ytop, wall_ybottom in walls:
if old_x <= wall_x <= new_x:
# player is possibly moving across the wall, check that y is valid
if wall_ybottom < y < wall_ytop:
# OK ! player moves through the hole
player.setx(new_x)
else:
# invalid, player is crossing a wall line
# resetting to old position, but you might want to stop the game
player.setx(old_x)

How to fix bug where my enemies don't disappear?

I want to make a Space Invaders game but my enemies don't disappear if they get hit. Does anyone know how to fix it?
I already tried a for loop (as you will see) but it doesnt work:
import turtle as tr
wn = tr.Screen()
wn.tracer(0)
bullet = tr.Turtle()
player = tr.Turtle()
enimis = []
y = -250
def shoot():
player.direction = "up"
wn.onkey(shoot,"space")
while True:
if len(enimis) == 0:
for u in range(-210,210,60):
for o in range(100,260,60):
enimi = tr.Turtle()
enimi.setpos(u,o)
enimis.append(enimi)
if player.direction == "up":
bullet.penup()
x = player.xcor()
bullet.setpos(x,y)
bullet.pendown()
for p in range(550):
bullet.setpos(x,y+p)
for k in enimis:
if bullet.distance(k) < 25:
score += 10
if score > highscore:
highscored = True
else:
highscored = False
del k
hit = True
break
else:
hit = False
wn.update()
There aren't any error messages, the enemies just don't disappear.
I don't see why you're stuck on making dead enemies disappear when the code doesn't run at all due to this error:
if player.direction == "up":
AttributeError: 'Turtle' object has no attribute 'direction'
Nor could you hit an enemy since your player and enemies can't move and the player isn't pointing at an enemy to start with. Too much magical thinking and not enough code.
To answer your question, this can't work:
for k in enimis:
if bullet.distance(k) < 25:
# ...
del k
# ...
break
It either needs to be:
for k in enimis:
if bullet.distance(k) < 25:
# ...
enimis.remove(k) # remove by value
# ...
break
or:
for k in range(len(enimis)):
if bullet.distance(enimis[k]) < 25:
# ...
del enimis[k] # remove by index
# ...
break
Below is my complete rewrite of your code to get it to basically play: player can move left and right; bullets fire, hit enemies, score points, and enemies disappear; the score is shown on the screen; etc.
from turtle import Screen, Turtle
BASELINE = -250
FONT = ('Arial', 18, 'bold')
def left():
player.setx(player.xcor() - 5)
def right():
player.setx(player.xcor() + 5)
def shoot():
global firing
firing = True
firing = False
enemies = []
score = 0
bullet = Turtle('triangle')
bullet.hideturtle()
bullet.speed('fastest')
bullet.shapesize(0.5)
bullet.setheading(90)
bullet.penup()
player = Turtle('turtle')
player.hideturtle()
player.speed('fastest')
player.color('green')
player.setheading(90)
player.penup()
player.sety(BASELINE)
player.showturtle()
marker = Turtle()
marker.hideturtle()
marker.penup()
marker.goto(-300, 300)
marker.write("Score: {}".format(score), align='center', font=FONT)
def play():
global firing, score
if not enemies:
screen.tracer(False)
for x in range(-210, 210, 60):
for y in range(100, 260, 60):
enemy = Turtle('turtle')
enemy.color('red')
enemy.setheading(270)
enemy.penup()
enemy.setpos(x, y)
enemies.append(enemy)
screen.tracer(True)
if firing:
bullet.setx(player.xcor())
bullet.sety(BASELINE)
bullet.showturtle()
for p in range(0, 550, 5):
bullet.sety(BASELINE + p)
for enemy in enemies:
if bullet.distance(enemy) < 20:
score += 10
marker.undo()
marker.write("Score: {}".format(score), align='center', font=FONT)
enemy.clear()
enemy.hideturtle()
enemies.remove(enemy)
break
else: # no break
continue
break
bullet.clear()
bullet.hideturtle()
firing = False
screen.ontimer(play, 100)
screen = Screen()
screen.onkey(shoot, 'space')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
play()
screen.mainloop()
Still needed: moving enemies left, right and down; making bullet firing and player/enemy movement happen at the same time; add back highscore; etc.

Keyboard input and score. Python turtle

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.

Categories