|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
020-游戏中角色移动-闭包
问题1:当 move = create() 这里赋值之后,为什么 move([1, 0], 10) 要这么写?
(我可以理解这三个数字 1:x轴正方向 0:y轴不动 10:移动十步)
但是为什么1,0,10,这3个值怎么赋给函数里的四个变量呢?
定义-函数
- def create(pos_x=0, pos_y=0): #这里有 pos_x=0, pos_y=0 两个变量
- def moving(direction, step): #这里也有 direction, step 两个变量
复制代码
调用-输出
- move = create()
- print('向右移动10步后,位置是:', move([1, 0], 10))
复制代码
问题2:
我想删掉 move = create() 这句话,然后在 print 里面直接调用 create 函数
但是以下这两个写法运行之后 都报错了,该怎么修改,才能直接在 print 里面调用呢?
- print('向右移动10步后,位置是:', create(1,0)(1,20) )
复制代码
- print('向右移动10步后,位置是:', create[1,0][1,20] )
复制代码
这是最原始的程序(供大家参考) 希望大神能来解答
- origin = (0, 0) # 原点
- legal_x = [-100, 100] # x轴的移动范围
- legal_y = [-100, 100] # y轴的移动范围
- 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
- new_y = pos_y + direction[1] * step
- # 检查移动后是否超出x轴边界
- if new_x < legal_x[0]:
- pos_x = legal_x[0] - (new_x - legal_x[0])
- elif new_x > legal_x[1]:
- pos_x = legal_x[1] - (new_x - legal_x[1])
- else:
- pos_x = new_x
- # 检查移动后是否超出y轴边界
- if new_y < legal_y[0]:
- pos_y = legal_y[0] - (new_y - legal_y[0])
- elif new_y > legal_y[1]:
- pos_y = legal_y[1] - (new_y - legal_y[1])
- else:
- pos_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))
复制代码 |
|