Hardware Reference
In-Depth Information
he += and -= operators are used to change the value of a variable by a certain amount: +=
sets the variable to its previous value plus the new value, while -= sets the variable to its
previous value minus the new value. By way of example, snakePosition[0] += 20 is a
shorthand way of writing snakePosition[0] = snakePosition[0] + 20 . he num-
ber in square brackets following the snakePosition variable name is the position in the
list being afected: the irst value in the snakePosition list stores the snake's position
along the X axis, while the second value stores the position along the Y axis. Python begins
counting at zero, so the X axis is controlled with snakePosition[0] and the Y axis with
snakePosition[1] . If the list were longer, additional entries could be afected by increas-
ing the number: [2] , [3] and so on.
Although the snakePosition list is always two values long, another list created at the start
of the program is not: snakeSegments . his list stores the location of the snake's body,
behind the head. As the snake eats raspberries and grows longer, this list increases in size
and provides the diiculty in the game: as the player progresses, it becomes harder to avoid
hitting the body of the snake with the head. If the head hits the body, the snake dies and the
game is over. Type the following line to make the snake's body grow:
snakeSegments.insert(0,list(snakePosition))
his uses the insert instruction to insert a new value into the snakeSegments list: the
current position of the snake. Each time Python reaches this line, it will increase the length
of the snake's body by one segment, and locate that segment at the current position of the
snake's head. To the player, it will look as though the snake is growing. However, you only
want this to happen when the snake eats a raspberry—otherwise the snake will just grow
and grow. Type the following lines:
if snakePosition[0] == raspberryPosition[0] Æ
and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
he irst instruction checks the X and Y coordinates of the snake's head to see if it matches
the X and Y coordinates of the raspberry—the target the player is chasing. If the values
match, the raspberry is considered to have been eaten by the snake—and the raspber-
rySpawned variable is set to 0 . he else instruction tells Python what to do if the raspberry
has not been eaten: pop the earliest value from the snakeSegments list.
Search WWH ::




Custom Search