以下是一个基于MATLAB的贪吃蛇游戏的示例代码:
function SnakeGame()
% 初始化游戏界面
figure('Name', '贪吃蛇游戏', 'NumberTitle', 'off', 'MenuBar', 'none', 'Color', 'k', 'KeyPressFcn', @keyDown);
axis off;
axis square;
hold on;
% 设置游戏参数
gridSize = 20;
numCells = 25;
gameSpeed = 0.1;
% 初始化贪吃蛇
snakeHead = [ceil(numCells/2), ceil(numCells/2)];
snakeTail = [snakeHead(1) - 2, snakeHead(2)];
snake = [snakeHead; snakeTail];
snakeDirection = 'right';
% 初始化食物
food = generateFood();
% 游戏循环
while true
% 更新贪吃蛇位置
snake = updateSnake(snake, snakeDirection);
% 检查是否吃到食物
if isFoodEaten(snakeHead, food)
snake = [snake; snakeTail];
food = generateFood();
else
snake = snake(1:end-1, :);
end
% 检测游戏结束
if isGameOver(snake)
break;
end
% 更新游戏界面
drawGame(snake, food, gridSize, numCells);
% 控制游戏速度
pause(gameSpeed);
end
% 游戏结束提示
text(numCells/2, numCells/2, 'Game Over!', 'Color', 'r', 'FontSize', 30, 'HorizontalAlignment', 'center');
text(numCells/2, numCells/2-1, ['Score: ', num2str(size(snake, 1)-2)], 'Color', 'r', 'FontSize', 20, 'HorizontalAlignment', 'center');
function keyDown(~, event)
% 根据按键设置蛇的移动方向
key = event.Key;
if strcmp(key, 'up') && ~strcmp(snakeDirection, 'down')
snakeDirection = 'up';
elseif strcmp(key, 'down') && ~strcmp(snakeDirection, 'up')
snakeDirection = 'down';
elseif strcmp(key, 'left') && ~strcmp(snakeDirection, 'right')
snakeDirection = 'left';
elseif strcmp(key, 'right') && ~strcmp(snakeDirection, 'left')
snakeDirection = 'right';
end
end
function drawGame(snake, food, gridSize, numCells)
% 清空游戏界面
cla;
% 绘制贪吃蛇
plot(snake(:, 2), snake(:, 1), 'Color', 'g', 'LineWidth', 2);
% 绘制食物
plot(food(2), food(1), 'r.', 'MarkerSize', 20);
% 绘制网格
for i = 1:numCells
x = [0, numCells*gridSize];
y = [i*gridSize, i*gridSize];
plot(x, y, 'Color', 'w');
x = [i*gridSize, i*gridSize];
y = [0, numCells*gridSize];
plot(x, y, 'Color', 'w');
end
% 设置坐标轴范围
xlim([0, numCells*gridSize]);
ylim([0, numCells