游戏中的角色移动:闭包(closure)在实际开发中的作用

                                          游戏中的角色移动:闭包(closure)在实际开发中的作用              

在某种情况下,我们并不方便使用全局变量,所以灵活的使用闭包可以实现替代全局变量。    
例如以下的游戏开发中,我们需要将游戏中角色的移动位置保护起来,不希望被其他函数轻易

可以修改到,所以我们选择使用闭 包操作,参考代码及注释如下:                                            

这里需要注意的一点是:move = create(),如果当 move 变量重新被赋值的话,相应的 pos_x

和 pos_y 也都会被初始化为 0。 

代码如下

  1. origin = (0, 0)         # 原点
  2. legal_x = [-100, 100]   # x轴的移动范围
  3. legal_y = [-100, 100]   # y轴的移动范围
  4. def create(pos_x=0, pos_y=0):
  5. # 初始化位于原点为主    
  6.     def moving(direction, step):
  7.     # direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动
  8.     # step参数设置移动的距离
  9.         nonlocal pos_x, pos_y
  10.         new_x = pos_x + direction[0] * step
  11.         new_y = pos_y + direction[1] * step
  12.         # 检查移动后是否超出x轴边界
  13.         if new_x < legal_x[0]:
  14.             pos_x = legal_x[0] - (new_x - legal_x[0])
  15.         elif new_x > legal_x[1]:
  16.             pos_x = legal_x[1] - (new_x - legal_x[1])
  17.         else:            
  18.             pos_x = new_x
  19.         # 检查移动后是否超出y轴边界
  20.         if new_y < legal_y[0]:
  21.             pos_y = legal_y[0] - (new_y - legal_y[0])
  22.         elif new_y > legal_y[1]:
  23.             pos_y = legal_y[1] - (new_y - legal_y[1])
  24.         else:            
  25.             pos_y = new_y
  26.         return pos_x, pos_y
  27.     return moving
  28.     
  29. move = create()
  30. print('向右移动10步后,位置是:', move([1, 0], 10))
  31. print('向上移动130步后,位置是:', move([0, 1], 130))
  32. print('向左移动10步后,位置是:', move([-1, 0], 10))
  33. ------------------ 运行结果如下 ------------------------------
  34. 向右移动10步后,位置是: (10, 0)
    向上移动130步后,位置是: (10, 70)
    向左移动10步后,位置是: (0, 70)

猜你喜欢

转载自www.cnblogs.com/daodantou/p/10308162.html