Home > Software design >  Turtle text increases by a seemingly random amount, how do I fix this?
Turtle text increases by a seemingly random amount, how do I fix this?

Time:09-26

I'm pretty new to coding with python, so I am very confused. I am currently working on a cookie clicker-type game. Here is the code so far.

import turtle as t

#screen
wn = t.Screen()
wn.bgcolor("DarkSlateGray")
wn.setup(width=1366, height=768)

#clicks
clicks = 0

#square
sq = t.Turtle()
sq.speed(0)
sq.shape("square")
sq.color("coral2")
sq.shapesize(stretch_wid=5, stretch_len=5)
sq.penup()
sq.goto(0,0)

#pen
pen = t.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 270)
pen.write("Times clicked: 0", align="center", font=("Comic Sans MS", 24, "normal"))

#click function
def getclick(sq, clicks):
    clicks  = 1
    pen.clear()
    pen.write("Times clicked: {}".format(clicks), align="center", font=('Comic Sans MS', 24, 'normal'))

#click detection
wn.listen()
sq.onclick(getclick)

The function "getclick" is supposed to make the "clicks" go up by 1 and then the rest of the function writes the new amount of clicks. However, when I test this code, the number does not go up by 1, but it goes up by a random amount somewhere between -49.0 and 49.0. For example, I'll run the program and then click the turtle and the number goes to -29.0 and then again it goes to 34.0, but then if I click it again, it doesn't do anything.

CodePudding user response:

There's some issues in the use of sq.onclick(getclick). From the turtle documentation: The signature of turtle.onclick is

turtle.onclick(fun, btn=1, add=None)
Parameters
fun – a function with two arguments which will be called with the
coordinates of the clicked point on the canvas

So the x, y coordinates of your click are being passed to your getclick function, and you've been printing the y coordinate of your clicks (between around '-49.0 and 49.0'). The function parameter clicks is also not doing what you expect: it just shadows the global clicks, and doesn't modify it. A more correct version is:

def getclick(x, y):
    global clicks
    clicks  = 1
    pen.clear()
    pen.write("Times clicked: {}".format(clicks), align="center", font=('Comic Sans MS', 24, 'normal'))
  • Related