把一些功能用函数包装起来
创建了两个函数
1:def is_eat_self(nh: Rect, snake_body: list[Rect]):的作用是检查头部矩形与身体有没有产生碰撞 如果产生了碰撞返回False
2:def get_next_pos(direction: int, x: int, y: int, body_size: int):计算出下一个 头部的位置
from pygame import Rect
#名称:eat_self
#功能:检查矩形(nh)是否和snake body
def is_eat_self(nh: Rect, snake_body: list[Rect]):
# 把nh 和 snacke_body 里每一个数去对比, 看是否有碰撞
# 只要产生碰撞 就说明吃到了自己
for body in snake_body:
if nh.colliderect(body):
return True
return False
# 名称 get_next_pos
# 功能: 根据(direction: int, x: int, y: int, body_size: int):
def get_next_pos(direction: int, x: int, y: int, body_size: int):
if direction ==1:
nx = x + body_size# 新头部的 x 坐标
ny = y# 新头部的 y 坐标
if direction == 2:
nx = x# 新头部的 x 坐标
ny = y + body_size # 新头部的 y 坐标
if direction == 3:
nx = x - body_size# 新头部的 x 坐标
ny = y# 新头部的 y 坐标
if direction == 4:
nx = x# 新头部的 x 坐标
ny = y - body_size# 新头部的 y 坐标
return nx, ny
...
浙公网安备 33010602011771号