I need help creating the snake game in matlab for a personal project.

조회 수: 34 (최근 30일)
Uzayr
Uzayr 2024년 11월 13일 17:57
댓글: Voss 2024년 11월 18일 16:15
Hello, I am creating the snake game in which the user has to click the left, right, up and down arrow keys to move the direction of the snake, and when it moves over the food icon, it increases in size. I just started learning Matlab 2 months ago in school and I wanted to challenge myself by creating this game. Currently I think I have the code to create a 20x20 axis in which it randomly plots the snake and food, and I think I have the code for the key press functions to move the snake. I also have code to make it so that when the snake's x or y values touches the borders that it turns off the while loop by setting alive=false. However, it is giving me a couple errors, and honestly I feel like i did the keypress part incorrectly. I will paste the code below for anyone to give suggestions because I really need it. Most of what I used in this code was self taught so if I did something wrong I apologize in advance. Cheers!
%% Snake.m
% Creates the snake game
% By: Anonymous
clear;clc;
%% perameters
axis([0, 20, 0, 20]);
snakex = randi([1,19],1);
snakey = randi([1,19],1);
foodx = randi([1,19],1);
foody = randi([1,19],1);
alive = true;
while alive == true
figure(100);
Food = plot(foodx,foody,'db'); hold("on");
Snake = plot(snakex,snakey,'og'); pause(0.1); hold("on");
grid("on"); axis("tight"); axis([0, 20, 0, 20])
% Below is the keypress code and the main cause for confusion!
set(gcf, 'KeyPressFcn', @processKey)
function processKey(~,evnt)
Function definitions are not supported in this context. Functions can only be created as local or nested functions in code files.
if length(evnt.Key) >= 1
switch evnt.Key
case 'leftarrow'
snakex = snakex - 1;
LastInput = left;
case 'rightarrow'
snakex = snakex + 1;
LastInput = right;
case 'downarrow'
snakey = snakey - 1;
LastInput = down;
case 'uparrow'
snakey = snakey + 1;
LastInput = up;
otherwise
if LastInput == left
snakex = snakex - 1;
elseif LastInput == right
snakex = snakex + 1;
elseif LastInput == down
snakey = snakey - 1;
elseif LastInput == up
snakey = snakey + 1;
end
end
end
end
if snakex == 0
alive = false;
end
if snakex == 20
alive = false;
end
if snakey == 0
alive = false;
end
if snakey == 20
alive = false;
end
end

채택된 답변

Voss
Voss 2024년 11월 13일 20:44
"Function definitions are not supported in this context. Functions can only be created as local or nested functions in code files."
Like the error message says, function definitions are not supported inside control blocks (if, else, while, for, etc.). You'd have to define the function processKey outside any control block in your script.
Since your intent is for processKey to set variables that need to be accessed within the while loop of the script (snakex, snakey, LastInput), it is convenient to make processKey a nested function (which requires making your script into a function) since nested functions share variables with their parent function.
Some construction as follows might be close to what you had in mind:
function snake_game()
fig = figure();
% Only need to set the figure's KeyPressFcn once, before the while loop.
% (processKey() will be called whenever the user presses a key while the
% figure has focus.)
set(fig, 'KeyPressFcn', @processKey)
axis([0, 20, 0, 20]);
snakex = randi([1,19],1);
snakey = randi([1,19],1);
foodx = randi([1,19],1);
foody = randi([1,19],1);
alive = true;
% initialize LastInput here in the parent function so that
% processKey can modify it
LastInput = '';
while alive
figure(fig);
Food = plot(foodx,foody,'db'); hold("on");
Snake = plot(snakex,snakey,'og'); pause(0.1); hold("on");
grid("on"); axis("tight"); axis([0, 20, 0, 20])
if snakex == 0
alive = false;
end
if snakex == 20
alive = false;
end
if snakey == 0
alive = false;
end
if snakey == 20
alive = false;
end
end
function processKey(~,evnt)
if length(evnt.Key) >= 1
switch evnt.Key
case 'leftarrow'
snakex = snakex - 1;
LastInput = 'left';
case 'rightarrow'
snakex = snakex + 1;
LastInput = 'right';
case 'downarrow'
snakey = snakey - 1;
LastInput = 'down';
case 'uparrow'
snakey = snakey + 1;
LastInput = 'up';
otherwise
switch LastInput
case 'left'
snakex = snakex - 1;
case 'right'
snakex = snakex + 1;
case 'down'
snakey = snakey - 1;
case 'up'
snakey = snakey + 1;
end
end
end
end
end
  댓글 수: 2
Uzayr
Uzayr 2024년 11월 18일 15:03
OMG! Thank you so much. This solves a LOT of my confusion. I am going to start working on figuring out how to have the snake interact with the food now and actually making the game fully functional. If I have any other questions I'll probably post it here. Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by