用python语言写一个五子棋
时间: 2023-12-29 10:55:43 浏览: 57
抱歉,作为AI语言模型,我无法编写出完整的程序。但我可以提供一个五子棋的Python代码框架,您可以根据它来编写您自己的五子棋程序。
```python
class Board:
def __init__(self, size=15):
self.size = size
self.board = [[0 for _ in range(size)] for _ in range(size)]
def print_board(self):
for i in range(self.size):
row = ''
for j in range(self.size):
if self.board[i][j] == 0:
row += ' + '
elif self.board[i][j] == 1:
row += ' ● '
else:
row += ' ○ '
print(row)
def is_valid_move(self, x, y):
if x < 0 or x >= self.size or y < 0 or y >= self.size:
return False
return self.board[x][y] == 0
def make_move(self, x, y, player):
self.board[x][y] = player
def is_game_over(self, x, y):
if self._check_horizontal(x, y) or self._check_vertical(x, y) or self._check_diagonal(x, y):
return True
return False
def _check_horizontal(self, x, y):
count = 1
for i in range(1, 5):
if y - i >= 0 and self.board[x][y - i] == self.board[x][y]:
count += 1
else:
break
for i in range(1, 5):
if y + i < self.size and self.board[x][y + i] == self.board[x][y]:
count += 1
else:
break
if count >= 5:
return True
return False
def _check_vertical(self, x, y):
count = 1
for i in range(1, 5):
if x - i >= 0 and self.board[x - i][y] == self.board[x][y]:
count += 1
else:
break
for i in range(1, 5):
if x + i < self.size and self.board[x + i][y] == self.board[x][y]:
count += 1
else:
break
if count >= 5:
return True
return False
def _check_diagonal(self, x, y):
count = 1
for i in range(1, 5):
if x - i >= 0 and y - i >= 0 and self.board[x - i][y - i] == self.board[x][y]:
count += 1
else:
break
for i in range(1, 5):
if x + i < self.size and y + i < self.size and self.board[x + i][y + i] == self.board[x][y]:
count += 1
else:
break
if count >= 5:
return True
count = 1
for i in range(1, 5):
if x - i >= 0 and y + i < self.size and self.board[x - i][y + i] == self.board[x][y]:
count += 1
else:
break
for i in range(1, 5):
if x + i < self.size and y - i >= 0 and self.board[x + i][y - i] == self.board[x][y]:
count += 1
else:
break
if count >= 5:
return True
return False
class Game:
def __init__(self):
self.board = Board()
self.current_player = 1
def play(self):
while True:
self.board.print_board()
x = int(input(f'Player {self.current_player}, please enter row: '))
y = int(input(f'Player {self.current_player}, please enter column: '))
if not self.board.is_valid_move(x, y):
print('Invalid move, try again.')
continue
self.board.make_move(x, y, self.current_player)
if self.board.is_game_over(x, y):
print(f'Player {self.current_player} wins!')
return
self.current_player = 2 if self.current_player == 1 else 1
if __name__ == '__main__':
game = Game()
game.play()
```
这个框架包含一个 `Board` 类和一个 `Game` 类来实现五子棋游戏的逻辑。您可以根据自己的需求修改和扩展这个框架。
阅读全文