本篇内容介绍了“怎么用python实现五子棋”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
具体代码如下
# 制作一个棋盘"""++++++++++++++++++++++++++++++++++++++++"""def createBoard(): board = [] for i in range(15): board.append(["+"] * 15) return boarddef 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][c]: 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(">>>黑方胜!") 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 = 0while not isGameOver():#游戏继续的操作 if player % 2 == 0: print(">>>请黑方下棋,", end="") if not chess("●"): continue else: print(">>>请白方下棋,", end="") if not chess("○"): continue printBoard() player += 1print(">>>游戏结束!")
“怎么用python实现五子棋”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!