概述
制作了一个生命游戏的小游戏
上下左右移动红点
空格绘制生命
按键B开始运动
按键C暂停
按键A清空
按键backspace删除生命
游戏截图
动图
代码部分
function lifecontrol
% life game which can input point as you will.
% move the red cross with the key
% 'uparrow','downarrow','leftarrow','rightarrow'
% use the key 'space'to input
% 'bacspace'to delete
% 'b' to begin 'c'to stop and 'a' to restart
n=50;
%n=input('the board size is:');
axis equal
axis(0.5+[0,n,0,n])
set(gca,'xtick',[],'ytick',[],'xcolor','w','ycolor','w')
set(gca,'color','w')
hold on
%axis set.........................................................................
%A=randi(9,[n,n]);
%A(A<2.1)=0;
%A(A>2)=1;
A=zeros(n,n);
%A=[input sqare with only ones and zeros]
[a,b]=find(A(:,:)==1);
B=[b,length(sum(A,2))-a];
postion=[floor(n/2),floor(n/2)];
control=1;
plotl=scatter(gca,B(:,1),B(:,2),1200/n,'ks','filled');
plotpostion=scatter(gca,postion(1,1),postion(1,2),150,'rx');
set(gcf, 'KeyPressFcn', @key)
fps = 20;
game = timer('ExecutionMode', 'FixedRate', 'Period',1/fps, 'TimerFcn', @lifeGame);
start(game)
%beginning set.............................................................................
set(gcf,'tag','co','CloseRequestFcn',@clo);
function clo(~,~)
stop(game)
delete(findobj('tag','co'))
clf
close
end
function lifeGame(~,~)
chang=length(sum(A,2));
postion(postion>chang)=postion(postion>chang)-chang;
postion(postion<1)=postion(postion<1)+chang;
if control==2
B1=[A;zeros(1,chang)];B1(1,:)=[];B2=[zeros(1,chang);A];B2(end,:)=[];
B3=[zeros(chang,1),A];B3(:,end)=[];B4=[A,zeros(chang,1)];B4(:,1)=[];
C1=[zeros(chang,1),B1];C1(:,end)=[];C2=[B1,zeros(chang,1)];C2(:,1)=[];
C3=[zeros(chang,1),B2];C3(:,end)=[];C4=[B2,zeros(chang,1)];C4(:,1)=[];
NewA=B1+B2+B3+B4+C1+C2+C3+C4;
progressA=zeros(chang,chang);
progressA(NewA==3)=1;
t3=find(NewA==2);
t2=find(A==1);
[lalala,~,~]=intersect(t3,t2);
progressA(lalala)=1;
A=progressA;
[a,b]=find(A(:,:)==1);
B=[b,length(sum(A,2))-a];
end
if control==1
[a,b]=find(A(:,:)==1);
B=[b,length(sum(A,2))-a];
end
set(plotl,'XData',B(:,1),'YData',B(:,2))
set(plotpostion,'XData',postion(1,1),'YData',postion(1,2))
end
function key(~,event)
switch event.Key
case 'uparrow'
postion=postion+[0,1];
case 'downarrow'
postion=postion+[0,-1];
case 'leftarrow'
postion=postion+[-1,0];
case 'rightarrow'
postion=postion+[1,0];
case 'space'
A(length(sum(A,2))-postion(1,2),postion(1,1))=1;
case 'backspace'
A(length(sum(A,2))-postion(1,2),postion(1,1))=0;
case 'b'
control=2;
case 'c'
control=1;
case 'a'
A=zeros(100,100);
control=1;
end
end
end
将两段代码复制粘贴至同一个m文件即可
最后
以上就是糊涂花瓣为你收集整理的matlab 生命游戏 可自己输入图像的全部内容,希望文章能够帮你解决matlab 生命游戏 可自己输入图像所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复