用matlab写一个双人五子棋对战的代码
时间: 2023-08-27 09:03:47 浏览: 85
以下是一个双人五子棋对战的 MATLAB 代码示例:
```matlab
clc; clear; close all;
% 初始化游戏棋盘
board = zeros(15, 15);
% 确定先手玩家
player = 1;
% 游戏开始
while true
% 显示当前棋盘状态
disp(board);
% 玩家落子
disp(['Player ', num2str(player), ' turn.']);
[row, col] = input('Enter row and column: ');
board(row, col) = player;
% 判断是否有胜者
if check_win(board, player)
disp(['Player ', num2str(player), ' wins!']);
break;
end
% 切换玩家
if player == 1
player = 2;
else
player = 1;
end
end
% 检查是否有胜者
function win = check_win(board, player)
win = false;
for i = 1:15
for j = 1:11
if board(i,j) == player && board(i,j+1) == player && board(i,j+2) == player && board(i,j+3) == player && board(i,j+4) == player
win = true;
return;
end
end
end
for i = 1:11
for j = 1:15
if board(i,j) == player && board(i+1,j) == player && board(i+2,j) == player && board(i+3,j) == player && board(i+4,j) == player
win = true;
return;
end
end
end
for i = 1:11
for j = 1:11
if board(i,j) == player && board(i+1,j+1) == player && board(i+2,j+2) == player && board(i+3,j+3) == player && board(i+4,j+4) == player
win = true;
return;
end
end
end
for i = 1:11
for j = 5:15
if board(i,j) == player && board(i+1,j-1) == player && board(i+2,j-2) == player && board(i+3,j-3) == player && board(i+4,j-4) == player
win = true;
return;
end
end
end
end
```
运行以上代码后,你将看到一个 15*15 的空棋盘。每次轮到玩家操作时,程序会提示输入落子的行和列,然后将该位置设置为 1 或 2,代表不同的玩家。程序会在每次操作后检查是否有玩家获胜,如果有则输出胜者并结束游戏。
阅读全文