用python编写一个字符界面的五子棋人机对战代码,并且规范代码格式
时间: 2024-05-16 17:14:38 浏览: 102
以下是一个简单的五子棋人机对战代码,实现了基本的游戏规则和人机对战的功能。代码规范遵循 PEP 8 标准。
```python
import random
class ChessBoard:
def __init__(self, size=15):
self.size = size
self.board = [['+' for i in range(size)] for j in range(size)]
def display(self):
print(' ', end='')
for i in range(self.size):
print(chr(ord('a')+i), end=' ')
print()
for i in range(self.size):
print('{:>2d}'.format(i+1), end=' ')
for j in range(self.size):
print(self.board[i][j], end=' ')
print()
def put(self, x, y, ch):
if x < 0 or x >= self.size or y < 0 or y >= self.size:
return False
if self.board[x][y] != '+':
return False
self.board[x][y] = ch
return True
def check(self, x, y, ch):
count = 0
for i in range(x-4, x+5):
if i < 0 or i >= self.size:
continue
if self.board[i][y] == ch:
count += 1
if count >= 5:
return True
else:
count = 0
count = 0
for j in range(y-4, y+5):
if j < 0 or j >= self.size:
continue
if self.board[x][j] == ch:
count += 1
if count >= 5:
return True
else:
count = 0
count = 0
for i in range(-4, 5):
if x+i < 0 or x+i >= self.size or y+i < 0 or y+i >= self.size:
continue
if self.board[x+i][y+i] == ch:
count += 1
if count >= 5:
return True
else:
count = 0
count = 0
for i in range(-4, 5):
if x+i < 0 or x+i >= self.size or y-i < 0 or y-i >= self.size:
continue
if self.board[x+i][y-i] == ch:
count += 1
if count >= 5:
return True
else:
count = 0
return False
class ChessGame:
def __init__(self, size=15):
self.board = ChessBoard(size)
self.players = ['X', 'O']
def play(self):
player = 0
while True:
self.board.display()
print('Player', player+1, 'turn')
x, y = self.get_input(player)
if self.board.put(x, y, self.players[player]):
if self.board.check(x, y, self.players[player]):
self.board.display()
print('Player', player+1, 'wins!')
return
player = 1 - player
else:
print('Invalid move')
def get_input(self, player):
if player == 0:
x = int(input('Enter x coordinate: ')) - 1
y = ord(input('Enter y coordinate: ')) - ord('a')
return x, y
else:
print('Computer is thinking...')
x, y = self.get_computer_input()
print('Computer put', chr(ord('a')+y)+str(x+1))
return x, y
def get_computer_input(self):
while True:
x = random.randint(0, self.board.size-1)
y = random.randint(0, self.board.size-1)
if self.board.put(x, y, self.players[1]):
if self.board.check(x, y, self.players[1]):
self.board.put(x, y, '+')
continue
return x, y
if __name__ == '__main__':
game = ChessGame()
game.play()
```
代码中使用了 `ChessBoard` 类和 `ChessGame` 类来实现五子棋游戏的逻辑。其中 `ChessBoard` 类用于表示棋局状态和操作,`ChessGame` 类用于控制游戏流程和玩家交互。实现了人机对战功能,计算机玩家使用随机策略来下棋。
阅读全文