用matlab写一个五子棋游戏
时间: 2023-11-04 13:06:03 浏览: 98
好的,以下是一个简单的五子棋游戏代码,希望对你有帮助:
```matlab
function FiveInARow()
% 五子棋游戏
% by CSDN开发者-五味子菜
% 设置棋盘大小
boardSize = 15;
% 初始化棋盘
board = zeros(boardSize);
% 设置玩家和电脑的棋子
player = 1;
computer = 2;
% 游戏循环
while true
% 绘制棋盘
drawBoard(board);
% 玩家落子
if player == 1
[x, y] = getPlayerMove(board);
board(x, y) = player;
% 判断是否获胜
if checkWin(board, player)
drawBoard(board);
disp('你赢了!');
break;
end
% 切换到电脑落子
player = computer;
end
% 电脑落子
if player == computer
[x, y] = getComputerMove(board);
board(x, y) = computer;
% 判断是否获胜
if checkWin(board, computer)
drawBoard(board);
disp('你输了!');
break;
end
% 切换到玩家落子
player = 1;
end
end
end
function drawBoard(board)
% 绘制棋盘
boardSize = size(board, 1);
clf;
hold on;
axis equal;
axis([0 boardSize+1 0 boardSize+1]);
for i = 1:boardSize
line([1 boardSize], [i i], 'Color', 'k');
line([i i], [1 boardSize], 'Color', 'k');
end
[x, y] = find(board == 1);
plot(x, y, 'ko', 'MarkerSize', 10, 'LineWidth', 2);
[x, y] = find(board == 2);
plot(x, y, 'ro', 'MarkerSize', 10, 'LineWidth', 2);
drawnow;
end
function [x, y] = getPlayerMove(board)
% 玩家落子
while true
[x, y] = ginput(1);
x = round(x);
y = round(y);
if x >= 1 && y >= 1 && x <= size(board, 1) && y <= size(board, 2) && board(x, y) == 0
break;
end
end
end
function [x, y] = getComputerMove(board)
% 电脑落子
boardSize = size(board, 1);
[x, y] = find(board == 0);
n = length(x);
for i = 1:n
if checkPosition(board, x(i), y(i), computer)
break;
end
end
if i == n
i = randi(n);
end
x = x(i);
y = y(i);
end
function win = checkWin(board, player)
% 判断是否获胜
boardSize = size(board, 1);
for i = 1:boardSize
for j = 1:boardSize
if checkPosition(board, i, j, player)
win = true;
return;
end
end
end
win = false;
end
function win = checkPosition(board, x, y, player)
% 判断位置是否获胜
boardSize = size(board, 1);
dx = [0 1 1 1 0 -1 -1 -1];
dy = [1 1 0 -1 -1 -1 0 1];
for k = 1:8
count = 0;
for i = 0:4
xi = x + i*dx(k);
yi = y + i*dy(k);
if xi >= 1 && yi >= 1 && xi <= boardSize && yi <= boardSize && board(xi, yi) == player
count = count + 1;
else
break;
end
end
if count == 5
win = true;
return;
end
end
win = false;
end
```
运行该程序后,你可以与电脑进行五子棋游戏了。祝你玩得愉快!
阅读全文