MATLAB贪吃蛇游戏

以下是一个基于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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值