Using Python to realize simple Gobang game

Time:2019-12-4

Using Python to realize the practice process of simple human-machine mode of Gobang, for your reference, the specific contents are as follows

The first time I wrote a blog, I tried to write it well.

Recently, I was just learning python. Today, I will use some of my own superficial understanding to record the practice of Python simple human-computer Gobang game these days. The following is the understanding of the implementation process (running in CMD):

Main process:*Key content*

-First, the division of modules and classes
-Methods of chessboard and chessboard
-Subdivide the functions in the strategy class, and call the chessboard class and chessboard class
-Write out the way to judge the winning or losing
-Using main function to control the whole game progress

Division of modules and classes

Class division involves object-oriented content. According to the setting of Gobang game, people and machines play chess in one board in turn. One side and five children are connected to win. It is preliminarily divided intoChess pieces, chessboardandPolicy classEach class has one module, and the main module has four modules.

  • The chess class contains the coordinates and colors (cAMP) of the chess pieces, as well as the related get and set methods
  • The chessboard class contains the size and state of the chessboard, and the related get and set methods
  • Functions of chessboard: receive the pieces to be placed, clear the chessboard, print (display) the chessboard, and give the status of the corresponding position
  • Strategy class: a strategy class corresponds to a chessboard class, and a chessboard class is imported into the constructor
  • The functions of strategy class: people put pieces on the board, machines put pieces on the board, and judge the winning or losing of the board

Chessmen and chessboard

chessmanIt is relatively simple. From the point of view of chess pieces, as long as the receiving position and color (cAMP), the outgoing position and color (cAMP) can be used, where the position is packed and passed by tuples

class Chessman(object):
			Initialization
			def __init__(self):
			pass

			def set_pos(self,pos):
			self.pos = pos

			def get_pos(self):
			return self.pos

			def set_color(self,color):
			self.color = color

			def get_color(self):
	return self.color

chessboardYou need to use the chessboard. Before that, you need to set the chessboard
Here, the chessboard is built with a list, which is divided into two layers to realize the position of X and Y. the size of the chessboard is set as a class attribute

Attributes of the genus
			board_size =15
			#Initialize chessboard
			def __init__(self):
	self.__board = [[0 for i in range(0,Chessboard.board_size+1)] for j in range(0,Chessboard.board_size+1)]

Clearing the chessboard is similar

#Clear the chessboard and '+' is the look of the chessboard
			def init_board(self):
			#Ignore row 0
			for i in range(1,Chessboard.board_size+1):
			for j in range(1,Chessboard.board_size+1):
	self.__board[i][j] = '+'

The printing is almost the same. Pay attention to putting the serial number beside the coordinate axis, where the ordinate is 1-15 and the abscissa is a-o

#Print chessboard
			def print_board(self):
			#Print column number
			print(' ', end='')
			for i in range(1,Chessboard.board_size+1):
			c = chr(ord('a') + i-1) 
			#Ord letter to class
			print(c,end='')
			print()
			Chessboard
			for i in range(1,Chessboard.board_size+1):
			if 1<= i <=9:
			print(' ', end='')
			print(i, end='')
			for j in range(1,Chessboard.board_size+1):
			print(self.__board[i][j], end='')
	print()

The effect is as follows

Next is the placement of chess pieces:

This can be divided into two methods: one is to place the incoming color according to the incoming location; the other is to receive the instance object of a chess class, obtain the location and color of the instance, call the first method and pass in the value. Be sure to verify when passing the parameter

#Write the color of the corresponding position
			def set_chess(self,pos, color):
			if not isinstance(pos,tuple):
			Raise runtimeerror ('the first parameter must be a tuple ')
			if pos[0] <= 0 or pos[0] > Chessboard.board_size:
			Raise runtimeerror ('line subscript out of range ')
			if pos[1] <=0 or pos[1] > Chessboard.board_size:
			Raise runtimeerror ('vertical subscript out of range ')
			self.__board[pos[0]][pos[1]] = color 

			#Put the chess object on the chessboard 
			def set_chessman(self,chessman):
			if not isinstance(chessman, Chessman):
			Raise runtimeerror ('wrong type, first argument should be chessman object ')
			pos = chessman.get_pos()
			color = chessman.get_color()
			self.set_chess(pos,color)

The next method to get the color of chessboard according to the position of chessboard is mainly for the decision of winning or losing strategy class

#Get the color of chessboard according to its position
			def get_chess(self,pos):
			if pos[0] <= 0 or pos[0] > Chessboard.board_size:
			Raise runtimeerror ('line subscript out of range ')
			if pos[1] <=0 or pos[1] > Chessboard.board_size:
			Raise runtimeerror ('vertical subscript out of range ')
	return self.__board[pos[0]][pos[1]]

Policy class

The first two types are used for policy classes. There are more methods or attributes with names to use, so you need to be more careful about which is which
First pass in a checkerboard instance object

#Initialize the checkerboard object
			def __init__(self,chessboard):
	self.__chessboard = chessboard

Person playing chess: the strategy class is responsible for changing the character string entered by the person into x, y coordinates and writing it into the chess object

def parse_user_input(self,input,chessman):
			if not isinstance(chessman,Chessman):
			Raise runtimeerror ('wrong type, the first parameter must be a chessman object ')

			ret = input.split(',')
			value1 = ret[0]
			value2 = ret[1]
			#Convert to coordinates
			pos_x = int(value1)
			pos_y = ord(value2) - ord('a') +1
			chessman.set_pos((pos_x, pos_y))
	#print(ret)

Machine playing chess: the specific strategy here is temporarily replaced by random numbers

#The strategy of computer playing chess
			def computer_go(self, chessman):
			if not isinstance(chessman,Chessman):
			Raise runtimeerror ('wrong type, the first parameter must be a chessman object ')
			while True:

			#POS ﹣ X and POS ﹣ y randomly generate a number between 1 and 15
			pos_x = math.ceil(random.random()*Chessboard.board_size)
			pos_y = random.randint(1,15)
			#Judge whether it is empty, otherwise regenerate the coordinates
			if self.__chessboard.get_chess((pos_x,pos_y)) == '+':
			Print ('computer playing position:% D,% d '% (pos_x, pos_y))
			chessman.set_pos((pos_x,pos_y))
	break

Judge the winning or losing of the current chess game: each party must judge once to play chess. Therefore, it can judge whether there are five consecutive sons in the up, down, left, right and two oblique rows according to the range of the next son currently. If there are any, they will win.

Oblique row mainly means that the judgment range of X and Y is difficult to determine, and others are similar. The following are the judgment methods that my baby racked his brain to think of (especially oblique row). There is no problem until now, maybe there is a better way:

#Judge the outcome
			#When placing a piece, judge whether to win or not
			def is_won(self,pos,color):
			#Vertical range
			start_x = 1
			end_x = 15
			if pos[0] -4 >=1:
			start_x =pos[0] - 4
			if pos[0] +4 <=15:
			end_x = pos[0]+4
			#Judgment of vertical direction
			count = 0
			for pos_x in range(start_x, end_x+1):
			if self.__chessboard.get_chess((pos_x, pos[1])) == color:
			count +=1
			if count >=5:
			return True
			else:
			#Once disconnected, the statistics are cleared
			count = 0

			#Horizontal range 
			start_y = 1
			end_y = 15
			if pos[1] -4 >=1:
			start_y =pos[1] - 4
			if pos[1] +4 <=15:
			end_y = pos[1]+4
			#Judgment of horizontal direction
			count = 0
			for pos_y in range(start_y, end_y+1):
			if self.__chessboard.get_chess((pos[0], pos_y)) == color:
			count +=1
			if count >=5:
			return True
			else:
			#Once disconnected, the statistics are cleared
			count = 0

			#Left up right down direction judgment
			count = 0
			s=pos[0] - pos[1]
			start=start_x
			end=end_y+s
			if pos[0]>pos[1]:
			start=start_y+s
			end=end_x
			for index in range(start, end+1):
			if self.__chessboard.get_chess((index, index-s)) == color:
			count +=1
			if count >=5:
			return True
			else:
			#Once disconnected, the statistics are cleared
			count = 0

			#Left down right up direction judgment
			count = 0
			s=pos[0] + pos[1]
			if pos[0]+pos[1]<=16:
			start=start_x
			end=s-start_y

			if pos[0]+pos[1]>16:
			start=s-start_y
			end=start_x

			if s>=6 and s<=12:
			for index in range(start, end+1):
			if self.__chessboard.get_chess((index, s-index)) == color:
			count +=1
			if count >=5:
			return True
			else:
			#Once disconnected, the statistics are cleared
			count = 0
	return False

Next, use a method to judge the winner to call the above strategy

#Judge whether the winner or loser has been scored after the object is placed
			def is_wonman(self,chessman):
			if not isinstance(chessman,Chessman):
			Raise runtimeerror ('wrong type, the first parameter must be a chessman object ')
			pos = chessman.get_pos()
			color = chessman.get_color()
			#Call is? Won() to get its return value
	return self.is_won(pos,color)

Main module

The main module is used to control the playing pattern of the whole game.
The main function realizes the flow of a game. Here we use the cycle to realize simple man-machine alternating chess. Because the function of user selection is added, the code is temporarily tedious (covering the face) and can be simplified. Here is the first one:

def main():
			chessboard =Chessboard()
			chessboard.init_board()
			chessboard.print_board()
			engine = Engine(chessboard)
			count=0
			Select = int (input ('user selection order: (first: 1, then: 2)))
			First of all
			while True:
			chessman = Chessman()
			chessman.set_color('x')
			if select==1:
			I = input ('People play chess, please enter the chess coordinates (Format: X, y): ')
			Engine. Parse? User? Input (I, chessman)? Conversion to coordinates
			else:
			#Computer playing chess
			Print ('computer chess: ')
			engine.computer_go(chessman)
			#Put the chess object on the board
			chessboard.set_chessman(chessman)
			count +=1
			#Print chessboard
			chessboard.print_board()
			if engine.is_wonman(chessman):
			if select==1:
			Print ('People win! )

			else:
			Print ('the computer won! )
			break
			if count == 225:
			Print ('draw! )
			break


			Hou Hou 
			chessman = Chessman()
			chessman.set_color('o')
			if k==1:
			#Computer playing chess
			Print ('computer chess: ')
			#Computer generated strategy for chess pieces (location)
			engine.computer_go(chessman)
			else:
			I = input ('People play chess, please enter the chess coordinates (Format: X, y): ')
			engine.parse_user_input(i, chessman)
			#Convert to coordinates
			To play chess
			chessboard.set_chessman(chessman)
			count +=1
			chessboard.print_board()
			if engine.is_wonman(chessman):
			if k==1:
			Print ('the computer won! )
			else:
			Print ('People win! )
			break
			if count == 225:
			Print ('draw! )
	break

The main thread controls each chess game as the program entry:

if __name__ == '__main__':
			while True:
			Print ('Start a game! )
			#Call main method
			main()
			S = int (input ('another round or not: (yes: 1, No: 0)))
			if s!=1:
			break
	Print ('end of game! )

The simple human-machine mode of Gobang is to sum up, but the input place in this code is not checked, so the coordinate input must be in the form of number plus comma plus letter, and regular expression can be added for judgment. Put on the renderings:

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.