帮我写一个贪吃蛇的matlab代码
时间: 2023-08-20 11:12:34 浏览: 125
好的,以下是一个简单的贪吃蛇的 MATLAB 代码,希望可以帮到你:
```matlab
clc;
clear all;
close all;
% 初始化贪吃蛇
game_over = false;
snake_pos = [5 5];
snake_dir = [0 1];
snake_len = 3;
snake_body = snake_pos;
food_pos = randi([1 20], 1, 2);
% 游戏循环
while ~game_over
% 显示画布
canvas = zeros(20, 20);
canvas(snake_pos(1), snake_pos(2)) = 1;
for i = 2:snake_len
canvas(snake_body(i, 1), snake_body(i, 2)) = 1;
end
canvas(food_pos(1), food_pos(2)) = 2;
imagesc(canvas);
axis equal;
axis off;
drawnow;
% 判断游戏结束
if snake_pos(1) < 1 || snake_pos(1) > 20 || snake_pos(2) < 1 || snake_pos(2) > 20 || any(all(bsxfun(@eq, snake_body, snake_pos), 2))
game_over = true;
end
% 判断是否吃到食物
if all(bsxfun(@eq, snake_pos, food_pos))
food_pos = randi([1 20], 1, 2);
snake_len = snake_len + 1;
snake_body(snake_len, :) = snake_body(snake_len-1, :);
end
% 移动贪吃蛇
snake_body(2:end, :) = snake_body(1:end-1, :);
snake_body(1, :) = snake_pos;
snake_pos = snake_pos + snake_dir;
% 获取用户输入
key = getkey();
switch key
case 'uparrow'
snake_dir = [-1 0];
case 'downarrow'
snake_dir = [1 0];
case 'leftarrow'
snake_dir = [0 -1];
case 'rightarrow'
snake_dir = [0 1];
case 'escape'
game_over = true;
end
end
% 游戏结束
disp('Game Over!');
% 获取键盘输入
function key = getkey()
set(gcbf,'KeyPressFcn',@setglobalkey);
waitfor(gcbf,'UserData');
key = get(gcbf,'UserData');
end
% 设置全局键盘输入
function setglobalkey(src,event)
set(gcbf,'UserData',event.Key);
end
```
使用方法:复制以上代码到 MATLAB 中,运行即可。按上下左右键控制贪吃蛇移动,按 ESC 键退出游戏。
阅读全文