Is there a way to move turtle slower in Python Turtle Graphics? - python

I have made a program to move turtle position by pressing the keyboard, but is there a way to make it move in smaller increments of pixels?
and also, is it possible to move turtle up and down instead of only left and right?
from turtle import Screen, Turtle
TURTLE_SIZE = 200
# functions
def go_left():
t.direction = 'left'
def go_right():
t.direction = 'right'
screen = Screen()
screen.setup(1152,648)
screen.tracer(0)
# player
t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
t.direction = 'stop'
# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()
while True:
x = t.xcor()
if t.direction == 'left':
if x > TURTLE_SIZE - 576:
x -= 3
t.setx(x)
else:
t.direction = 'stop'
elif t.direction == 'right':
if x < 576 - TURTLE_SIZE:
x += 3
t.setx(x)
else:
t.direction = 'stop'
screen.update()
screen.mainloop()

The reason your dot was moving so fast was because of your while True loop.
I moved most of that logic inside the the go_ functions and added an up and down for you as well.
from turtle import Screen, Turtle
TURTLE_SIZE = 200
def go_left():
x = t.xcor()
if x > TURTLE_SIZE - 576:
x -= 3
t.setx(x)
screen.update()
def go_right():
x = t.xcor()
if x < 576 - TURTLE_SIZE:
x += 3
t.setx(x)
screen.update()
def go_up(): # added this function
y = t.ycor()
if y < 576 - TURTLE_SIZE:
y += 3
t.sety(y)
screen.update()
def go_down(): # added this function
y = t.ycor()
if y < 576 - TURTLE_SIZE:
y -= 3
t.sety(y)
screen.update()
screen = Screen()
screen.setup(1152,648)
screen.tracer(0)
t = Turtle()
t.shape("circle")
t.speed("slowest")
t.color("blue")
t.penup()
t.setx(338)
t.sety(0)
screen.update()
# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_down, 'Down') # added this listener
screen.onkeypress(go_up, 'Up') # added this listner
screen.onkeypress(go_right, 'Right')
screen.listen()
screen.mainloop()

Related

Making python turtle based game reset on click

I'm trying to get my game to restart once the user clicks on the screen. I've tried wrapping the whole thing in a while loop, but that gave me errors about variables not being defined.
I've also tried wrapping the code in a function but that also gives me errors on variables.
Here's the code.
import turtle
import math
import random
import pygame
pygame.init()
pygame.mixer.init()
# MUSIC AND SOUND SETUP
pygame.mixer.music.load("Sounds/music.mp3")
pygame.mixer.music.play(loops=-1)
I'm using pygame just to add music into my game.
bubblefiredsound = pygame.mixer.Sound("Sounds/bubblefired.mp3")
enemyhitsound = pygame.mixer.Sound("Sounds/enemyhit.mp3")
# SCREEN SETUP
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Space Invaders")
screen.bgpic("TurtleInvadersBackground.png")
# CUSTOM SHAPES
turtle.register_shape("Enemy.gif")
turtle.register_shape("Turtle.gif")
turtle.register_shape("Bubble.gif")
# BORDERS
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.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
# SCORE
score = 0
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 270)
scorestring = "Score: %s" % score
score_pen.write(scorestring, False, align="left", font=("Bubble3D", 20, "normal"))
score_pen.hideturtle()
# MAIN TURTLE
MajorTom = turtle.Turtle()
MajorTom.color("blue")
MajorTom.shape("Turtle.gif")
MajorTom.penup()
MajorTom.speed(0)
MajorTom.setposition(0, -250)
MajorTom.setheading(90)
playerspeed = 0
# NUMBER OF ENEMIES
number_of_enemies = 5
# PLACEHOLDER FOR ENEMIES
enemies = []
# ADD ENEMIES TO THE PLACEHOLDER
for i in range(number_of_enemies):
# CREATE ENEMIES
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("Enemy.gif")
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
enemyspeed = 5
# CREATE THE PROJECTILE BUBBLE
bubble = turtle.Turtle()
bubble.color("blue")
bubble.shape("Bubble.gif")
bubble.penup()
bubble.speed(0)
bubble.setheading(90)
bubble.hideturtle()
bubble.setpos(0, -300)
bubblespeed = 20
# BUBBLE STATE, READY = READY TO FIRE, FIRE = FIRING
bubblestate = "ready"
# MOVEMENT (LEFT AND RIGHT)
def move_left():
global playerspeed
playerspeed = -7
def move_right():
global playerspeed
playerspeed = 7
def stop_player():
global playerspeed
playerspeed = 0
def fire_bubble():
global bubblestate
if bubblestate == "ready":
bubblestate = "fire"
# MOVE BUBBLE TO MAJOR TOM
x = MajorTom.xcor()
y = MajorTom.ycor() + 10
bubble.setposition(x, y)
bubble.showturtle()
if bubblestate == "fire":
bubblefiredsound.play()
def CollisionDetection(t1, t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
if distance < 32:
return True
else:
return False
# KEYBINDINGS
screen.listen()
screen.onkeypress(move_left, "a")
screen.onkeypress(move_right, "d")
screen.onkeyrelease(stop_player, "a")
screen.onkeyrelease(stop_player, "d")
screen.onkey(fire_bubble, "space")
This is the main loop, most of the code is put together here.
# GAME LOOP
while True:
# MOVE PLAYER
MajorTom.setx(MajorTom.xcor() + playerspeed)
# BORDER CONTROL
if MajorTom.xcor() > 285:
MajorTom.setx(285)
playerspeed = 0
elif MajorTom.xcor() < -285:
MajorTom.setx(-285)
playerspeed = 0
for enemy in enemies:
# ENEMY MOVEMENT
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
# MOVE THE ENEMY BACK AND DOWN
if enemy.xcor() > 280 or enemy.xcor() < -280:
# MOVE ALL ENEMIES DOWN
for e in enemies:
y = e.ycor()
y -= 40
e.sety(y)
# CHANGE ENEMY DIRECTION
enemyspeed *= -1
# BUBBLE HITS ENEMY
if CollisionDetection(bubble, enemy):
# PLAY BUBBLE BURST SOUND
enemyhitsound.play()
# RESET BUBBLE POSITION
bubble.hideturtle()
bubblestate = "ready"
bubble.setposition(0, -400)
# RESET ENEMY POSITION "SPAWN NEW ENEMY"
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
# ADD SCORE IF PLAYER HITS BUBBLE
score += 10
scorestring = "Score: %s" % score
score_pen.clear()
score_pen.write(scorestring, False, align="left", font=("Bubble3D", 20, "normal"))
if CollisionDetection(MajorTom, enemy) or enemy.ycor() < -300:
MajorTom.hideturtle()
enemy.hideturtle()
print("Game Over")
GameOverPen = turtle.Turtle()
GameOverPen.hideturtle()
GameOverPen.penup()
GameOverPen.goto(0,0)
GameOverPen.speed(0)
GameOverPen.color("pink")
GameOverPen.write("GAME OVER!", align="center", font=("Bubble3D", 90, "normal"))
GameOverPen.goto(0, -20)
GameOverPen.write("\nClick to try again!", align="center", font=("Arial", 20, "normal"))
break
# BUBBLE MOVEMENT
if bubblestate == "fire":
y = bubble.ycor()
y += bubblespeed
bubble.sety(y)
# CHECK TO SEE IF BUBBLE HAS HIT THE CEILING
if bubble.ycor() > 275:
bubble.hideturtle()
bubblestate = "ready"
you are looking for the turtle.onscreenclick function.
this function is called with the current x and y coordinates of the mouse when the screen is clicked.
def reset(x_pos, y_pos):
# reset the game
turtle.onscreenclick(reset)

Get snake (list of turtles) to restart after self collision?

How would I get my turtle to restart in the middle of screen once it collides with it's own body?
from turtle import Screen, Turtle
import random
import time
DELAY = 100
def move():
if direction == 'up':
y = turtle.ycor()
turtle.sety(y + 20)
elif direction == 'down':
y = turtle.ycor()
turtle.sety(y - 20)
elif direction == 'left':
x = turtle.xcor()
turtle.setx(x - 20)
elif direction == 'right':
x = turtle.xcor()
turtle.setx(x + 20)
screen.update()
screen.ontimer(move, DELAY)
if turtle.xcor()>490 or turtle.xcor()<-490 or turtle.ycor()>490 or turtle.ycor()<-490:
time.sleep(1)
turtle.goto(0,0)
turtle.direction = "stop"
for section in sections
section.goto(1000, 1000)
sections.clear()
if turtle.distance(food) < 20:
x = random.randint(-390, 390)
y = random.randint(-390, 390)
food.goto(x, y)
new_section = Turtle()
new_section.speed(0)
new_section.shape("square")
new_section.color("orange", "grey")
new_section.penup()
sections.append(new_section)
for index in range(len(sections)-1,0, -1):
x = sections[index-1].xcor()
y = sections[index-1].ycor()
sections[index].goto(x, y)
if len(sections) > 0:
x = turtle.xcor()
y = turtle.ycor()
sections[0].goto(x, y)
def up():
global direction
direction = 'up'
def down():
global direction
direction = 'down'
def left():
global direction
direction = 'left'
def right():
global direction
direction = 'right'
screen = Screen()
screen.title(" Snakebite mini Game")
screen.bgcolor('brown')
screen.setup(width=800, height=700)
screen.tracer(0)
turtle = Turtle()
turtle.shape('turtle')
turtle.speed(0)
turtle.penup()
food = Turtle()
food.shape('circle')
food.color("red", "yellow")
food.speed(0)
food.penup()
food.goto(0,100)
sections = []
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()
The basic answer is something like:
if any(turtle.distance(section) < 20 for section in sections):
turtle.goto(0, 0)
direction = 'stop'
...
But be warned, this means that doing a 180 is now a fatal move!
Complete code rework with optimizations, style tweaks and changes to make it more playable:
from turtle import Screen, Turtle
from random import randint
DELAY = 100
def up():
global direction
direction = 'up'
turtle.setheading(90)
def down():
global direction
direction = 'down'
turtle.setheading(270)
def left():
global direction
direction = 'left'
turtle.setheading(180)
def right():
global direction
direction = 'right'
turtle.setheading(0)
def move():
global direction
x, y = old_position = turtle.position()
if direction == 'up':
turtle.sety(y + 20)
elif direction == 'down':
turtle.sety(y - 20)
elif direction == 'left':
turtle.setx(x - 20)
elif direction == 'right':
turtle.setx(x + 20)
if direction != 'stop':
if sections:
if any(turtle.distance(section) < 20 for section in sections):
turtle.goto(0, 0)
direction = 'stop'
for section in sections:
section.hideturtle()
sections.clear()
else:
last_position = sections[-1].position()
if len(sections) > 1:
for index in range(len(sections) - 1, 0, -1):
sections[index].goto(sections[index - 1].position())
sections[0].goto(old_position)
old_position = last_position
if not (-390 < turtle.xcor() < 390 and -390 < turtle.ycor() < 390):
turtle.goto(0, 0)
direction = 'stop'
for section in sections:
section.hideturtle()
sections.clear()
if turtle.distance(food) < 20:
food.goto(randint(-380, 380), randint(-380, 380))
new_section = Turtle()
new_section.shape('square')
new_section.speed('fastest')
new_section.color('orange', 'grey')
new_section.penup()
new_section.goto(old_position)
sections.append(new_section)
screen.update()
screen.ontimer(move, DELAY)
screen = Screen()
screen.title("Snakebite mini Game")
screen.bgcolor('brown')
screen.setup(width=800, height=800)
screen.tracer(False)
turtle = Turtle()
turtle.shape('triangle')
turtle.speed('fastest')
turtle.color('orange', 'grey')
turtle.penup()
food = Turtle()
food.shape('circle')
food.speed('fastest')
food.color('red', 'yellow')
food.penup()
food.goto(randint(-380, 380), randint(-380, 380))
sections = []
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()

Why does it say my mainloop is unreachable?

import turtle
import time
delay = 0.1
ms = turtle.Screen()
ms.title("hungry snake Game by #Rafa")
ms.bgcolor("green")
ms.setup(width=600, height=600)
ms.tracer(0)
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x + 20)
if head.direction == "right":
x = head.xcor()
head.setx(x - 20)
# main game loop
while True:
ms.update()
move()
time.sleep(delay)
//Here is where am having trouble with the code?
ms.mainloop()
The real error here is the use of while True: and sleep() in an event-driven environment like turtle. We can replace the infinite loop and the time.sleep() with a turtle ontimer() method:
from turtle import Screen, Turtle
DELAY = 100 # milliseconds
def move():
if direction == 'up':
y = turtle.ycor()
turtle.sety(y + 20)
elif direction == 'down':
y = turtle.ycor()
turtle.sety(y - 20)
elif direction == 'left':
x = turtle.xcor()
turtle.setx(x - 20)
elif direction == 'right':
x = turtle.xcor()
turtle.setx(x + 20)
screen.update()
screen.ontimer(move, DELAY)
def up():
global direction
direction = 'up'
def down():
global direction
direction = 'down'
def left():
global direction
direction = 'left'
def right():
global direction
direction = 'right'
screen = Screen()
screen.title("Hungry Snake Game")
screen.bgcolor('green')
screen.setup(width=600, height=600)
screen.tracer(0)
turtle = Turtle()
turtle.shape('square')
turtle.speed('fastest')
turtle.penup()
direction = 'stop'
screen.onkey(up, 'Up')
screen.onkey(down, 'Down')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
# main game loop
move()
screen.mainloop()

Python Turtle Space Invaders bullets not hitting invaders

I'm very new to turtle and python in general, so I apologize if my code seems messy.
I'm currently coding a turtle version of space invaders and I can't figure out why my invaders aren't dying when they hit the turtles. The code seems to be the same as all the other space invader turtle programs I can find. Any help would be greatly appreciated.
import turtle
import random
import math
#### Player ####
player1 = turtle.Turtle()
player1.shape("arrow")
player1.color("white")
player1.speed(0)
player1.penup()
player1.setheading(90)
player1.setposition(0, -175)
player1.speed(4)
def move_right():
x = player1.xcor()
x += playerspeed
if x > 210:
x = 210
player1.setx(x)
def move_left():
x = player1.xcor()
x -= playerspeed
if x < -210:
x = -210
player1.setx(x)
bulletlist = []
def fire():
if len(bulletlist) < 5:
bulletlist.append(Bullet())
#### Window ####
win = turtle.Screen()
win.bgcolor("black")
win.tracer(2)
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-225, -225)
border_pen.pensize(3)
border_pen.pendown()
for side in range(4):
border_pen.fd(450)
border_pen.lt(90)
border_pen.hideturtle()
### Invader ###
class Invader(turtle.Turtle):
def __init__(self, xcor, ycor):
turtle.Turtle.__init__(self)
self.color("red")
self.shape("turtle")
self.penup()
self.speed(0)
self.setposition(xcor, ycor)
self.setheading(270)
self.speed(1)
self.hit = 0
### Bullet ###
bulletstate = 1
class Bullet(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color("yellow")
self.shape("arrow")
self.shapesize(.5, 1)
self.penup()
self.speed(0)
self.setheading(90)
self.hideturtle()
self.bulletspeed = 20
fire()
def bullet_movement():
global firedb
firedb = bulletlist[-1]
firedb.speed(0)
ybul = firedb.ycor()
ybul += 10
firedb.sety(ybul)
if ybul > 195:
firedb.hideturtle()
def fire_bullet():
print("fire!")
firedb = bulletlist[-1]
firedb.hideturtle()
x = player1.xcor()
y = player1.ycor() + 20
firedb.setpos(x, y)
firedb.showturtle()
if firedb.ycor() > 200:
firedb.hideturtle()
bulletlist.remove(firedb)
def bulletmake():
bulletfire = Bullet()
def bulletmechanics():
fire()
fire_bullet()
win.listen()
win.onkey(move_left, "Left")
win.onkey(move_right, "Right")
win.onkey(fire_bullet, "space")
enemies = []
xx = -175
xxxx = -175
for invader in range(19):
if invader <= 9:
enemies.append(Invader(xx, 200))
xx += 30
if invader >= 9:
enemies.append(Invader(xxxx, 175))
xxxx += 30
playerspeed = 7
enemyspeed = 8
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
dead = []
while True:
global firedb
firedb = bulletlist[-1]
fire()
bullet_movement()
for Invader in enemies:
bullet_movement()
# if Invader.distance(firedb.xcor()+200, firedb.ycor()+200) < 1:
if isCollision(bulletlist[-1], Invader) == True:
print("AAAAAAAAGH")
isCollision(firedb, Invader)
Invader.hit += 1
if Invader.hit == 1:
Invader.color("orange")
if Invader.hit == 2:
Invader.color("yellow")
if Invader.hit == 3:
Invader.speed(0)
Invader.setpos(1000, 1000)
dead.append(Invader)
Invader.hideturtle()
for invader in enemies:
bullet_movement()
xpos = invader.xcor()
invader.speed(0)
xpos += enemyspeed
invader.setx(xpos)
if invader.xcor() > 200:
for invader in enemies:
ypos = invader.ycor()
ypos -= 40
invader.sety(ypos)
enemyspeed *= -1
if invader.xcor() < -200:
for invader in enemies:
y = invader.ycor()
y -= 40
invader.sety(y)
enemyspeed *= -1
I belive your problem is the way you interlace bullet movements with invader movements. In your while True: loop (which shouldn't exist in an event-driven world like turtle) you call bullet_movement() at the top level, then in a for loop and again within a nested for loop. So where you see the bullet and where it is relative to invaders aren't necessarily the same.
I've reworked your code, and for example purposes, simplified it in places. Along with the above issues, I've also modified the code to use turtle tilt which is perfect for this sort of game where the turtles face in one direction but move in another. And I've completely trashed your isCollision() function as turtles already know how to compute their distance from another turtle.
from turtle import Screen, Turtle
class Invader(Turtle):
def __init__(self, xcor, ycor):
super().__init__(shape="turtle")
self.color("red")
self.penup()
self.setposition(xcor, ycor)
self.tilt(-90)
self.speed('slow')
self.hit = 0
class Bullet(Turtle):
def __init__(self):
super().__init__(shape="arrow", visible=False)
self.shapesize(.5, 1)
self.color("yellow")
self.penup()
self.setheading(90)
self.speed('fastest')
self.bulletspeed = 20
def move_right():
if player.xcor() + playerspeed < 210:
player.forward(playerspeed)
def move_left():
if player.xcor() - playerspeed > -210:
player.backward(playerspeed)
def bullet_movement():
firedb.forward(10)
if firedb.ycor() > 195:
firedb.hideturtle()
def fire_bullet():
if not firedb.isvisible():
x, y = player.position()
firedb.setposition(x, y + 20)
firedb.showturtle()
def isCollision(t1, t2):
return t1.distance(t2) < 20
def move():
global enemyspeed
if firedb.isvisible():
bullet_movement()
for invader in enemies:
if firedb.isvisible() and isCollision(firedb, invader):
invader.hit += 1
if invader.hit == 1:
invader.color("orange")
elif invader.hit == 2:
invader.color("yellow")
elif invader.hit == 3:
invader.hideturtle()
enemies.remove(invader)
firedb.hideturtle() # only one hit per bullet!
invader.forward(enemyspeed)
if invader.xcor() < -200 or invader.xcor() > 200:
for invader in enemies:
y = invader.ycor() - 40
invader.sety(y)
enemyspeed *= -1
win.update()
win.ontimer(move, 50)
#### Player ####
player = Turtle("arrow")
player.color("white")
player.penup()
player.tilt(90)
player.sety(-175)
player.speed('fast')
#### Window ####
win = Screen()
win.bgcolor("black")
win.tracer(False)
border_pen = Turtle(visible=False)
border_pen.speed('fastest')
border_pen.color("white")
border_pen.pensize(3)
border_pen.penup()
border_pen.setposition(-225, -225)
border_pen.pendown()
for _ in range(4):
border_pen.forward(450)
border_pen.left(90)
### Bullet ###
firedb = Bullet()
enemies = []
xx = -175
xxxx = -190
for invader_count in range(19):
if invader_count < 9:
enemies.append(Invader(xx, 200))
xx += 30
else:
enemies.append(Invader(xxxx, 175))
xxxx += 30
playerspeed = 7
enemyspeed = 2
win.onkey(move_left, "Left")
win.onkey(move_right, "Right")
win.onkey(fire_bullet, "space")
win.listen()
move()
win.mainloop()
Finally, be careful with Python global and turtle tracer() which are routinely misunderstood.

Game loop in turtle python not functioning

Hi i am trying to create a simple environment/ game with turtle. It is a 3x4 grid with the upper right most square being the end goal. as the token enters this goal I would like the token to reset to the start. My while loop however seems to be freezing the script. I believe my logic here is wrong. the coordinates of the goal is (-25,225). I would like to check if the token's current position matches this and if so return true - this is the logic i would like to implement. Thanks for your help!
import turtle
wn = turtle.Screen()
wn.bgcolor("white")
wn.title("test")
""" Create the Grid """
greg = turtle.Turtle()
greg.speed(0)
def create_square(size,color="black"):
greg.color(color)
greg.pd()
for i in range(4):
greg.fd(size)
greg.lt(90)
greg.pu()
greg.fd(size)
def row(size,color="black"):
for i in range(4):
create_square(size)
def board(size,color="black"):
greg.pu()
greg.goto(-(size*4),(size*4))
for i in range(3):
row(size)
greg.bk(size*4)
greg.rt(90)
greg.fd(size)
greg.lt(90)
def color_square(start_pos,distance_sq, sq_width, color):
greg.pu()
greg.goto(start_pos)
greg.fd(distance_sq)
greg.color(color)
greg.begin_fill()
for i in range(4):
greg.fd(sq_width)
greg.lt(90)
greg.end_fill()
greg.pu()
def initiate_grid():
board(50)
color_square((-200,200),150, 50,color="green")
color_square((-200,150),50, 50,color="black")
color_square((-200,150),150, 50,color="red")
greg.hideturtle()
initiate_grid()
""" Create the token object """
player = turtle.Turtle()
player.color("blue")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(-175,125)
player.setheading(90)
""" Player Movement """
playerspeed = 50
#Move the player left and right
def move_left():
x = player.xcor()
x -= playerspeed
if x < -175:
x = -175
player.setx(x)
def move_right():
x = player.xcor()
x += playerspeed
if x > -25:
x = -25
player.setx(x)
def move_up():
y = player.ycor()
y += playerspeed
if y > 225:
y = 225
player.sety(y)
def move_down():
y = player.ycor()
y -= playerspeed
if y < 125:
y = 125
player.sety(y)
#Create Keyboard Bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
def isGoal(player_pos):
if player_pos.xcor() == -25 and player_pos.ycor() == 225:
return True
else:
return False
#Main Game loop
while True:
#check for collision between player and goal
if isGoal(player):
#reset player
player.setposition(-175,125)
delay = input("Press enter to finish.")
EDIT :
I have now tried the following code. Game doesn't freeze anymore and once i enter the square the token appears inside the square but this is where the second problem occurs. I have now entered the square which should reset me back to my original position (-175, 125). However I need to press any key a second time in order for that reset to happen and by this time the token would have reset and moved one space based on the key I pressed. any ideas?
def isGoal():
if player.xcor() == -25 and player.ycor() == 225:
player.goto(-175,125)
else:
pass
""" Player Movement """
playerspeed = 50
#Move the player left and right
def move_left():
isGoal()
x = player.xcor()
x -= playerspeed
if x < -175:
x = -175
player.setx(x)
def move_right():
isGoal()
x = player.xcor()
x += playerspeed
if x > -25:
x = -25
player.setx(x)
def move_up():
isGoal()
y = player.ycor()
y += playerspeed
if y > 225:
y = 225
player.sety(y)
def move_down():
isGoal()
y = player.ycor()
y -= playerspeed
if y < 125:
y = 125
player.sety(y)
#Create Keyboard Bindings
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
delay = input("Press enter to finish.")
Your while loop prevents anything else to happen indeed. What you want here is to put your isGoal() checks in the move_<XXX> event handlers and let turtle's own main loop run.
EDIT: for your second question:
However I need to press any key a second time in order for that reset to happen
the reason is quite simple: you should call isGoal() after you move the player's turtle, not before:
def move_left():
x = player.xcor()
x -= playerspeed
if x < -175:
x = -175
player.setx(x)
isGoal()

Categories

Resources