Home  >  Article  >  Backend Development  >  Write a 2048 mini game without interface in Python

Write a 2048 mini game without interface in Python

高洛峰
高洛峰Original
2017-03-02 16:11:431225browse

When the game 2048 became popular, I happened to write one in another language. Now that I am learning python, I just remembered and decided to write a 2048 in python. Since I have never learned the interface programming in python, I wrote an extremely Simple no interface 2048. The principle and implementation of the game 2048 are not difficult. It can be used to practice. If you don’t know this game, you can check it online or download it to your mobile phone to play. I won’t go into the principle. I know that if you don’t put a picture, no one will be interested at all. Let’s first put a picture of the game, and then we will explain how to implement it step by step using the most basic knowledge.

Write a 2048 mini game without interface in Python

1. Generate a 4*4 matrix

The first part of the game The first step is to generate a 4*4 matrix as the main interface of our game. In fact, it is relatively simple to say. The most primitive method is used here, which is to print it out directly using

print. First we need to generate a 4*4 two-dimensional list of all 0s, and then use some characters like '┌ ├└,┤,┘┐│,─,┬,┴' to form our border. Let's take a look. Implementation of the code

matix=[[ for i in range()] for i in range()]    # 用列表推导式初始化生成一个*的列表,列表元素全为 
# notzero函数的作用:游戏界面上非零的时候才显示,当为的时候,让其显示空,
def notzero(s):                    
  return s if s!= else ''             # 非零的话返回本身,否则返回 ''
def display():                        # 显示界面函数,用┌ ├└,┤,┘┐│,─,┬,┴ 等显示边框,中间显示*矩阵里的的元素
  print("\r\
┌──┬──┬──┬──┐\n\
│%s│%s│%s│%s│\n\
├──┬──┬──┬──┤\n\
│%s│%s│%s│%s│\n\
├──┬──┬──┬──┤\n\
│%s│%s│%s│%s│\n\
├──┬──┬──┬──┤\n\
│%s│%s│%s│%s│\n\
└──┴──┴──┴──┘"\
%(notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),\
 notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),\
 notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),notzero(matix[][]), \
 notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),notzero(matix[][]),)
     )
display()

Let’s take a look at the effect of the above code. Do you feel that the framework of a game has been set up? Due to the initialization , the matrix elements are all zero, and the picture below does not show 0. Isn’t it very simple? We have built a game interface, but after all, we have never learned the interface, so don’t complain about how ugly this interface is. Haha.

Write a 2048 mini game without interface in Python                                                               

2. Initialization to generate random numbers
Every time this game starts will randomly generate two random numbers 2 or 4 in the above matrix. So how do we generate a random number 2 or 4 at a random position in the above matrix? Of course, we use what we learned before The random module and pmod(), let's take a look at how to use the random module to implement a function.


def init():                      # 初始化矩阵
  initNumFlag = 
  while :
    k = if random.randrange(, ) > else  # 当生成随机数大于的时候k=否则k= 生成和的概率为:
    s = pmod(random.randrange(, ), )    # 生成矩阵初始化的下标 比如pmod(,)的话,s为(,)正好可以作为矩阵下标
    if matix[s[]][s[]] == :          # 只有当其值不为的时候才赋值,避免第二个值重复
      matix[s[]][s[]] = k
      initNumFlag += 
      if initNumFlag == :           # 当initNumFlag== 的话表示矩阵里两个随机数都已经生成了,退出循环
        break
init()
display( )

Let’s take a look at the effect of the above code. Have we generated two numbers at two random positions? If you have time Try it, and you can see that each time it is executed, the position on the matrix is ​​different, and the number that appears each time is also different. Because I set the probability of 2:4 to 9:1, so 2 appears most of the time. This is also what the game needs. At this point, the matrix can already be moved, and the game's functions can be said to be half completed.


Write a 2048 mini game without interface in Python

3. Implementation of the game logic part
If you have played this game You will know that every time you move up, down, left, and right in the game, for example, if you move down, all the numbers will move downward. If you encounter the same number, it will become a new number, such as if 2 and 2 meet. , 4 will be generated, and then a 2 or 4 will be randomly generated at other positions. Similarly, if 4 and 4 meet, 8 will be generated. The game will be successful until the 2048 is synthesized, or the numbers in the matrix cannot be moved. It's Game Over. Of course, if we play games on our mobile phones, we can slide all the numbers in one direction with just a swipe. However, there is no interface here and the conditions are difficult, so we can only read the letters entered by the user from the console and then come in one by one. To determine where the user has moved, we need to write 4 functions to handle the user's up, down, left, and right movements respectively, and let the latter function handle how to add a random number after each user moves. Let's write a piece of pseudo code to explain the process.


def addRandomNum():            #每次移动后随机在矩阵中在生成一个数
  pass        
def moveDown():              #向上移动的处理函数
  pass<br>  addRandomNum()             #移动处理完成后,随机生成一个数
def moveLeft():               #向左移动的处理函数
  pass
  addRandomNum()
def moveUp():                #向上移动的处理函数
  pass
  addRandomNum()
def moveRight():              #向右移动的处理函数
  pass
  addRandomNum()
def main():
  while flag:                          #定义一个死循环,不断读入用户的输入,然后在做判断,看是向哪里移动
    d = input(&#39; (↑:w) (↓:s) (←:a) (→:d),q(uit) :“)
    if d == &#39;a&#39;:
      moveLeft() 
    elif d == &#39;s&#39;:
      moveDown()
    elif d == &#39;w&#39;:
      moveUp()
    elif d == &#39;d&#39;:
      moveRight()
    elif d == &#39;q&#39;:
      break
    else:
      pass

The above is a piece of pseudo code for understanding. Let’s take a look at how to implement the movement processing function. This is the most difficult to handle in the entire game. part, once this part is completed, the entire game will basically be implemented. Here I take the downward movement processing function as an example. Everything else is the same. When the user input moves downward, all the numbers will move downward. Move, if you encounter the same number and want to merge, the square with the number moves to the square without the number. This needs to be implemented with a loop. There are 4 columns, so the outermost loop has 4 times. Each column needs to be looped. Let’s take a look at how to implement it.

def addRandomNum():                        # 跟初始化生成随机数一样,只不过这里只是生成一个随机数
  while :
    k = if random.randrange(, ) > else 
    s = pmod(random.randrange(, ), )
    if matix[s[]][s[]] == :
      matix[s[]][s[]] = k
      break
  display()                           # 随机数添加完成后就直接调用显示函数,直接显示一下游戏界面
def moveDown():                                #处理向下移动的函数
  for i in range():                            #外层次循环处理例,内层两个层循环,来处理相邻的两个数
    for j in range(, , -):
      for k in range(j - , -, -):
        if matix[k][i] > :                    # 从最下面的数开始处理相邻的两个数
          if matix[j][i] == :
            matix[j][i] = matix[k][i]            # 如果下面的数为空,上面的数字不为空就移动上面的数为下面的数
            matix[k][i] = 
          elif matix[j][i] == matix[k][i]:          # 如果相邻的两个数相等的话,就和并,并把上面的输置零,下面的数变成两倍
            matix[j][i] *= 
            matix[k][i] = 
          break
  addRandomNum()                              # 移动完成后再随机生成一个数

写完了向下移动的处理函数,那么向其他方向的移动函数也一样,照着写,就可以,到这里游戏中最难的部分就完成,可以说胜利就在眼前了,好了在这之前,我们还需要处理一下其他问题,那就是每次移动后都要检查,游戏是不是Game Over了,还有就是定义一个变量来纪录分数了,这些实现起来都比较简单。

四、游戏纪录分数和检查游戏是否结束

  游戏结束的标志是矩阵中所有的数都不为0,而且所有相邻的数都不能合并,根据这个我们就可以来写一个函数来判断游戏是否GG,至于分数纪录,我们只需定义一个变量,然后每次有何并的时候,就加上一定的分数即可。下面我们来看检查函数的实现。

def check():            
  for i in range(4):        #按每一排循环4 次
    for j in range(3):      # 如果矩阵中有0存在,或者有相邻的数就表示游戏还可以继续经行,否则就是GG
      if matix[i][j] == 0 or matix[i][j] == matix[i][j + 1] or matix[j][i] == matix[j + 1][i]:
        return True
  else:
    return False

五、完整游戏源码  

  完成了上面的部分,整个游戏的过程就实现了,下面附上整个游戏的源码。游戏还有很多不够完善的地方,比如说游戏中如果出现2048的话,就表示玩家胜利,游戏结束,但是我这里没有做处理,所以这个游戏可以一直玩到4096....没有结束,除非你游戏中GG了,要处理也很简单,还可以将矩阵存在文件中,完成一个游戏存档的功能。有兴趣的话大家去实现一下。

import random
score = 0                         # 纪录游戏的分数
matix = [[0 for i in range(4)] for i in range(4)] # 初始化生成一个4*4的列表
def notzero(s):
  return s if s != 0 else &#39;&#39;
def display():
  print("\r\
     ┌──┬──┬──┬──┐\n\
     │%4s│%4s│%4s│%4s│\n\
     ├──┬──┬──┬──┤\n\
     │%4s│%4s│%4s│%4s│\n\
     ├──┬──┬──┬──┤\n\
     │%4s│%4s│%4s│%4s│\n\
     ├──┬──┬──┬──┤\n\
     │%4s│%4s│%4s│%4s│\n\
     └──┴──┴──┴──┘" \
     % (notzero(matix[0][0]), notzero(matix[0][1]), notzero(matix[0][2]), notzero(matix[0][3]), \
       notzero(matix[1][0]), notzero(matix[1][1]), notzero(matix[1][2]), notzero(matix[1][3]), \
       notzero(matix[2][0]), notzero(matix[2][1]), notzero(matix[2][2]), notzero(matix[2][3]), \
       notzero(matix[3][0]), notzero(matix[3][1]), notzero(matix[3][2]), notzero(matix[3][3]),)
     )
def init():                               # 初始化矩阵
  initNumFlag = 0
  while 1:
    k = 2 if random.randrange(0, 10) > 1 else 4       # 随机生成 2 或 4
    s = pmod(random.randrange(0, 16), 4)          # 生成矩阵初始化的下标
    if matix[s[0]][s[1]] == 0:                  # 只有当其值不为0的时候才赋值,避免第二个值重复
      matix[s[0]][s[1]] = k
      initNumFlag += 1
      if initNumFlag == 2:
        break
  display()
def addRandomNum():                        #处理完移动后添加一个新的随机数
  while 1:
    k = 2 if random.randrange(0, 10) > 1 else 4
    s = pmod(random.randrange(0, 16), 4)
    if matix[s[0]][s[1]] == 0:
      matix[s[0]][s[1]] = k
      break
  display()
def check():                            #检查游戏是否GG
  for i in range(4):
    for j in range(3):
      if matix[i][j] == 0 or matix[i][j] == matix[i][j + 1] or matix[j][i] == matix[j + 1][i]:
        return True
  else:
    return False
def moveRight():                         # 向右移动处理函数
  global score
  for i in range(4):
    for j in range(3, 0, -1):
      for k in range(j - 1, -1, -1):
        if matix[i][k] > 0:
          if matix[i][j] == 0:
            matix[i][j] = matix[i][k]
            matix[i][k] = 0
          elif matix[i][j] == matix[i][k]:
            matix[i][j] *= 2
            score += matix[i][j]       #将当前数作为score加上
            matix[i][k] = 0
          break
  addRandomNum()
def moveUp():
  global score
  for i in range(4):
    for j in range(3):
      for k in range(j + 1, 4):
        if matix[k][i] > 0:
          if matix[j][i] == 0:
            matix[j][i] = matix[k][i]
            matix[k][i] = 0
          elif matix[k][i] == matix[j][i]:
            matix[j][i] *= 2
            score += matix[j][i]
            matix[k][i] = 0
          break
  addRandomNum()
def moveDown():
  global score
  for i in range(4):
    for j in range(3, 0, -1):
      for k in range(j - 1, -1, -1):
        if matix[k][i] > 0:
          if matix[j][i] == 0:
            matix[j][i] = matix[k][i]
            matix[k][i] = 0
          elif matix[j][i] == matix[k][i]:
            matix[j][i] *= 2
            score += matix[j][i]
            matix[k][i] = 0
          break
  addRandomNum()
def moveLeft():
  global score
  for i in range(4):
    for j in range(3):
      for k in range(1 + j, 4):
        if matix[i][k] > 0:
          if matix[i][j] == 0:
            matix[i][j] = matix[i][k]
            matix[i][k] = 0
          elif matix[i][j] == matix[i][k]:
            matix[i][j] *= 2
            score += matix[i][j]
            matix[i][k] = 0
          break
  addRandomNum()
def main():
  print("    \033[33;1mWelcome to the Game of 2048!\033[0m")
  flag = True
  init()
  while flag:                                    #循环的标志
    print(&#39;        \033[33;1m You Score:%s\033[0m&#39; % (score))
    d = input(&#39;\033[33;1m (↑:w) (↓:s) (←:a) (→:d),q(uit) :\033[0m&#39;)  #不断处理用户输入
    if d == &#39;a&#39;:                                  
      moveLeft()
      if not check():                             #检查游戏是否GG
        print(&#39;GG&#39;)
        flag = False                             #GG的话直接退出
    elif d == &#39;s&#39;:
      moveDown()
      if not check():
        print(&#39;GG&#39;)
        flag = False
    elif d == &#39;w&#39;:
      moveUp()
      if not check():
        print(&#39;GG&#39;)
        flag = False
    elif d == &#39;d&#39;:
      moveRight()
      if not check():
        print(&#39;GG&#39;)
        flag = False
    elif d == &#39;q&#39;:                          # 退出
      break
    else:                                # 对用户的其他输入不做处理
      pass
if __name__ == &#39;__main__&#39;:
  main()

最后在附上一张图片最为结束

 Write a 2048 mini game without interface in Python  

以上所述是小编给大家介绍的用Write a 2048 mini game without interface in Python,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Write a 2048 mini game without interface in Python相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn