matlab五子棋程序
时间: 2023-07-31 12:11:09 浏览: 96
以下是一个简单的 MATLAB 五子棋程序示例:
```matlab
% 游戏初始化
clc; clear; close all;
boardSize = 15; % 棋盘大小
board = zeros(boardSize); % 初始化棋盘
player = 1; % 玩家初始化为1
gameOver = false; % 游戏结束标志
% 游戏循环
while ~gameOver
% 显示棋盘
imagesc(board);
axis equal tight;
set(gca, 'XTick', 1:boardSize, 'YTick', 1:boardSize, 'XTickLabel', [], 'YTickLabel', []);
xlabel('X');
ylabel('Y');
title(['Player ', num2str(player)]);
drawnow;
% 玩家下棋
[x, y] = ginput(1); % 获取玩家下棋位置
x = round(x);
y = round(y);
if x < 1 || x > boardSize || y < 1 || y > boardSize || board(y, x) ~= 0 % 判断是否越界或位置已被占用
continue;
end
board(y, x) = player; % 玩家下棋
% 判断游戏是否结束
if checkGameOver(board, player)
gameOver = true;
disp(['Player ', num2str(player), ' wins!']);
break;
end
% 切换玩家
player = 3 - player;
end
% 检查游戏是否结束
function gameOver = checkGameOver(board, player)
% 检查行
for i = 1:size(board, 1)
count = 0;
for j = 1:size(board, 2)
if board(i, j) == player
count = count + 1;
if count == 5
gameOver = true;
return;
end
else
count = 0;
end
end
end
% 检查列
for i = 1:size(board, 2)
count = 0;
for j = 1:size(board, 1)
if board(j, i) == player
count = count + 1;
if count == 5
gameOver = true;
return;
end
else
count = 0;
end
end
end
% 检查对角线
for i = 1:size(board, 1)-4
for j = 1:size(board, 2)-4
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
gameOver = true;
return;
end
end
end
% 检查反对角线
for i = 1:size(board, 1)-4
for j = 5:size(board, 2)
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
gameOver = true;
return;
end
end
end
gameOver = false;
end
```
请注意,这只是一个简单的示例,没有实现 AI 玩家,也没有实现更高级的游戏规则。您可以根据自己的需要进行修改和扩展。
阅读全文