Python游戏代码
代码语言:javascript复制class Board:
def __init__(self, size=15):
self.size = size
self.board = [[' ' for _ in range(size)] for _ in range(size)]
self.current_player = 'X'
def display(self):
print(' ' ' '.join(str(i) for i in range(self.size)))
print(' ' '--- ' * self.size)
for i in range(self.size):
row = f' {i} |'
for j in range(self.size):
row = f' {self.board[i][j]} |'
print(row)
print(' ' '--- ' * self.size)
def make_move(self, x, y):
if not self.is_valid_move(x, y):
return False
self.board[x][y] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
def is_valid_move(self, x, y):
if x < 0 or x >= self.size or y < 0 or y >= self.size:
return False
if self.board[x][y] != ' ':
return False
return True
def check_winner(self):
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] == ' ':
continue
if self.check_right(i, j) or self.check_down(i, j) or self.check_diagonal_down_right(i, j) or self.check_diagonal_down_left(i, j):
return self.board[i][j]
return None
def check_right(self, x, y):
count = 1
while y count < self.size and self.board[x][y count] == self.board[x][y]:
count = 1
return count >= 5
def check_down(self, x, y):
count = 1
while x count < self.size and self.board[x count][y] == self.board[x][y]:
count = 1
return count >= 5
def check_diagonal_down_right(self, x, y):
count = 1
while x count < self.size and y count < self.size and self.board[x count][y count] == self.board[x][y]:
count = 1
return count >= 5
def check_diagonal_down_left(self, x, y):
count = 1
while x count < self.size and y - count >= 0 and self.board[x count][y - count] == self.board[x][y]:
count = 1
return count >= 5
if __name__ == '__main__':
board = Board()
while True:
board.display()
move = input(f"{board.current_player}, make a move (row column): ")
try:
x, y = move.split()
x, y = int(x), int(y)
except:
print('Invalid input.')
continue
if not board.make_move(x, y):
print('Invalid move.')
continue
winner = board.check_winner()
if winner is not None:
board.display()
print(f"Game over. {winner} wins!")
break
这个代码实现了一个简单的五子棋游戏,玩家需要在棋盘上下五子棋,先连成五个的玩家即为胜者。你可以运行这个代码,体验一下这个游戏的玩法。
运行结果: