Home > Mobile >  Trying to find the screensize and make an object go to the screensize over 2 with turtle
Trying to find the screensize and make an object go to the screensize over 2 with turtle

Time:06-19

So I'm writing a tron game in python turtle and I want to make the two bikes start at whatever the screen width is/2, and height/2. (Same thing for the other but negative width). Sadly this doesn't seem to work because you can't divide a function by an int. Does anyone know how to do it?

This is what I tried:

width = turtle.window_width
height = turtle.window_height

def tron():
    #Drawing the starting turtles
    blueplayer = turtle.Turtle()
    redplayer = turtle.Turtle()
    screen = turtle.Screen()
    screen.setup(width, height)
    screen.bgpic('TronBg.png')
    screen.bgcolor('black')
    screen.addshape('BlueBike.gif')
    screen.addshape('RedBike.gif')
    blueplayer.shape('BlueBike.gif')
    redplayer.shape('RedBike.gif')
    redplayer.pencolor("red")
    redplayer.pensize(3)
    blueplayer.pencolor("blue")
    blueplayer.pensize(3)
    redplayer.pu()
    blueplayer.pu()
    -> blueplayer.goto(width/2, height/2)
    -> redplayer.goto(-1*(width)/2, height/2)**
    redplayer.pd()
    blueplayer.pd()
    
    #Box border 
    #Border
    box = Turtle()
    box.ht()
    box.color('purple')
    box.speed('fastest')
    box.pensize(10)

    box.pu()
    box.setpos(-355, -345)
    box.pd()

    for i in range(5):
      box.forward(700)
      box.left(90)
tron()

CodePudding user response:

Change your code as follows and the problem will go away:

import turtle

width  = turtle.window_width()
height = turtle.window_height()

P.S. to obtain window width you call in case of the turtle module a function. To call a function it is necessary to provide () after the function name, else width will become just another name for turtle.window_width function. If you don't put the brackets after turtle.window_width in width = turtle.window_width you can solve the problem by adding width = width() in the next line. Try this out to see that it works in order to gain better understanding of what an assignment operator = does.

By the way: you can check which type and which value the variable width has with print(type(width), width). Such print debugging is often helpful because sometimes it is necessary to use value = module.some_name and sometimes value = module.some_name() to get the right value.

  • Related