|
发表于 2022-8-21 00:39:33
|
显示全部楼层
本帖最后由 jackz007 于 2022-8-21 10:34 编辑
这个代码在我这里没有任何问题
- origin = (0, 0) # 原点
- legal_x = [-100, 100] # x轴的移动范围
- legal_y = [-100, 100] # y轴的移动范围
- def foo(p , v):
- if v < p[0]:
- v = p[1] - (p[0] - v)
- elif v > p[1]:
- v = p[0] + (v - p[1])
- return v
- def create(pos_x = 0 , pos_y = 0):
- # 初始化位于原点为主
- def moving(direction , step):
- # direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
- # step参数设置移动的距离
- nonlocal pos_x, pos_y
- new_x = pos_x + direction[0] * (step % (legal_x[1] - legal_x[0]))
- new_y = pos_y + direction[1] * (step % (legal_y[1] - legal_y[0]))
- pos_x , pos_y = foo(legal_x , new_x) , foo(legal_y , new_y)
- return pos_x , pos_y
- return moving
-
- move = create()
- print('向右移动 10步后,位置是:' , move([ 1 , 0] , 10))
- print('向上移动130步后,位置是:' , move([ 0 , 1] , 130))
- print('向左移动 10步后,位置是:' , move([-1 , 0] , 10))
- print('向右移动570步后,位置是:' , move([ 1 , 0] , 570))
- print('向上移动330步后,位置是:' , move([ 0 , 1] , 330))
- print('向左移动420步后,位置是:' , move([-1 , 0] , 420))
复制代码
运行实况:
- D:\[00.Exerciese.2022]\Python>python x.py
- 向右移动 10步后,位置是: (10, 0)
- 向上移动130步后,位置是: (10, -70)
- 向左移动 10步后,位置是: (0, -70)
- 向右移动570步后,位置是: (-30, -70)
- 向上移动330步后,位置是: (-30, 60)
- 向左移动420步后,位置是: (-50, 60)
- D:\[00.Exerciese.2022]\Python>
复制代码 |
|