A coordinate is a numerical value that specifies a position along an axis. On a canvas, four coordinates describe a rectangle: x1 and y1 mark its top-left corner, while x2 and y2 mark its bottom-right corner. section 38.2
A rectangle's position and size can be built step by step:
- Choose random values for x1 and y1. section 38.2
- Choose a size, then calculate x2 as x1 plus size and y2 as y1 plus size. section 38.2
- Store the four values together and give them to the canvas when creating the rectangle. section 38.2
Moving a rectangle
To move a player upward, subtract 10 from the y-coordinates for both corners. To move it right, add 10 to the x-coordinates. Update the canvas with the changed coordinate values. section 38.3
Listing 38.2. A class for the player
import random
class Player(object):
def __init__(self, canvas, color): #1
self.color = color #2
size = random.randint(1,100) #3
x1 = random.randint(100,700) #4
y1 = random.randint(100,700) #5
x2 = x1+size #6
y2 = y1+size #7
self.coords = [x1, y1, x2, y2] #8
self.piece = canvas.create_rectangle(self.coords) #9
canvas.itemconfig(self.piece, fill=color) #10
Inspect the player class to see coordinates randomly generated, stored in a list, and passed to create_rectangle. section 38.2
Listing 38.4. How to move a shape inside the canvas
class Player(object):
def __init__(self, canvas, color):
size = random.randint(1,100)
x1 = random.randint(100,700)
y1 = random.randint(100,700)
x2 = x1+size
y2 = y1+size
self.color = color
self.coords = [x1, y1, x2, y2]
self.piece = canvas.create_rectangle(self.coords, tags=color)
canvas.itemconfig(self.piece, fill=color)
def move(self, direction): #1
if direction == 'u': #2
self.coords[1] -= 10 #3
self.coords[3] -= 10 #3
canvas.coords(self.piece, self.coords) #4
if direction == 'd':
self.coords[1] += 10
self.coords[3] += 10
canvas.coords(self.piece, self.coords)
if direction == 'l':
self.coords[0] -= 10
self.coords[2] -= 10
canvas.coords(self.piece, self.coords)
if direction == 'r':
self.coords[0] += 10
self.coords[2] += 10
canvas.coords(self.piece, self.coords)
Inspect the move method to follow coordinate changes for each direction and the subsequent canvas update. section 38.3




