用matlab实现一个简单美观的五子棋游戏
时间: 2024-05-15 09:14:15 浏览: 190
以下是一个简单美观的五子棋游戏的Matlab代码:
```matlab
%初始化游戏
clc; clear; close all;
board = zeros(15,15); % 15*15的棋盘初始化
player = 1; % 玩家初始化为1,即黑色棋子先手
winner = 0; % 初始化胜利者为0
move_count = 0; % 记录已下棋子的个数
gameover = false; % 游戏结束标志
%绘制棋盘
figure('Name','五子棋游戏','NumberTitle','off','MenuBar','none','ToolBar','none',...
'Position',get(0,'ScreenSize'),'Color',[1 1 1],'Resize','off');
axis off;
hold on;
line([1 15],[1 1],'Color','k','LineWidth',2);
line([1 15],[15 15],'Color','k','LineWidth',2);
line([1 1],[1 15],'Color','k','LineWidth',2);
line([15 15],[1 15],'Color','k','LineWidth',2);
for i = 1:14
line([i+1 i+1],[1 15],'Color','k','LineWidth',1);
line([1 15],[i+1 i+1],'Color','k','LineWidth',1);
end
%开始游戏
while ~gameover
%下棋
[x,y] = ginput(1);
x = round(x);
y = round(y);
if x < 1 || x > 15 || y < 1 || y > 15 || board(y,x) ~= 0
continue;
end
move_count = move_count + 1;
board(y,x) = player;
%绘制棋子
if player == 1
plot(x,y,'ok','MarkerSize',15,'LineWidth',2);
else
plot(x,y,'ow','MarkerSize',15,'LineWidth',2);
end
%判断胜负
if move_count >= 9
if check_win(board,player,x,y)
winner = player;
gameover = true;
end
end
%切换玩家
if player == 1
player = 2;
else
player = 1;
end
%如果平局
if move_count >= 225
gameover = true;
end
end
%输出胜利者
if winner == 0
msgbox('平局!');
else
if winner == 1
msgbox('黑棋胜利!');
else
msgbox('白棋胜利!');
end
end
%判断是否胜利
function win = check_win(board,player,x,y)
win = false;
%横向判断
count = 1;
for i = x-1:-1:1
if board(y,i) == player
count = count + 1;
else
break;
end
end
for i = x+1:15
if board(y,i) == player
count = count + 1;
else
break;
end
end
if count >= 5
win = true;
return;
end
%纵向判断
count = 1;
for i = y-1:-1:1
if board(i,x) == player
count = count + 1;
else
break;
end
end
for i = y+1:15
if board(i,x) == player
count = count + 1;
else
break;
end
end
if count >= 5
win = true;
return;
end
%左斜向判断
count = 1;
i = x-1;
j = y-1;
while i>=1 && j>=1
if board(j,i) == player
count = count + 1;
i = i - 1;
j = j - 1;
else
break;
end
end
i = x+1;
j = y+1;
while i<=15 && j<=15
if board(j,i) == player
count = count + 1;
i = i + 1;
j = j + 1;
else
break;
end
end
if count >= 5
win = true;
return;
end
%右斜向判断
count = 1;
i = x+1;
j = y-1;
while i<=15 && j>=1
if board(j,i) == player
count = count + 1;
i = i + 1;
j = j - 1;
else
break;
end
end
i = x-1;
j = y+1;
while i>=1 && j<=15
if board(j,i) == player
count = count + 1;
i = i - 1;
j = j + 1;
else
break;
end
end
if count >= 5
win = true;
return;
end
end
```
该代码实现了一个简单的五子棋游戏,具有以下功能:
1. 绘制15×15的棋盘
2. 玩家可以通过鼠标在棋盘上下棋
3. 根据规则判断胜负
4. 游戏结束后弹出胜利者的信息框
该程序使用了Matlab的绘图功能和GUI设计,通过绘制棋盘和棋子来实现游戏画面。其中,check_win函数实现了五子棋的胜负判断,通过横向、纵向、左斜向和右斜向的判断,判断当前玩家是否连成了五个棋子。程序还实现了玩家之间的轮流下棋,通过记录已下棋子个数和判断是否平局来判断游戏是否结束。
阅读全文