I have written a code that makes a turtle move around within a box. I am trying to write a portion to change its size if you push certain keys, such as g for grow and s for shrink.
However, I feel the way I make it grow and shrink is not very good. Whenever the turtle is at its default size and I press shrink, I get an error stating that its stetch_len
/stretch_wid
must not be 0
.
I have tried using if
to make it so it can't shrink if its size is one, but I cannot get it to work. I think it may have something to do with my method of shrinking it, but I am not sure.
Semi-related, I had a button I set to reset the turtle to its default when pushed. However, If I make the turtle grow bigger, it it will not shrink down as much. The larger I make it, the bigger its default seems to become. Again, I think its related to the method I used to change the size, but I am not sure.
import turtle
import os
#Creates the window for the game
wn = turtle.Screen()
wn.bgcolor("cyan")
wn.title("Game Test")
#Creates the background for the game
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("black")
border_pen.penup()
border_pen.setposition(-250,-250)
border_pen.pendown()
border_pen.pensize(1)
for side in range(4):
border_pen.fd(500)
border_pen.lt(90)
border_pen.hideturtle()
#Creates the turtle
player = turtle.Turtle()
player.color("black")
player.shape("square")
player.pensize(2)
#player.penup()
player.setposition(0, 0)
player.setheading(90)
player.shapesize(1)
playerspeed = 10
# This resets the player to its default, beginning state
def reset():
player.setposition(0, 0)
player.setheading(90)
player.shapesize(1)
# Makes the character grow larger
def grow():
size = player.turtlesize()
increase = tuple([1 + num for num in size])
player.turtlesize(*increase)
return
#Makes the character shrink
def shrink():
size = player.turtlesize()
decrease = tuple([-1 + num for num in size])
if player.turtlesize() == 1:
return
else:
player.turtlesize(*decrease)
return
# Prints the characters coordinates in a seperate window from the game
def place():
b, c = player.pos()
print("\n")
print(b, ",", c)
# These are the keys you push to activate different things
# The movement uses a number pad, which make programming diagonal keys easier.
turtle.listen()
turtle.onkeypress(reset, "5")
turtle.onkey(grow, "g")
turtle.onkey(shrink, "s")
turtle.onkey(place, "p")
input("Press any key to exit...")
Uriya Harpeness brought to my attention I was using
turtlesize
. I switched this toshapesize
which allowed me to correct the code.To fix the problem, I used
shapesize
and set the variable to a, b, c instead of size. This allowed me to just add to each one, then set the new values as theshapesize
.It also meant for the reset function, I just had to write
player.shapesize(1, 1, 1)
.