python五子棋代码实现
时间: 2024-05-26 10:08:55 浏览: 93
Python 是一种常用的编程语言,可以实现五子棋游戏。下面是一个简单的五子棋游戏代码示例:
```
import numpy as np
ROW = 15
COLUMN = 15
class Chessboard(object):
def __init__(self):
self.board = np.zeros((ROW, COLUMN))
self.player = 1
def update(self, row, column):
if self.board[row][column] == 0:
self.board[row][column] = self.player
self.player = -self.player
def print_board(self):
print(" ", end="")
for i in range(COLUMN):
print(chr(ord("a") + i), end=" ")
print()
for i in range(ROW):
print("{:2d}".format(i + 1), end=" ")
for j in range(COLUMN):
if self.board[i][j] == 1:
print("●", end=" ")
elif self.board[i][j] == -1:
print("○", end=" ")
else:
print("+", end=" ")
print()
def main():
chessboard = Chessboard()
chessboard.print_board()
while True:
input_str = input("Please input row and column(e.g. '1a'): ")
try:
row, column = int(input_str) - 1, ord(input_str) - ord("a")
chessboard.update(row, column)
chessboard.print_board()
except Exception as e:
print(e)
if __name__ == "__main__":
main()
```
这个程序使用了 numpy 库实现棋盘的绘制,同时利用了面向对象的思想,将棋盘的状态和更新逻辑封装在 Chessboard 类中。在主函数中,通过循环读入玩家的输入,并调用 Chessboard 类的方法更新棋盘状态和打印棋盘。
阅读全文