Turtle Clear Screen - python

I'm not sure how to get rid of the black arrow, if you could help that would be great! Thanks, also if you have any other modifications to make the game better that would be awesome as well! Thanks again!
It says I need to write more detail, so I m just going to keep typing fora bit and hope that I have enough words to write. It should be good right around here.
import math
import random
score = 0
print ("\n" * 40)
print("Welcome Player, I Hope You Have What it Takes to be the Next WARLORD BOSS")
print("Enemies Killed:\n0")
#Title
t=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
t.penup()
t.setposition(-300,350)
t.write("Catch 40 turtles for a suprise ( ͡° ͜ʖ ͡°)", font=("Verdana", 18))
#Tip
text=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
turtle.clear()
t.penup()
t.setposition(-100, -350)
t.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))```
#Set up screen
wn = turtle.Screen()
wn.bgcolor("dim gray")
wn.title("EXEXEXEXEEXXEXEXE HACK COMMENCING␀␀␀␀␀")
#Draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.speed(10)
mypen.hideturtle()
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
for side in range(4):
mypen.color("crimson")
mypen.forward(300)
mypen.color("gold")
mypen.forward(300)
mypen.left(90)
mypen.hideturtle()
#Create player turtle
player = turtle.Turtle()
player.color("powder blue")
player.shape("arrow")
player.penup()
player.speed(0)
#Create goal
goal = turtle.Turtle()
goal.color("red")
goal.shape("turtle")
goal.penup()
goal.speed(0)
goal.setposition(-100, -100)
#Set speed
speed = 1
#Define functions
def turnleft():
player.left(30)
def turnright():
player.right(30)
def increasespeed():
global speed
speed +=0.5
def decreasespeed():
global speed
speed -= 1
#Set keyboard binding
turtle.listen()
turtle.onkey(turnleft, "Left")
turtle.onkey(turnright, "Right")
turtle.onkey(increasespeed, "Up")
turtle.onkey(decreasespeed, "Down")
while True:
player.forward(speed)
#Boundary check
if player.xcor() > 300 or player.xcor() < -300:
print("I Knew you could never be a WARLORD... Try Again")
quit()
if player.ycor() > 300 or player.ycor() < -300:
print("I Knew you could never be a WARLORD... Try Again")
quit()
#Collision checking
d= math.sqrt(math.pow(player.xcor()-goal.xcor(),2) + math.pow(player.ycor()-goal.ycor(),2))
if d < 20 :
goal.setposition(random.randint(-300,300), random.randint(-300, 300))
score = score + 1
print ("\n" * 40)
print("Wow, You Actually got one!")
print("I think you Might Have What it Takes to be the Next WARLORD BOSS")
print("Enemies Killed")
print (score)

This code is your problem:
text=turtle.Pen()
t.pencolor("magenta")
t.hideturtle()
turtle.clear()
t.penup()
t.setposition(-100, -350)
t.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))
You copied and pasted but forgot to update t. to instead be text. Also, turtle.clear() doesn't make sense as that refers to a different turtle altogether:
text = turtle.Pen()
text.hideturtle()
text.pencolor("magenta")
text.penup()
text.setposition(-100, -350)
text.write("TOUCH THE EDGES, I DARE YOU", font=("Verdana", 18))

Related

Python Turtle race game. Ending game function does not seem to work

I have got a problem with how to end my turtle python game. The code seems to function if I place the turtles at the starting/ending point from the beginning of the code, but it does not register when the turtle reaches the endpoint in gameplay. From what I know I think my maths for the end function is right. I am new and appreciate the help. I am currently offline though.
CODE:
import time
import turtle
from turtle import *
wn = turtle.Screen()
name=textinput("Question", "what is your name")
#display
pencolor("white")
penup()
goto(0,170)
write("hello " +name,align='center',font=('Comic Sans', 20))
#wn = turtle.screen() if the code doesn't work
#diffrent turtles here
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t3 = turtle.Turtle()
#starting psoition
turtle.penup()
t1.penup()
turtle.goto(-1, -230)
t1.goto(-1, -170)
#starting line postion
def f():
fd(10)
def b():
bk(10)
def l():
left(10)
def r():
right(10)
#testing
def fo():
t1.fd(10)
def ba():
t1.bk(10)
def le():
t1.left(10)
def ri():
t1.right(10)
#turtle coordinates
first=turtle.ycor()
second=turtle.xcor()
third=t1.ycor()
fourth=t1.xcor()
#when to end the game
if (turtle.ycor()>= (-160)) and (turtle.ycor()<= (-240)):
if (turtle.xcor()>= (0)) and (turtle.xcor()<= (11)):
print("Finally working")
#replaced with write who the winner is later
if (t1.ycor()>= (-160)) and (t1.ycor()<= (-240)):
if (t1.xcor()>= (0)) and (t1.xcor()<= (11)):
print("Finally")
# onkey creates the key board = turtle.onkey("function, key") You have to keep pressing keys for it to move
turtle.onkey(f, "w")
turtle.onkey(b, "s")
turtle.onkey(l, "a")
turtle.onkey(r, "d")
wn.onkey(fo, "Up")
wn.onkey(ba, "Down")
wn.onkey(le, "Left")
wn.onkey(ri, "Right")
listen()
#WINDOW SETUP
window = Screen()
window.setup(800, 800)
window.title("Turtle game")
turtle.bgcolor("forestgreen")
t3.color("black")
t3.speed(0)
t3.penup()
t3.setpos(-140, 250)
t3.write("THE TURTLE RACE", font=("Comic Sans", 30, "bold"))
t3.penup()
#turtle ask name
#add images here
#turtle controls
# def creates a function. : means opperation f means move turtle foward. fd push turtle forward
# onkey creates the key board = turtle.onkey("function, key") You have to keep pressing keys for it to move
t2.speed(0)
t2.color("grey")
t2.pensize(100)
t2.penup()
t2.goto(-200, -200)
t2.left(90)
t2.pendown()
t2.forward(300)
t2.right(90)
t2.forward(500)
t2.right(90)
t2.forward(300)
t2.right(90)
t2.forward(500)
turtle.penup()
Firstly, your maths is not quite right - a coordinate can never be both <= -240 and >= -160. It should be t.ycor() >= -240 and t.ycor() <= -160, or more briefly, -240 <= t.ycor() <= -160.
Secondly, the condition as it stands is only checked once, when the code is first run. Instead, you need to get the program to check it regularly. You can do this by adding a general onkeypress event handler which is checked every time any key is pressed.
def check_status():
for player, t in enumerate([turtle, t1]):
if 0 <= t.xcor() <= 11 and -240 <= t.ycor() <= -160:
print(f"Player {player} is at the endpoint")
...
wn.onkeypress(check_status)
listen()

After a few seconds, one turtle stops and the other goes faster

After weeks of trying, I have not come up with a solution to this issue, in which one turtle comes to a complete stop and the other goes 2x - 3x faster. How can I fix this? You must move them both around for a little bit to encounter the issue. Also this is on the site: repl.it
I have tried moving the wn.listen() command but that only switched which turtle stopped and which one didn't. I have unsuccessfully tried to switch the forward() command to goto() and I have tried to use direction specific movement (also unsuccessfully):
import turtle
import sys
player1 = turtle.Turtle()
player1.up()
player1.goto(0,350)
player1.right(90)
player1.down()
player2 = turtle.Turtle()
wn = turtle.Screen()
#preGame setup
player2.up()
player2.goto(0,-350)
player2.left(90)
player2.down()
player2.color("blue")
player1.color("red")
#main game loop
player1.speed(0)
player2.speed(0)
k = 0
def kr():
player1.left(90)
def kl():
player1.right(90)
wn.onkey(kr, "d")
wn.onkey(kl, "a")
def k1():
player2.right(90)
def k2():
player2.left(90)
wn.onkey(k1, "k")
wn.onkey(k2, "l")
wn.listen()
while True:
player1.forward(1)
player2.forward(1)
while player1.xcor() < (-350) or player1.xcor() > (350) or player1.ycor() > (350) or player1.ycor() < (-350):
player1.back(30)
while player2.xcor() < (-350) or player2.xcor() > (350) or player2.ycor() > (350) or player2.ycor() < (-350):
player2.back(30)
if player1.pos() == player2.pos():
print ("DONT CRASH INTO THE OTHER PLAYER")
sys.exit()
I expected them both to continue moving indefinitely, but one always stops, and the other is going 2x the speed.
Move the keylisteners outside your loop - having them inside the while loop will reattach them and redefine the functions all the time and confuse turtle.
You need to set them up once not every few milliseconds:
import turtle
player1 = turtle.Turtle()
player2 = turtle.Turtle()
player1.goto(350, 0)
player2.goto(-350, 0)
player1.right(180)
wn = turtle.Screen()
def kl():
player1.left(90)
def kr():
player1.right(90)
def k1():
player2.right(90)
def k2():
player2.left(90)
wn.onkey(kl, "d") # changed to lowercase
wn.onkey(kr, "a")
wn.onkey(k1, "j") # changed to other letters
wn.onkey(k2, "l")
wn.listen()
while True: # not changing k so just use while True
player1.forward(1) # changed speed
player2.forward(1)
Your nested while loop structure is working against you and isn't valid for an event-driven environment like turtle. Here's a rework of your program to fix this issue and clean up the code:
from turtle import Screen, Turtle
import sys
# preGame setup
player1 = Turtle()
player1.hideturtle()
player1.up()
player1.goto(0, 350)
player1.down()
player1.right(90)
player1.color('red')
player1.speed('fastest')
player1.showturtle()
def r1():
player1.left(90)
def l1():
player1.right(90)
player2 = Turtle()
player2.hideturtle()
player2.up()
player2.goto(0, -350)
player2.down()
player2.left(90)
player2.color('blue')
player2.speed('fastest')
player2.showturtle()
def r2():
player2.right(90)
def l2():
player2.left(90)
# main game loop
def move():
player1.forward(5)
if not (-350 < player1.xcor() < 350 and -350 < player1.ycor() < 350):
player1.backward(30)
player2.forward(5)
if not (-350 < player2.xcor() < 350 and -350 < player2.ycor() < 350):
player2.backward(30)
if player1.distance(player2) < 5:
print("DON'T CRASH INTO THE OTHER PLAYER!")
sys.exit()
screen.ontimer(move, 100)
screen = Screen()
screen.onkey(r1, 'd')
screen.onkey(l1, 'a')
screen.onkey(r2, 'k')
screen.onkey(l2, 'l')
screen.listen()
move()
screen.mainloop()
See if this behaves more like you expect/desire.

Troubles implementing a video game using Python turtle graphics

Basically what I'm trying to do is create a two player game using Python's turtle module. There are two turtles at the bottom which are the players and two circles at the top which act as checkpoints. One turtle is supposed to go back and forth between the two checkpoints—this turtle is the target. The bottom turtles shoot circles at the target.
My issues:
The target turtle moves way too rapidly.
The bullets for the turtles at the bottom spawn from the middle of the screen.
Note: There may be some parts of the code which are confusing and/or not needed.
Here's the code:
from turtle import*
import math
def k1():#Enemy Key Commands
enemy.left(90)
enemy.forward(10)
enemy.right(90)
def k2():
enemy.left(90)
enemy.backward(10)
enemy.right(90)
def k3():#Yertle Key Commands
yertle.left(90)
yertle.forward(10)
yertle.right(90)
def k4():
yertle.left(90)
yertle.backward(10)
yertle.right(90)
def k5():
a=bullet_red()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def k6():
a=bullet_blue()
a.speed(10)
a.forward(400)
collision= math.sqrt(math.pow(a.xcor()-yertle.xcor(),2)+math.pow(a.ycor()-yertle.ycor(),2))
if(collision<10):
text=enemy.write("Game Over", align="center" , font=("Arial", 16, "normal"))
a.hideturtle()
def collision(a, b):
collision= math.sqrt(math.pow(a.xcor()-b.xcor(),2)+math.pow(a.ycor()-b.ycor(),2))
if(collision<5):
print("Bottom Player Wins")
print("Game Over")
def bullet_red():
bullet=Turtle("circle")#Description For Bullet
bullet.color("red")
bullet.penup()
bullet.goto(enemy.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
def bullet_blue():
bullet=Turtle("circle")#Description For Bullet
bullet.color("blue")
bullet.penup()
bullet.goto(yertle.pos())
bullet.setheading(180)
bullet.right(90)
return bullet
ops = Screen()
ops.setup(500, 500)
ops.onkey(k1, "a")#Enemy
ops.onkey(k2, "d")#Enemy
ops.onkey(k3, "Left")#Yertle
ops.onkey(k4, "Right")#Yertle
ops.onkey(k5, "w")#Shoot(Enemy)
ops.onkey(k6, "Up")#Shoot(Enemy)
ops.listen()
checkpoint_1=Turtle(shape="circle")#Turtle Description for Checkpoint 1
checkpoint_1.color("red")
checkpoint_1.setheading(180)
checkpoint_1.right(90)
checkpoint_1.penup()
checkpoint_1.setx(-220)
checkpoint_1.sety(230)
checkpoint_1.speed(0)
#_____________________________
checkpoint_2=Turtle(shape="circle")#Turtle Description for Checkpoint 2
checkpoint_2.color("red")
checkpoint_2.setheading(180)
checkpoint_2.right(90)
checkpoint_2.penup()
checkpoint_2.setx(220)
checkpoint_2.sety(230)
checkpoint_2.speed(0)
#____________________________
runner=Turtle(shape="turtle")#Turtle Description for Checkpoint 2
runner.color("yellow")
while(runner!=collision):
runner.penup()
runner.goto(checkpoint_1.pos())
runner.goto(checkpoint_2.pos())
runner.speed(0)
#_____________________________
enemy=Turtle(shape="turtle")#Turtle Description for Player 1
enemy.color("red")
enemy.setheading(180)
enemy.right(90)
enemy.penup()
enemy.setx(-20)
enemy.sety(-200)
enemy.speed(0)
#_____________________________
yertle = Turtle(shape="turtle")#Turtle Description for Player 2
yertle.color("blue")
yertle.setheading(180)
yertle.right(90)
yertle.penup()
yertle.setx(20)
yertle.sety(-200)
yertle.speed(0)
#_____________________________
Below is my rework of your code to get it to just basically play the game -- it still needs work to become a finished program.
from turtle import Turtle, Screen
FONT = ("Arial", 32, "bold")
def k1(): # Enemy Key Commands
enemy.backward(10)
def k2():
enemy.forward(10)
def k3(): # Yertle Key Commands
yertle.backward(10)
def k4():
yertle.forward(10)
def k5(): # enemy shoot
bullet.color("red")
bullet.goto(enemy.position())
bullet.showturtle()
bullet.forward(430)
if bullet.distance(runner) < 10:
magic_marker.write("Game Over", align="center", font=FONT)
bullet.hideturtle()
def k6(): # yertle shoot
bullet.color("blue")
bullet.goto(yertle.position())
bullet.showturtle()
bullet.forward(430)
if bullet.distance(runner) < 10:
magic_marker.write("Game Over", align="center", font=FONT)
bullet.hideturtle()
def move_runner():
if runner.distance(checkpoint_1) < 5 or runner.distance(checkpoint_2) < 5:
runner.left(180)
runner.forward(2)
screen.ontimer(move_runner, 50)
screen = Screen()
screen.setup(500, 500)
bullet = Turtle("circle", visible=False) # Description For Bullet
bullet.speed('normal')
bullet.penup()
bullet.setheading(90)
checkpoint_1 = Turtle("circle", visible=False) # Turtle Description for Checkpoint 1
checkpoint_1.color("red")
checkpoint_1.penup()
checkpoint_1.goto(-220, 230)
checkpoint_2 = checkpoint_1.clone() # Turtle Description for Checkpoint 2
checkpoint_2.goto(220, 230)
runner = Turtle("turtle", visible=False)
runner.color("orange")
runner.speed('fastest')
runner.penup()
runner.sety(230)
yertle = Turtle(shape="turtle", visible=False) # Turtle Description for Player 1
yertle.tiltangle(90) # face one way but move another!
yertle.speed('fastest')
yertle.penup()
yertle.color("blue")
yertle.goto(20, -200)
enemy = yertle.clone() # Turtle Description for Player 2
enemy.color("red")
enemy.goto(-20, -200)
checkpoint_1.showturtle()
checkpoint_2.showturtle()
runner.showturtle()
yertle.showturtle()
enemy.showturtle()
magic_marker = Turtle(visible=False) # for writing text
screen.onkey(k1, "a") # Enemy
screen.onkey(k2, "d") # Enemy
screen.onkey(k3, "Left") # Yertle
screen.onkey(k4, "Right") # Yertle
screen.onkey(k5, "w") # Shoot(Enemy)
screen.onkey(k6, "Up") # Shoot(Yertle)
screen.listen()
move_runner()
screen.mainloop()
Your code had errors (as did your comments) but my primary advice is to review the turtle documentation to see all the features available to you -- when writing a game, you need to know what a turtle can do.
I changed the bullets into a single shared bullet -- turtles don't go away when you're finished with them so this seemed better resource-wise. But it's also buggy, however. If you continue with a single bullet model, you'll want to interlock the firing events to prevent overlap. If you instead go with multiple bullets firing at the same, you'll want to add more ontimer events like the runner uses to control their motion.

Python Turtle: Starting Countdown gets stuck

I am making a dodging game in which the turtle (shaped like a turtle) has to avoid other turtles (shaped like crocodiles). I got the game working but am trying to add in a countdown before the game starts which goes 3,2,1,GO!
My thinking is that since the countdown_number variable I have goes 3, 2, 1, and then GO!, I can get it to come before the rest of the game by having everything else dependent on the value of the countdown_number being "GO!".
Right now, however, when I start the program it gets stuck on 3 and after the update interval starts over again instead of continuing through 2, 1, and GO! so the game cannot start.
I've seen a lot of questions on Stack Overflow that have to do with running timers and things concurrent to the game but I need this to occur before the game starts.
import turtle
import random
import pygame
window_height = 600
window_width = 600
update_interval = 25
countdown_number = 3
river_width = 400
minimum_river_width = 200
border_height = 600
river_width_update = 0.5
safe_distance_from_border = border_height / 2 + 3
number_of_enemies = 10
enemies = []
enemy_speeds = []
enemy_width = 100
enemy_height = 40
enemy_speed_min, enemy_speed_max = 10, 20
safe_distance_from_enemy = 15
def startgame():
global countdown_number
if countdown_number >= 1:
turtle.home()
turtle.left(270)
turtle.clear()
turtle.speed(0)
for _ in range(0,100,5):
turtle.forward(1)
turtle.color("grey"+str(_))
turtle.write(countdown_number, align="center", font=("Arial", 200, "normal"))
if countdown_number == 0:
countdown_number = "GO!"
turtle.home()
turtle.left(270)
turtle.clear()
turtle.speed(0)
for _ in range(0,100,5):
turtle.forward(1)
turtle.color("grey"+str(_))
turtle.write(countdown_number, align="center", font=("Arial", 200, "normal"))
turtle.clear()
#print(number)
def gameover(msg):
print(msg) # Probably comment this out later
turtle.home()
turtle.write(msg, align="center", font=("Arial", 24, "normal"))
def moveplayerturtle(x, y):
if x > -window_width / 2 and x < window_width / 2:
turtle.goto(x, y)
def updatescreen():
global river_width
global countdown_number
if countdown_number != "GO!":
startgame()
if countdown_number == "GO!":
if upper_river_border.ycor() >= window_height-200:
upper_river_border.sety(upper_river_border.ycor() - river_width_update)
if lower_river_border.ycor() <= -window_height+200:
lower_river_border.sety(lower_river_border.ycor() + river_width_update)
if upper_river_border.ycor() - turtle.ycor() < safe_distance_from_border:
gameover("Game over!")
return
if turtle.ycor() - lower_river_border.ycor() < safe_distance_from_border:
gameover("Game over!")
return
for i in range(number_of_enemies):
enemies[i].forward(enemy_speeds[i])
if enemies[i].xcor() > (window_width+enemy_width)/2:
x = -(window_width+enemy_width)/2
y = int(turtle.ycor())
enemies[i].goto(x, y)
s=1
enemy_speeds[i]=int(random.randrange(10+s, 20+s))
if turtle.distance(enemies[i]) < safe_distance_from_enemy:
gameover("You lose!")
return
turtle.ontimer(updatescreen, update_interval)
turtle.update()
turtle.setup(window_width, window_height) # Set the window size
turtle.bgcolor("DarkBlue")
turtle.tracer(False)
upper_river_border = turtle.Turtle()
upper_river_border.up()
lower_river_border = turtle.Turtle()
lower_river_border.up()
upper_river_border.shape("square")
lower_river_border.shape("square")
upper_river_border.color("DarkOrange4")
lower_river_border.color("DarkOrange4")
upper_river_border.shapesize(30, 40)
lower_river_border.shapesize(30, 40)
upper_river_border.sety((border_height + river_width) / 2)
lower_river_border.sety(-(border_height + river_width) / 2)
turtle.addshape("crocodile.gif")
for _ in range(number_of_enemies):
enemy = turtle.Turtle()
turtle.addshape("crocodile.gif")
enemy.shape("crocodile.gif")
enemy.up()
x = -(window_width + enemy_width) / 2
y = random.randint(-(river_width-enemy_height)/2, (river_width-enemy_height)/2)
enemy.goto(x, y)
enemies.append(enemy)
enemy_speeds.append(random.randint(enemy_speed_min, enemy_speed_max))
turtle.shape("turtle")
turtle.left(180)
turtle.color("GreenYellow")
turtle.up()
turtle.ondrag(moveplayerturtle)
turtle.ontimer(updatescreen, update_interval)
turtle.done()
I've gotten the countdown to work perfectly fine on its own when I've written it as it's own program so I think it must just have to do with transitioning from the countdown sequence to the game loop itself that's causing the problem.
Any help would be appreciated.
You've got your wires crossed as far as the splash screen countdown -- calling the wrong thing at the wrong time. Below's my suggestion on a minimal fix. First, redefine startgame() as follows:
def startgame():
global countdown_number
turtle.home()
turtle.clear()
turtle.left(270)
if countdown_number > 0:
for grey in range(0, 100, 5):
turtle.forward(1)
turtle.color("grey" + str(grey))
turtle.write(countdown_number, align="center", font=("Arial", 200, "normal"))
countdown_number -= 1
turtle.ontimer(startgame, countdown_interval)
else:
for grey in range(0, 100, 5):
turtle.forward(1)
turtle.color("grey" + str(grey))
turtle.write("GO!", align="center", font=("Arial", 200, "normal"))
turtle.clear()
turtle.ontimer(updatescreen, countdown_interval)
Next some small changes to accomodate this rewrite. At the top of your code, add the definition:
countdown_interval = 1000
near the definition of update_interval.
At the bottom of your code, instead of this:
turtle.ontimer(updatescreen, update_interval)
turtle.done()
Do this:
turtle.ontimer(startgame, update_interval)
turtle.done()
Finally, in updatescreen() remove all code dealing with countdown_number:
global countdown_number
if countdown_number != "GO!":
startgame()
if countdown_number == "GO!":
and reindent the body of this function as needed.
That should do it. Happy dodging!

Python Turtle game, Check not working?

import turtle
# Make the play screen
wn = turtle.Screen()
wn.bgcolor("red")
# Make the play field
mypen = turtle.Turtle()
mypen.penup()
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(5)
for side in range(4):
mypen.forward(600)
mypen.left(90)
mypen.hideturtle()
# Make the object
player = turtle.Turtle()
player.color("black")
player.shape("circle")
player.penup()
# define directions( East, West , South , Nord )
def west():
player.setheading(180)
def east():
player.setheading(0)
def north():
player.setheading(90)
def south():
player.setheading(270)
# define forward
def forward():
player.forward(20)
# Wait for input
turtle.listen()
turtle.onkey(west, "a")
turtle.onkey(east, "d")
turtle.onkey(forward,"w")
turtle.onkey(north,"q")
turtle.onkey(south,"s")
if player.xcor() > 300 or player.xcor() < -300:
print("Game over")
if player.ycor() > 300 or player.ycor() < -300:
print("Game over")
So everything is working fine, till the If statements. When i go trough the play field it should give me a print " Game over ". The coordinates are right but it doesnt check the coordinates! What am i doing wrong ?
The problem is that your logic to test if the player has gone out of bounds is at the top level of your code -- it doesn't belong there. You should turn control over to the turtle listener, via mainloop() and handle the bounds detection in one of your callback methods, namely forward().
A demonstration of the above in a rework of your code:
import turtle
QUADRANT = 250
# Make the play screen
screen = turtle.Screen()
screen.bgcolor("red")
# Make the play field
play_pen = turtle.Turtle()
play_pen.pensize(5)
play_pen.speed("fastest")
play_pen.penup()
play_pen.setposition(-QUADRANT, -QUADRANT)
play_pen.pendown()
for _ in range(4):
play_pen.forward(QUADRANT * 2)
play_pen.left(90)
play_pen.hideturtle()
# Make the object
player = turtle.Turtle()
player.color("black")
player.shape("circle")
player.penup()
# define forward
def forward():
player.forward(20)
if player.xcor() > QUADRANT or player.xcor() < -QUADRANT or player.ycor() > QUADRANT or player.ycor() < -QUADRANT:
player.hideturtle()
player.setposition((0, 0))
player.write("Game over", False, align="center", font=("Arial", 24, "normal"))
# define directions(East, West, North, South)
turtle.onkey(lambda: player.setheading(180), "a") # west
turtle.onkey(lambda: player.setheading(0), "d") # east
turtle.onkey(lambda: player.setheading(90), "q") # north
turtle.onkey(lambda: player.setheading(270), "s") # south
turtle.onkey(forward, "w")
# Wait for input
turtle.listen()
turtle.mainloop()

Categories

Resources