本篇文章用matlab做了一个经典的小游戏-贪吃蛇,代码如下所示,仅仅包含一个函数snake,整体来说实现难度比较小,适合初学者熟悉matlab:
function snake
axis equal
axis(0.5+[0, 20, 0, 20])
set(gca,'xtick',[],'ytick',[],'xcolor','w','ycolor','w')
set(gca, 'color', 'y')
hold on
snakeTop = [5, 5];
snakeDirect = [1, 0];
body = [5, 5 ; 4, 5 ; 3, 5];
long = 3;
food = [10, 10];
plotSnake = scatter(gca, body(:, 1), body(:, 2), 220, 'bs', 'filled');
plotFood = scatter(gca, food(1), food(2), 150, 'g', 'filled');
set(gcf, 'KeyPressFcn', @key)
fps = 5;
game = timer('ExecutionMode', 'FixedRate', 'Period',1/fps, 'TimerFcn', @snakeGame);
start(game)
function snakeGame(~,~)
snakeTop = snakeTop + snakeDirect;
body = [snakeTop; body] ;
while length(body)> long
body(end, : ) = [];
end
if intersect(body(2 : end, : ), snakeTop, 'rows')
ButtonName1 = questdlg('游戏结束,请点击按钮继续......','Gave Over','重新开始','关闭游戏', 'Yes');
if ButtonName1 == '重新开始'
clf;
snake();
else
close;
end
end
if isequal(snakeTop, food)
long = long + 1;
food = randi(20, [1, 2]);
while any(ismember(body, food, 'rows'))
food = randi(20, [1, 2]);
end
end
if (snakeTop(1, 1)>20)||(snakeTop(1, 1)<1)||(snakeTop(1, 2)>20)||(snakeTop(1, 2)<1)
ButtonName2 = questdlg('游戏结束,请点击按钮继续......','Gave Over','重新开始','关闭游戏', '关闭游戏');
if ButtonName2 == '重新开始'
clf;
snake();
else
close;
end
end
set(plotFood, 'XData', food(1), 'YData', food(2));
set(plotSnake, 'XData', body( : , 1), 'YData', body( : , 2));
end
function key(~,event)
switch event.Key
case 'uparrow'
direct = [0, 1];
case 'downarrow'
direct = [0, -1];
case 'leftarrow'
direct = [-1, 0];
case 'rightarrow'
direct = [1, 0];
case 'space'
stop(game);
direct = snakeDirect;
ButtonName3 = questdlg('游戏暂停......', 'Stop ', '重新开始', '关闭游戏', '继续游戏', '关闭游戏');
if ButtonName3 == '重新开始'
clf;
snake();
elseif ButtonName3 == '关闭游戏'
close;
else
start(game);
end
otherwise
direct = nan;
end
if any(snakeDirect + direct)
snakeDirect = direct;
end
end
end
最终的运行示意图如下:

图1 操控贪吃蛇吃掉果实

图2 吃掉果实随机刷新

图3 碰到墙后的系统提示