canbu make a snake game in matlab

main.m
% Snake Game in MATLAB

function SnakeGame()
    % Set up game parameters
    rows = 20;
    cols = 20;
    snake = [3 3; 3 4; 3 5];  % Initial snake coordinates
    dir = [0 1];    % Initial direction of movement (right)
    food = randi([1, rows], 1, 2);  % Initial food position
    
    % Create empty game board
    gameboard = zeros(rows, cols);
    
    % Main game loop
    while true
        % Display gameboard
        clf
        imagesc(gameboard);
        axis off
        colormap(gray);
        
        % Update snake position
        head = snake(1, :) + dir;
        snake = [head; snake(1:end-1, :)];
        
        % Check for collision
        if any(head < 1) || any(head > [rows cols]) || any(all(bsxfun(@eq, snake, head), 2))
            disp('Game Over!')
            break;
        end
        
        % Check for food
        if all(head == food)
            snake = [head; snake];
            food = randi([1, rows], 1, 2);
        end
        
        % Update gameboard with snake and food
        gameboard = zeros(rows, cols);
        for i = 1:size(snake, 1)
            gameboard(snake(i, 1), snake(i, 2)) = 1;
        end
        gameboard(food(1), food(2)) = 2;
        
        drawnow;
        
        % Set game speed
        pause(0.1);
    end
end
1293 chars
51 lines

This code provides a basic implementation of a snake game in MATLAB using a simple game loop and updating the game board at each step. The snake moves automatically in the direction specified until it collides with the wall or itself. The game ends in case of collision. The player can control the direction of the snake using the arrow keys. The game also includes a food item that the snake can eat to grow in size.

related categories

gistlibby LogSnag