An issue with a custom WindowKeyPressFcn (Interrupted)?
Afficher commentaires plus anciens
Hello. I am writing a simple game similar to the snake. To code the direction in which the snake will move next I am using a custom WindowKeyPressFcn. Since just like in the original game I want the snake to constantly move I am using a while loop with a pause(0.2) inside. However, once i start smashing buttons code freezes (no error, just freezes). I am assuming that I am interrupting the current function run and start another one and something goes wrong. Without the while loop everything works great. I tried to look into dbstack() and suck, but was unable to find multiple calls to WindowKeyPressFcn function. Setting Interruptible property of the figure "off" and "on" at the beginning/end of the loop did not help.
here is a full code:
if true
function test
step = 1;
F=figure;
A=axes;
P=patch([2 2 3 3],[2 3 3 2],'r');
set(A,'XLim',[-25 25],'YLim',[-25 25],'DataAspectRatio',[1 1 1]);
seed_x = round(rand*49-25);
seed_y = round(rand*49-25);
food = patch([seed_x seed_x seed_x+1 seed_x+1],[seed_y seed_y+1 seed_y+1 seed_y],'g');
set(F,'WindowKeyPressFcn',{@move,P,food,step}, ...
'NumberTitle','off', ...
'Name','Snake. Score: 0');
end
function move(~,event,L,f,s)
while 1
if strcmpi(event.Key,'leftarrow')
set(L,'XData',get(L,'Xdata') - s);
eat(L,f);
if any(get(L,'XData')<-25)
set(L,'XData',[24 24 25 25]);
end
elseif strcmpi(event.Key,'rightarrow')
set(L,'XData',get(L,'Xdata') + s);
eat(L,f);
if any(get(L,'XData')>25)
set(L,'XData',[-25 -25 -24 -24]);
end
elseif strcmpi(event.Key,'uparrow')
set(L,'YData',get(L,'Ydata') + s);
eat(L,f);
if any(get(L,'YData')>25)
set(L,'YData',[-25 -24 -24 -25]);
end
elseif strcmpi(event.Key,'downarrow')
set(L,'YData',get(L,'Ydata') - s);
eat(L,f);
if any(get(L,'YData')<-25)
set(L,'YData',[24 25 25 24]);
end
end
pause(0.2)
end
end
function eat(I,fd)
persistent score;
if isempty(score)
score=0;
end
a=get(I,'Xdata');
b=get(I,'Ydata');
c=get(fd,'Xdata');
d=get(fd,'Ydata');
if all(a == c) && all(b == d)
score=score+1;
set(gcf,'Name',['Snake. Score: ' num2str(score)]);
sx = round(rand*49-25);
sy = round(rand*49-25);
set(fd,'Xdata',[sx sx sx+1 sx+1]);
set(fd,'Ydata',[sy sy+1 sy+1 sy]);
end
end
end
Can I do anything to rectify the issue? Thanks in advance!
Réponses (1)
Walter Roberson
le 28 Août 2013
0 votes
Instead of using a while loop with a pause(), use a timer() instead. Have your WindowKeyPressFcn only handle a single press. Set WindowKeyPressFcn interruptible off and BusyAction to the (default) 'queue'
2 commentaires
Aleksey
le 28 Août 2013
Walter Roberson
le 28 Août 2013
You do it for the entire figure.
Catégories
En savoir plus sur Conway's Game of Life dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!