用python实现五子棋实例

本文实例为大家分享了用python实现五子棋的具体代码,供大家参考,具体内容如下


 	# 制作一个棋盘
 	"""
 	++++++++++
 	++++++++++
 	++++++++++
 	++++++++++
 	"""
 	 
 	 
 	def createBoard():
 	     board = []
 	     for i in range(15):
 	     board.append(["+"] * 15)
 	     return board
 	 
 	 
 	def printBoard():# print(" ", end="")
 	     for i in range(1, 16):
 	     number = str(i).rjust(3)
 	     print(number, end="")
 	     print()#打印列号之后换行
 	     for i in range(15):
 	     number = str(i + 1).ljust(3)#注意这个函数,是将行号每个都变成左对齐,占3位,以实现棋盘对齐功能
 	     print(number, end="")#打印行号
 	     for j in range(15):
 	         print(board[i][j], end=" ")
 	     print()
 	 
 	 
 	def isGameOver():
 	     count = 0
 	     # 先判断连续
 	     for x in range(15):
 	     for y in range(15):
 	         if board[x][y] != "+":
 	         count += 1
 	         # 向右
 	         if y < 11:
 	             flag = True #表示默认游戏结束
 	             for c in range(y + 1, y + 5):
 	             if board[x][y] != board[x]:
 	                 flag = False
 	                 break
 	             if flag:
 	             if board[x][y] == "●":
 	                 print(">>>黑方胜!")
 	             else :
 	                 print(">>>白方胜!")
 	             return True; # 表示游戏结束
 	         # 向下
 	         if x < 11:
 	             if board[x][y] == board[x+1][y] == board[x+2][y] == board[x+3][y] == board[x+4][y]:
 	             if board[x][y] == "●":
 	                 print(">>>黑方胜!")
 	             else :
 	                 print(">>>白方胜!")
 	             return True
 	         # 向右下
 	         if x < 11 and y < 11:
 	             if board[x][y] == board[x+1][y+1] == board[x+2][y+2] == board[x+3][y+3] == board[x+4][y+4]:
 	             if board[x][y] == "●":
 	                 print(">>&amp;gt;黑方胜!")
 	             else :
 	                 print(">>>白方胜!")
 	             return True
 	         # 向右上
 	         if x > 3 and y < 11:
 	             if board[x][y] == board[x-1][y+1] == board[x-2][y+2] == board[x-3][y+3] == board[x-4][y+4]:
 	             if board[x][y] == "●":
 	                 print(">>>黑方胜!")
 	             else :
 	                 print(">>>白方胜!")
 	             return True
 	     # 再判断和棋
 	     if count == 15 ** 2:
 	     print(">>>和棋!")
 	     return True
 	     return False#如果以上连棋都没出现就游戏继续
 	 
 	 
 	def chess(c):
 	     x, y = eval(input("请输入坐标:"))
 	     x -= 1
 	     y -= 1
 	     if board[x][y] == "+":
 	     board[x][y] = c
 	     return True
 	     else:
 	     print(">>>此处已有棋子,请重新下棋!")
 	     return False
 	 
 	 
 	# 程序的开始
 	board = createBoard();
 	printBoard()
 	player = 0
 	while not isGameOver():#游戏继续的操作
 	     if player % 2 == 0:
 	     print(">>>请黑方下棋,", end="")
 	     if not chess("●"):
 	         continue
 	     else:
 	     print(">>>请白方下棋,", end="")
 	     if not chess("○"):
 	         continue
 	     printBoard()
 	     player += 1
 	print(">>>游戏结束!")

用python实现五子棋实例插图

五子棋胜局判断的根据所在如上图。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

标签

发表评论