Python project development case (two)-simple gomoku game (console version)

2. Simple Gomoku Game (Console Version)

2.1 Demand analysis

The Gobang game developed in this section is a console version, so the game should have the following functions:

  • The chessboard can be printed cyclically;
  • You can play stand-alone;
  • When one of the two sides wins, print the victory board and the winner;
  • Determine whether the chess piece exceeds the range of the chessboard;
  • Determine whether there is a chess piece at the specified coordinate position;
  • The interface is beautiful and the prompts are obvious.

2.2 Game design

2.2.1 Game function structure

2.2.2 Game business process

        The business process of the simple Gobang game (console version) is shown in the figure below.

2.3 Essentials for game development

2.3.1 Game development environment

The development and operating environment of this game are as follows:

  • Operating system: Windows7, Windows10, etc.;
  • Python version: Python3.7;
  • Development tools: Pycharm.

2.3.2 Folder organization structure

        The simple gobang game (console version) has only one gobang.py file, which represents the code file of the software, and all the codes that implement the gobang logic are in this file.

2.4 Checkerboard settings

2.4.1 Implementation process of board setting

        The board setting implementation process and the key technologies used are shown in the figure.

2.4.2 Initialize the chessboard

        When developing a gomoku game, you first need to initialize the board. The board of gomoku is similar to a two-dimensional list. Therefore, in this program, a two-dimensional list named checkboard is used to store the gomoku board. The code is as follows:

finish = False  #游戏是否结束
flagNum = 1     #当前下棋者标记
flagch = 'a'    #当前下棋者棋子
x = 0           #当前棋子的横坐标
y = 0           #当前棋子的纵坐标
print('\033[1;37;41m------------简易五子棋游戏(控制台版)---------\033[0m')
#棋盘初始化
checkerboard=[]
for i in range(10):
    checkerboard.append([])
    for j in range(10):
        checkerboard[i].append('-')

2.4.3 Print chessboard

        To play chess in the Gobang game, the user first needs to display the Gobang board. Since this program is a console program, directly select the gobang, py file in Pycharn and click the \tiny \trianglerightbutton in the upper right corner of the Pycharn interface to control it in Pycharn Taichung shows a chess board.

        Section 2.4.2 has initialized the Gomoku board, and the next work only needs to print it out. Here, a nested for loop is used to traverse the two-dimensional list storing the Gomoku board, and then it will traverse the elements once. Just output. code show as below:

#打印棋盘
print("\033[1;30;46m-----------------------")
print("  1 2 3 4 5 6 7 8 9 10")                #输出行标号
for i in range(len(checkerboard)):
    print(chr(i+ord('A'))+"",end='');          #输出列标号
    for j in range(len(checkerboard[i])):
        print(checkerboard[i][j]+"",end='')
    print()                                    #换行
print("--------------------------------\033[0m")

2.4.4 Print the victory board and the winner

        When playing the Gobang game, if one party wins, the final board is printed and the winner is output.

        Define a msg() function to output the final victory board and the winner. In this function, the nested for loop is mainly used to output the final victory backgammon board, and the output of the winner is achieved by judging the value of the variable flagNum. The msg() function implementation code is as follows:

def mag():
    #输出最后胜利的棋盘
    print("\033[1;37;41m--------------------------")
    print(" 1 2 3 4 5 6 7 8 9 10")
    for i in range(len(checkerboard)):
        print(chr(i+ord('A'))+"",end='')
        for j in range(len(checkerboard[i])):
            print(checkerboard[i][j]+"",end='')
        print()
    print("--------------------------\033[0m")
    #输出赢家
    if(flagNum == 1):
       print('\033[32m*棋胜利!***\033[0m')
    else:
       print('\033[32mo棋胜利!***\033[0m')

2.4.5 Set different fonts and background colors for the console

2.5 Gobang algorithm

2.5.1 Gobang algorithm analysis

        The game rule of Gobang is to look for pieces of the same type in eight directions with the point of entry as the center. If the number of the same pieces is greater than or equal to 5, it means that the player of this type of piece is the winner. The search direction of gobang pieces is shown in the figure.

                                                                  Figure 1 Determine the shape of a chess piece placed in eight directions

2.5.2 Determine the up, down, left and right direction of a chess piece

        Judging the up, down, left and right direction of the chess piece, mainly to judge whether the four pieces adjacent to the X coordinate or Y coordinate of the chess piece are the chess pieces of the same color, if so, set the finish flag to True, which means the end Play chess in a loop, and then call the msg() function to print the winning board and the winner. code show as below:

#判断棋子左侧
if(y - 4 >= 0):
   if(checkerboard[x][y-1] == flagch
           and checkerboard[x][y-2] == flagch
           and checkerboard[x][y-3] == flagch
           and checkerboard[x][y-4] == flagch):
      finish = True
      msg()


#判断棋子右侧
if(y + 4 <= 9):
   if(checkerboard[x][y+1] == flagch
          and checkerboard[x][y+2] == flagch
          and checkerboard[x][y+3] == flagch
          and checkerboard[x][y+4] == flagch):
      finish = True
      msg()

#判断棋子上方
if(x - 4 >= 0):
   if(checkerboard[x-1][y] == flagch
          and checkerboard[x-2][y] == flagch
          and checkerboard[x-3][y] == flagch
          and checkerboard[x-4][y] == flagch):
      finish = True
      msg()

#判断棋子下方
if(x + 4 <= 9):
   if(checkerboard[x+1][y] == flagch
          and checkerboard[x+2][y] == flagch
          and checkerboard[x+3][y] == flagch
          and checkerboard[x+4][y] == flagch):
      finish = True
      msg()

2.5.3 Determine the diagonal direction of a chess piece

        To determine the diagonal direction of a chess piece, it is mainly to determine whether the 4 chess pieces adjacent to the chess piece coordinates on the diagonal are the same color pieces. If so, set the finish flag to True, that is, end the cycle of chess, and then call The msg() function prints the victory board and the winner. code show as below:

#判断棋子右上方向
if(x - 4 >= 0 and y-4 >=0):
   if(checkerboard[x-1][y-1] == flagch
          and checkerboard[x-2][y-2] == flagch
          and checkerboard[x-3][y-3] == flagch
          and checkerboard[x-4][y-4] == flagch):
      finish = True
      msg()

#判断棋子右下方向
if(x + 4 <= 9 and y-4 >=0):
   if(checkerboard[x+1][y-1] == flagch
          and checkerboard[x+2][y-2] == flagch
          and checkerboard[x+3][y-3] == flagch
          and checkerboard[x+4][y-4] == flagch):
      finish = True
      msg()

#判断棋子左上方向
if(x - 4 >= 0 and y + 4 <= 9):
   if(checkerboard[x-1][y+1] == flagch
          and checkerboard[x-2][y+2] == flagch
          and checkerboard[x-3][y+3] == flagch
          and checkerboard[x-4][y+4] == flagch):
      finish = True
      msg()

#判断棋子左上方向
if(x + 4 <= 9 and y + 4 <= 9):
   if(checkerboard[x+1][y+1] == flagch
          and checkerboard[x+2][y+2] == flagch
          and checkerboard[x+3][y+3] == flagch
          and checkerboard[x+4][y+4] == flagch):
      finish = True
      msg()

2.6 Chess settings

2.6.1 Implementation process of chess setting

        The implementation process of chess setting and the key technologies used are shown in the figure.

2.6.2 Judging the current player

        When playing chess in the Gobang game, there are two opponents, which are shown in different background colors and font colors in the console.

        This program mainly uses a flagNum variable to determine the identities of the opponents. If the variable is 1, the player is "*", otherwise, the player is "o". The implementation code is as follows:

#判断当前下棋者
if flagNum == 1:
   flagch = '*'
   print('\033[1;37;45m请*输入棋子坐标(例如A1):\033[0m',end='')  # 粉字黑底
else:
   flagch = '*'
   print('\033[1;37;42m请o输入棋子坐标(例如J5):\033[0m',end='')  # 黑字绿底

        In addition, after one party has finished playing chess, the value of the flagNum variable needs to be changed to change the player. The code is as follows: 

flagNum *= -1; #更换下棋者标记

2.6.3 Record coordinates of chess pieces

        When the chess function is implemented in the backgammon game, it is mainly by recording the coordinates of the chess pieces to determine where to place it. Here, first use the input() function to record the coordinates of the chess pieces entered, and the coordinates are in the form of "capital letters+1 to 10 numbers" (For example, A1, A is the abscissa, and 1 is the ordinate), then you need to convert the coordinates to X and Y values, and convert the first letter to the X coordinate. You need to use the ord() function to get the ASCII code value corresponding to the letter, and then subtract The ASCII code value of the letter A; and to convert the second number to the Y coordinate, you only need to subtract 1 because the index starts from 0. The code to record the coordinates of a chess piece is as follows:

#输入棋子坐标
str = input()
ch = str[0] #获取第一个字符的大写形式
x = ord(ch) - 65
y = int(str[1]) - 1

2.6.4 Judging the coordinates of chess pieces

        When implementing the Gobang (console version) game, the set board is 10 \tiny \times10, so the input coordinates must be within the board range, if it exceeds the range, the corresponding prompt information will be printed.

        Since the board of Gobang is 10 \tiny \times10, and the board coordinate index starts from 0, as long as the X coordinate or Y coordinate is not within the range of 0-9, it means that the coordinate of the chess piece exceeds the range of the board. The implementation code is as follows:

#判断坐标是否在棋盘之内
if(x < 0 or x > 9 or y < 0 or y > 9 ):
   print('\033[31m***您输入的坐标有误请重新输入!***\033[0m')
   continue

2.6.5 Determine whether there is a chess piece at the specified coordinate position

         In the game of Gobang (console version), if one party has already placed a piece at a coordinate position, the other party cannot play the piece at that position. If it does, a corresponding prompt message should appear.

        The default value of each coordinate position of the Gobang board is "-", and after playing chess, the value will become "*" or "o". Therefore, to determine whether there is a chess piece at the specified coordinate position, you only need to determine whether its value is " -", if it is "-", you can play chess, otherwise, print the corresponding prompt information, the code is as follows:

#判断坐标上是否有棋子
if(checkerboard[x][y] == '-')
   if(flagNum == 1):
      checkerboard[x][y] == '*'
   else:
      checkerboard[x][y] == 'o'
else:
   print('\033[31m******您输入位置已经有其他棋子,请重新输入!\033[0m')
   continue

2.7 Summary

        This chapter mainly uses Python language to develop a simple Gomoku game (console version) project. The core of the project is the implementation algorithm of Gomoku. In addition, the Gomoku game interacts with users in the console. As everyone knows, the console is usually The black background and white font display data. How to have a good user experience in the console is a difficult point in this project. This project solves this difficulty by setting the background color and font color in the print() printing function. Through the study of this chapter, readers should be proficient in the realization algorithm of the Gobang game and be familiar with how to change the background color and font color of the PyCharn console.

Guess you like

Origin blog.csdn.net/weixin_38452841/article/details/108613734
Recommended