Help with two issues, buttons and second class object

Peter Otten __peter__ at web.de
Fri Nov 25 06:24:15 EST 2016


Thomas Grops via Python-list wrote:

> Also I am struggling to understand:
> 
>    def move_tank(self, dx, dy):
>         self.x += dx
>         self.y += dy
>         self.canvas.move(self.id, dx, dy)
> 
> Where does the dx and dy values get input?

To find the place where the move_tank() method is invoked hit the search 
button or key of your text editor. In this case you'll find

    def move(self):
        self.move_tank(*self.moves[self.direction])
        ...

so move_tank() is invoked by the move() method. But what the heck is

*self.moves[self.direction]

? From the fact that the script runs without error you can conclude that it 
resolves to two integer values. Let's try in the interactive interpreter
(the script is called tanks2, so that's what I import):

$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>> import tanks2
>>> root = tkinter.Tk()
>>> canvas = tkinter.Canvas(root, width=100, height=100)
>>> canvas.pack()
>>> tank = tanks2.Tank(root, canvas, "example", 10, 10, 10, 10, "red")
>>> tank.direction
0

That's the value determining the direction into which the tank is supposed 
to move (what you called "count" in your script).

>>> tank.moves
[(5, 0), (-5, 0), (0, -2), (0, 2), (-1, -1), (1, -1), (1, 1), (-1, 1)]

That's the list of speed vectors I set up in the initialiser (the 
Tank.__init__() method)

>>> tank.moves[tank.direction]
(5, 0)

So move_tank() is supposed to move the tank 5 pixels to the right and 0 
pixels down. For this invocation

self.move_tank(*self.moves[self.direction])

is equivalent to

self.move_tank(*(5, 0))

The leading star tells python to treat the elements of the tuple as if they 
were passed individually to the function or method. The actual dx and dy are 
then 5 and 0:

self.move_tank(5, 0)

Now let's move our little red tank:

>>> tank.x, tank.y
(10, 10)
>>> tank.move_tank(3, 7)
>>> tank.x, tank.y
(13, 17)
>>> tank.move_tank(tank.moves[tanks2.MRIGHTDOWN])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: move_tank() missing 1 required positional argument: 'dy'

Oops, I forgot the leading *. Second attempt:

>>> tank.move_tank(*tank.moves[tanks2.MRIGHTDOWN])
>>> tank.x, tank.y
(14, 18)






More information about the Python-list mailing list