# Python实现超级玛丽游戏系列教程02玛丽行走

### 行走

constants.py

``````STAND = 'standing'
WALK = 'walk'

SMALL_ACCEL = .2
SMALL_TURNAROUND = .35
``````

``````    def update(self, keys):
self.handle_state(keys)
self.update_position()
self.animation()

def update_position(self):
self.rect.x += self.x_vel
self.rect.y += self.y_vel

def handle_state(self, keys):
if self.state == c.STAND:
self.standing(keys)
elif self.state == c.WALK:
self.walking(keys)

def animation(self):
if self.facing_right:
self.image = self.right_frames[self.frame_index]
else:
self.image = self.left_frames[self.frame_index]

self.right_frames.append(
self.get_image(178, 32, 12, 16))  # right
self.right_frames.append(
self.get_image(80, 32, 15, 16))  # right walking 1
self.right_frames.append(
self.get_image(99, 32, 15, 16))  # right walking 2
self.right_frames.append(
self.get_image(114, 32, 15, 16))  # right walking 3
self.right_frames.append(
self.get_image(144, 32, 16, 16))  # right jump
self.right_frames.append(
self.get_image(130, 32, 14, 16))  # right skid

# The left image frames are numbered the same as the right
# frames but are simply reversed.

for frame in self.right_frames:
new_image = pg.transform.flip(frame, True, False)
self.left_frames.append(new_image)
``````

``````   def standing(self, keys):
self.frame_index = 0
self.x_vel = 0
self.y_vel = 0

if keys[pg.K_LEFT]:
self.facing_right = False
self.state = c.WALK
elif keys[pg.K_RIGHT]:
self.facing_right = True
self.state = c.WALK
else:
self.state = c.STAND

def walking(self, keys):
if self.frame_index == 0:
self.frame_index += 1
else:
if self.frame_index < 3:
self.frame_index += 1
else:
self.frame_index = 1

if keys[pg.K_LEFT]:
self.facing_right = False
self.x_accel = c.SMALL_ACCEL

#向左速度是负的，如果没达到最小的负的速度，继续向左
# 比如 -3 > -4，那就继续减小
if self.x_vel > (self.max_x_vel * -1):
self.x_vel -= self.x_accel

elif keys[pg.K_RIGHT]:
self.facing_right = True
self.x_accel = c.SMALL_ACCEL

if self.x_vel < self.max_x_vel:
self.x_vel += self.x_accel

``````