| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
uznh1227
8年前发布

Python实现小游戏--2048

   <h2>开篇语</h2>    <p>今天是笔者奶奶生日,昨天为此准备了不少事情,也因此花费了很多时间,今天上午接待客人,下午送我年迈的姑奶奶回家。等我抽出身来看代码已经是三点的事情了。再加上还有个“问题xx”要教导,真正开始认真看代码,已经是四点咯。然后看到五点多,爸爸叫我吃饭,我去,还没跑步,所以又是一番鸡飞狗跳。跑完回来一边压腿,一边看家人吃饭,也是醉醉的。虽然有点跑题,但是我还是要拿我的跑步的图来放一放~~~</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/cab4e918d7ead47ac165f2d76c032573.jpg"></p>    <p>这是定向越野~地面泥泞,公路上大大小小的石子,跑起来真是百曲千回~</p>    <p>第二天了,继续坚持!yeah!</p>    <h2>正文</h2>    <p>本次是我对于Python实现2048这个曾经风靡一时的小游戏的代码解读</p>    <p><img src="https://simg.open-open.com/show/abe5b6494cd97e4264ebe55c65f21de2.png"></p>    <p>工作环境</p>    <p>一、主逻辑图</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/c68cfe65ab0404d7ccfa266a36b9f9e4.jpg"></p>    <p>逻辑图解:黑色是逻辑层,蓝色是外部方法,红色是类内方法,稍后即可知道~</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0554db61187d50852b7e81c95ae26e6d.png"></p>    <p>状态机。。。游戏概念,出自实验楼</p>    <p>下面容我逐行解释主逻辑main()函数,并且在其中穿叉外部定义的函数与类。</p>    <p>二、主逻辑代码解读(完整代码见文末)</p>    <p>主逻辑main如下,之后的是对主函数中的一些方法的解读:</p>    <pre>  <code class="language-python">def main(stdscr):      def init():          #重置游戏棋盘          game_field.reset()          return 'Game'        def not_game(state):          #画出 GameOver 或者 Win 的界面          game_field.draw(stdscr)          #读取用户输入得到action,判断是重启游戏还是结束游戏          action = get_user_action(stdscr)          responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环          responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态          return responses[action]        def game():          #画出当前棋盘状态          game_field.draw(stdscr)          #读取用户输入得到action          action = get_user_action(stdscr)            if action == 'Restart':              return 'Init'          if action == 'Exit':              return 'Exit'          if game_field.move(action): # move successful              if game_field.is_win():                  return 'Win'              if game_field.is_gameover():                  return 'Gameover'          return 'Game'          state_actions = {              'Init': init,              'Win': lambda: not_game('Win'),              'Gameover': lambda: not_game('Gameover'),              'Game': game          }        curses.use_default_colors()      game_field = GameField(win=32)        state = 'Init'        #状态机开始循环      while state != 'Exit':          state = state_actions[state]()</code></pre>    <p>逐条解读(代码框内会标注是来自外部,无标注则是来自内部):定义主函数</p>    <pre>  <code class="language-python">def main(stdscr):</code></pre>    <pre>  <code class="language-python">def init():          #重置游戏棋盘          game_field.reset()</code></pre>    <p>reset出自外部定义的类, game_field=GameField 的一个方法reset:</p>    <pre>  <code class="language-python">外部:    def reset(self):          if self.score > self.highscore:              self.highscore = self.score          self.score = 0          self.field = [[0 for i in range(self.width)] for j in range(self.height)]          self.spawn()          self.spawn()  #其中highscore为程序初始化过程中定义的一个变量。记录你win游戏的最高分数记录。</code></pre>    <pre>  <code class="language-python">return 'Game'</code></pre>    <p>返回一个游戏进行中的状态。 game_field=GameField 状态在后面有定义:</p>    <pre>  <code class="language-python">主函数底部定义:   state_actions = {              'Init': init,              'Win': lambda: not_game('Win'),              'Gameover': lambda: not_game('Gameover'),              'Game': game          }</code></pre>    <pre>  <code class="language-python">def not_game(state):          #画出 GameOver 或者 Win 的界面          game_field.draw(stdscr)</code></pre>    <p>draw是导入的类 game_field=GameField 中的方法:</p>    <pre>  <code class="language-python">#来自外部类      def draw(self, screen):          help_string1 = '(W)Up (S)Down (A)Left (D)Right'          help_string2 = '     (R)Restart (Q)Exit'          gameover_string = '           GAME OVER'          win_string = '          YOU WIN!'  #定义各个字符串          def cast(string):              screen.addstr(string + '\n')            def draw_hor_separator():              line = '+' + ('+------' * self.width + '+')[1:]              separator = defaultdict(lambda: line)              if not hasattr(draw_hor_separator, "counter"):                  draw_hor_separator.counter = 0              cast(separator[draw_hor_separator.counter])              draw_hor_separator.counter += 1            def draw_row(row):              cast(''.join('|{: ^5} '.format(num) if num > 0 else '|      ' for num in row) + '|')            screen.clear()          cast('SCORE: ' + str(self.score))          if 0 != self.highscore:              cast('HGHSCORE: ' + str(self.highscore))          for row in self.field:              draw_hor_separator()              draw_row(row)          draw_hor_separator()          if self.is_win():              cast(win_string)          else:              if self.is_gameover():                  cast(gameover_string)              else:                  cast(help_string1)          cast(help_string2)  #这里面的draw方法的字函数我就不做多的解释了,很简单的一些概念。  #但是又运用到了很优秀的精简代码。  #有的地方建议去查一下python的一些高级概念,我就不做多的介绍了。</code></pre>    <p>这里面的draw方法的字函数我就不做多的解释了,很简单的一些概念。</p>    <p>但是又运用到了很优秀的精简代码。</p>    <p>有的地方建议去查一下python的一些高级概念,我就不做多的介绍了。</p>    <pre>  <code class="language-python">#读取用户输入得到action,判断是重启游戏还是结束游戏          action = get_user_action(stdscr)</code></pre>    <p>读取用户行为,函数来自于代码初始的定义</p>    <pre>  <code class="language-python">#来自外部定义的函数  def get_user_action(keyboard):          char = "N"      while char not in actions_dict:              char = keyboard.getch()      return actions_dict[char]</code></pre>    <p>在结尾处,也即是主函数执行的第三步,定义了 state = state_actions[state]() 这一实例:</p>    <pre>  <code class="language-python">#主函数底部:      state = 'Init'        #状态机开始循环      while state != 'Exit':          state = state_actions[state]()</code></pre>    <pre>  <code class="language-python">responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环          responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态          return responses[action]</code></pre>    <pre>  <code class="language-python">def game():          #画出当前棋盘状态          game_field.draw(stdscr)          #读取用户输入得到action          action = get_user_action(stdscr)            if action == 'Restart':              return 'Init'          if action == 'Exit':              return 'Exit'          if game_field.move(action): # move successful              if game_field.is_win():                  return 'Win'              if game_field.is_gameover():                  return 'Gameover'          return 'Game'  #game()函数的定义类似于上面已经讲过的not_game(),只是game()有了内部循环  #即如果不是Restart/Exit或者对move之后的状态进行判断,如果不是结束游戏,就一直在game()内部循环。</code></pre>    <p>game()函数的定义类似于上面已经讲过的not_game(),只是game()有了内部循环,即如果不是Restart/Exit或者对move之后的状态进行判断,如果不是结束游戏,就一直在game()内部循环。</p>    <pre>  <code class="language-python">state_actions = {              'Init': init,              'Win': lambda: not_game('Win'),              'Gameover': lambda: not_game('Gameover'),              'Game': game                          }        curses.use_default_colors()      game_field = GameField(win=32)          state = 'Init'        #状态机开始循环      while state != 'Exit':          state = state_actions[state]()  #此处的意思是:state=state_actions[state] 可以看做是:  #state=init()或者state=not_game(‘Win’)或者是另外的not_game(‘Gameover’)/game()</code></pre>    <p>此处的意思是:state=state_actions[state] 可以看做是:state=init()或者state=not_game(‘Win’)或者是另外的not_game(‘Gameover’)/game()</p>    <h2>结束语</h2>    <p>废话不多说,上一个我的成功的图,另外,可以通过设置最后几行中的 win=32 来决定你最终获胜的条件!</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/dbeda3b7db135ea8f1f200d7867a6e06.gif"></p>    <p>2048.gif</p>    <p>三、完整代码</p>    <pre>  <code class="language-python">#-*- coding:utf-8 -*-  import curses  from random import randrange, choice # generate and place new tile  from collections import defaultdict  letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']  actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']  actions_dict = dict(zip(letter_codes, actions * 2))  def transpose(field):      return [list(row) for row in zip(*field)]    def invert(field):      return [row[::-1] for row in field]    class GameField(object):      def __init__(self, height=4, width=4, win=2048):          self.height = height          self.width = width          self.win_value = win          self.score = 0          self.highscore = 0          self.reset()        def reset(self):          if self.score > self.highscore:              self.highscore = self.score          self.score = 0          self.field = [[0 for i in range(self.width)] for j in range(self.height)]          self.spawn()          self.spawn()        def move(self, direction):          def move_row_left(row):              def tighten(row): # squeese non-zero elements together                  new_row = [i for i in row if i != 0]                  new_row += [0 for i in range(len(row) - len(new_row))]                  return new_row                def merge(row):                  pair = False                  new_row = []                  for i in range(len(row)):                      if pair:                          new_row.append(2 * row[i])                          self.score += 2 * row[i]                          pair = False                      else:                          if i + 1 < len(row) and row[i] == row[i + 1]:                              pair = True                              new_row.append(0)                          else:                              new_row.append(row[i])                  assert len(new_row) == len(row)                  return new_row              return tighten(merge(tighten(row)))            moves = {}          moves['Left']  = lambda field:                              \                  [move_row_left(row) for row in field]          moves['Right'] = lambda field:                              \                  invert(moves['Left'](invert(field)))          moves['Up']    = lambda field:                              \                  transpose(moves['Left'](transpose(field)))          moves['Down']  = lambda field:                              \                  transpose(moves['Right'](transpose(field)))            if direction in moves:              if self.move_is_possible(direction):                  self.field = moves[direction](self.field)                  self.spawn()                  return True              else:                  return False        def is_win(self):          return any(any(i >= self.win_value for i in row) for row in self.field)        def is_gameover(self):          return not any(self.move_is_possible(move) for move in actions)        def draw(self, screen):          help_string1 = '(W)Up (S)Down (A)Left (D)Right'          help_string2 = '     (R)Restart (Q)Exit'          gameover_string = '           GAME OVER'          win_string = '          YOU WIN!'          def cast(string):              screen.addstr(string + '\n')            def draw_hor_separator():              line = '+' + ('+------' * self.width + '+')[1:]              separator = defaultdict(lambda: line)              if not hasattr(draw_hor_separator, "counter"):                  draw_hor_separator.counter = 0              cast(separator[draw_hor_separator.counter])              draw_hor_separator.counter += 1            def draw_row(row):              cast(''.join('|{: ^5} '.format(num) if num > 0 else '|      ' for num in row) + '|')            screen.clear()          cast('SCORE: ' + str(self.score))          if 0 != self.highscore:              cast('HGHSCORE: ' + str(self.highscore))          for row in self.field:              draw_hor_separator()              draw_row(row)          draw_hor_separator()          if self.is_win():              cast(win_string)          else:              if self.is_gameover():                  cast(gameover_string)              else:                  cast(help_string1)          cast(help_string2)        def spawn(self):          new_element = 4 if randrange(100) > 89 else 2          (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])          self.field[i][j] = new_element        def move_is_possible(self, direction):          def row_is_left_movable(row):               def change(i): # true if there'll be change in i-th tile                  if row[i] == 0 and row[i + 1] != 0: # Move                      return True                  if row[i] != 0 and row[i + 1] == row[i]: # Merge                      return True                  return False              return any(change(i) for i in range(len(row) - 1))            check = {}          check['Left']  = lambda field:                              \                  any(row_is_left_movable(row) for row in field)            check['Right'] = lambda field:                              \                   check['Left'](invert(field))            check['Up']    = lambda field:                              \                  check['Left'](transpose(field))            check['Down']  = lambda field:                              \                  check['Right'](transpose(field))            if direction in check:              return check[direction](self.field)          else:              return False  def main(stdscr):      def init():          #重置游戏棋盘          game_field.reset()          return 'Game'      def not_game(state):          #画出 GameOver 或者 Win 的界面          game_field.draw(stdscr)          #读取用户输入得到action,判断是重启游戏还是结束游戏          action = get_user_action(stdscr)          responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环          responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态          return responses[action]        def game():          #画出当前棋盘状态          game_field.draw(stdscr)          #读取用户输入得到action          action = get_user_action(stdscr)            if action == 'Restart':              return 'Init'          if action == 'Exit':              return 'Exit'          if game_field.move(action): # move successful              if game_field.is_win():                  return 'Win'              if game_field.is_gameover():                  return 'Gameover'          return 'Game'          state_actions = {              'Init': init,              'Win': lambda: not_game('Win'),              'Gameover': lambda: not_game('Gameover'),              'Game': game          }      curses.use_default_colors()      game_field = GameField(win=32)      state = 'Init'      #状态机开始循环      while state != 'Exit':          state = state_actions[state]()  curses.wrapper(main)</code></pre>    <h2> </h2>    <p> </p>    <p>来自:http://www.jianshu.com/p/7a3a7545d2fb</p>    <p> </p>    
 本文由用户 uznh1227 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1484707181391.html
Python 游戏开发 Python开发