2048游戏matlab代码
- 格式:docx
- 大小:49.22 KB
- 文档页数:5
Python100⾏代码实现2048⼩游戏⾸先我们来看看我们效果图:这是最简版后期可以去优化,后端⾃⼰写⼀个可视化页⾯,或者配上⼀个前端,可以使我们的程序变得更绚丽。
下⾯我们开始我们的代码⼀、构造⼀个把0元素移⾄末尾的函数[2, 4, 0, 2] --> [2, 4, 2, 0]1def zero_end():2"""3 0元素移⾄到末尾4 :param list_merge:5 :return:6"""7for i in range(-1, -len(list_merge) - 1, -1):8if list_merge[i] == 0:9del list_merge[i]10 list_merge.append(0)1112return list_merge⼆、构造⼀个合并相邻的元素的函数[2, 2, 0, 0] --> [4, 0, 0, 0]1def merge():2"""3合并相邻的相同元素4 :param list_merge:5 :return:6"""7for i in range(len(list_merge) - 1):8if list_merge[i] == list_merge[i + 1]:9 list_merge[i] += list_merge[i + 1]10del list_merge[i + 1]11 list_merge.append(0)12return list_merge三、构造⼀个向左移动地图并合并的函数1# @stochastic2# @finish3def move_left():4"""5地图向左移动并合并6 :return:7"""8for line in map_:9global list_merge10 list_merge = line11 zero_end()12 merge()13return map_四、构造⼀个向右移动地图并合并的函数(和向左移动差不多,就是相反放进去相反取出来就好)四、构造⼀个向右移动地图并合并的函数(和向左移动差不多,就是相反放进去相反取出来就好)1# @stochastic2# @finish3def move_right():4"""5地图向右移动并合并6 :return:7"""8for line in map_:9global list_merge10 list_merge = line[::-1]11 zero_end()12 merge()13 line[::-1] = list_merge14return map_五、构造⼀个向上(下)移动地图合并的函数⾸先我们写⼀个移动⽅阵的函数1def square_matrix_transpose(sqr_matrix):2for c in range(0, len(sqr_matrix) - 1):3for r in range(c, len(sqr_matrix)):4 sqr_matrix[r][c], sqr_matrix[c][r] = sqr_matrix[c][r], sqr_matrix[r][c]5return sqr_matrix然后我们开始构造向上移动并合并的函数1 # @stochastic2 # @finish3def move_up():4"""5向上移动⽅阵并合并6 :return:7"""8 square_matrix_transpose(map_)9for line in map_:10global list_merge11 list_merge = line12 zero_end()13 merge()14 square_matrix_transpose(map_)15return map_最后我们开始构造向下移动并合并的函数1# @stochastic2# @finish3def move_down():4"""5向下移动⽅阵并合并6 :return:7"""8 square_matrix_transpose(map_)9for line in map_:10global list_merge11 list_merge = line[::-1]12 zero_end()13 merge()14 line[::-1] = list_merge15 square_matrix_transpose(map_)16return map_到现在我们的总体代码就快写完了,还剩下两个装饰器就⼤功告成了⾸先我们来写每次移动我们随机添加⼀个数字21def stochastic(func, *args, **kwargs):2def lnner(*args, **kwargs):3try:4global one_execute5if not one_execute:6 one_execute = True7print("欢迎体验2048⼩游戏")7print("欢迎体验2048⼩游戏")8return map_9else:10 p = []11 data = func()12for k, v in enumerate(data):13for i, j in enumerate(v):14if j == 0:15 p.append([k, i])16 rand = random.choice(p)17 data[rand[0]][rand[1]] = 218return data19except Exception as e:20print(e)21return"Game over"⾸先我们来写⼀个结束的装饰器1def finish(func, *args, **kwargs):2def lnner(*args, **kwargs):3 now_list = copy.deepcopy(map_)4 data = func()5if now_list == data:6return"Game over"7return data89return lnner现在我们所有的代码就都⼤功告成了,就剩下最后⼀步了,⼤快⼈⼼的时刻来了。
说明:本代码为2048嬉戏matlab代码,程序未进行嬉戏结束判定,节目如下。
function g2048(action)global totalscore flag score_boardif nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h);totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch actioncase'initialize';figure_h=get(gcf,'UserData');set(figure_h,...'Color',[0.4 0.4 0.4],...'Menubar','none',...'Name','2048',...'NumberTitle','off',...'Position',[200 200 320 355],...'Resize','off');axis('off')game_score=uicontrol(figure_h,...'BackgroundColor',[1 1 1],...'ForegroundColor',[0 0 0], ...'HorizontalAlignment','center',...'FontSize',12,...'Units','points',...'Position',[235 305 65 30],...'String','Score',...'Style','edit',...'Tag','game_score');new_game_h=uicontrol(figure_h,...'Callback','g2048 restart',...'FontSize',12, ...'Units','points',...'Position',[35 30 65 30],...'String','New Game',...'Style','pushbutton');% closeclose_h=uicontrol(figure_h,...'Callback','close(gcf)',...'Fontsize',12, ...'Units','points',...'Position',[225 30 65 30],...'String','Close',...'Style','pushbutton');% rightmove_right=uicontrol(figure_h,...'Callback','g2048 right',...'Fontsize',12, ...'Units','points',...'Position',[255 185 60 30],...'String','Right',...'Style','pushbutton');% leftmove_left=uicontrol(figure_h,...'Callback','g2048 left',...'Fontsize',12, ...'Units','points',...'Position',[5 185 60 30],...'String','Left',...'Style','pushbutton');% upmove_up=uicontrol(figure_h,...'Callback','g2048 up',...'Fontsize',12, ...'Units','points',...'Position',[130 300 60 30],...'String','Up',...'Style','pushbutton');% downmove_down=uicontrol(figure_h,...'Callback','g2048 down',...'Fontsize',12, ...'Units','points',...'Position',[130 80 60 30],...'String','Down',...'Style','pushbutton');% setup the game boardirows=1;for counter=1:16jcols=rem(counter,4);if jcols==0j cols=4;endposition=[40*jcols+40 85+40*irows 40 40]; index=(irows-1)*4+jcols;if jcols==4i rows=irows+1;endboard.squares(index)=uicontrol(figure_h,...'FontSize',18,...'FontWeight','bold',...'Units','points',...'Position',position,...'Style','pushbutton',...'Tag',num2str(index));endset(figure_h,'userdata',board);g2048('restart')case'restart'totalscore=0;score_board=zeros(1,16);g2048('addnum') ;g2048('addnum') ;g2048('show')case'show'num_0=find(score_board==0);board=get(gcf,'UserData');set(board.squares,{'string'},num2cell(score_board)')set(board.squares,...'BackgroundColor',[0.701961 0.701961 0.701961],...'Enable','on',...'Visible','on')set(board.squares(num_0),...'BackgroundColor','black',...'Enable','off',...'String',' ');score_handle=findobj(gcf,'Tag','game_score');s et(score_handle,...'String',num2str(totalscore),...'Tag','game_score');case'down'C=score_board;for i=1:4A=[score_board(i) score_board(i+4) score_board(i+8) score_board(i+12)];[B score]=move(A);score_board(i)=B(1); score_board(i+4)=B(2);score_board(i+8)=B(3); score_board(i+12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'up'C=score_board;for i=13:16A=[score_board(i) score_board(i-4) score_board(i-8) score_board(i-12)];[B score]=move(A);score_board(i)=B(1); score_board(i-4)=B(2);score_board(i-8)=B(3); score_board(i-12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'right'C=score_board;for i=4:4:16A=[score_board(i) score_board(i-1) score_board(i-2) score_board(i-3)];[B score]=move(A);score_board(i)=B(1); score_board(i-1)=B(2);score_board(i-2)=B(3); score_board(i-3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'left'C=score_board;for i=1:4:13A=[score_board(i) score_board(i+1) score_board(i+2) score_board(i+3)];[B score]=move(A);score_board(i)=B(1); score_board(i+1)=B(2);score_board(i+2)=B(3); score_board(i+3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'addnum'num_0=find(score_board==0);l=length(num_0);if l>0score_board(num_0(ceil(l*rand)))=2+2*(rand<0.1);endendendfunction Y=addnum(X)num_0=find(X==0);l=length(num_0);X(num_0(ceil(l*rand)))=2+2*(rand<0.1);Y=X;endfunction [B score]=move(A)score=0;for k=1:2for i=1:3if A(i)==0for j=i:3A(j)=A(j+1);endA(4)=0;endendendif A(1)==A(2)if A(3)==A(4)A(1)=A(1)+A(2);A(2)=A(3)+A(4);A(3)=0;A(4)=0;score=A(1)+A(2);else A(1)=A(1)+A(2);A(2)=A(3);A(3)=A(4);A(4)=0;score=A(1);endelse if A(2)==A(3)A(1)=A(1);A(2)=A(2)+A(3);A(3)=A(4);A(4)=0;score=A(2);else if A(3)==A(4)A(1)=A(1);A(2)=A(2);A(3)=A(3)+A(4);A(4)=0;score=A(3);else score=0;endendendB=A;end。
Matlab编写的猜数字游戏一个猜数字的游戏,先随机生成一个1到100之间的整数,由游戏者来猜此数,当输入的数过大,会提示数字大了,当输入的数过小,会提示数字小了,当猜中此数,游戏结束。
好玩而已,呵呵,欢迎共同学习,email:slqinyi@function caishuzi(arg)if nargin < 1arg = 'newgame';endif strcmp(arg,'newgame')clf% set(gcf,'resize','off'); % 禁止调整窗口的大小set(gcf,'name','猜数字Version 1.0') % 修改标题栏set(gcf,'numbertitle','off') % 去掉标题栏中的figure 1num = randint(1,1,100); % 随机产生个一小于100的正整数h_casu = uicontrol(gcf,'style','edit',...'unit','normalized','position',[0.8,0.75,0.08,0.1],...'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',12,'visible','off','string',num2str (num),'tag','t_casu');h_suru = uicontrol(gcf,'style','edit',...'unit','normalized','position',[0.8,0.75,0.08,0.1],...'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',12,'tag','t_suru');h_jisu = uicontrol(gcf,'style','edit',...'unit','normalized','position',[0.75,0.75,0.08,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',12,'visible','off','string',num2str (0),'tag','t_jisu');wz_string = '请输入一个整数(1~100):';h_wenz = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.12,0.75,0.65,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'string',wz_string,'tag','t_wenz');cs_string = '您已输入的次数为0 次';h_cisu = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.12,0.6,0.65,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'string',cs_string,'tag','t_cisu' ;);h_newg = uicontrol(gcf,'style','pushbutton',...'unit','normalized','position',[0.34,0.15,0.17,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'string','新局','callback','caishuzi(''newgame'')',& #39;tag','t_newg');h_tiji = uicontrol(gcf,'style','pushbutton',...'unit','normalized','position',[0.54,0.15,0.17,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'string','提交','callback','caishuzi(''submit'')', 9;tag','t_tiji');h_tuci = uicontrol(gcf,'style','pushbutton',...'unit','normalized','position',[0.74,0.15,0.17,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'string','退出','callback','close','tag','t_tucu'); elseif strcmp(arg,'submit')h_casu = findobj(gcf,'tag','t_casu');h_suru = findobj(gcf,'tag','t_suru');h_jisu = findobj(gcf,'tag','t_jisu');h_cisu = findobj(gcf,'tag','t_cisu');h_tiji = findobj(gcf,'tag','t_tiji');num = str2num(get(h_casu,'string'));ges = str2num(get(h_suru,'string'));jis = str2num(get(h_jisu,'string'));jis = jis+1;set(h_jisu,'string',num2str(jis))cs_string = ['您已输入的次数为' num2str(jis) '次'];set(h_cisu,'string',cs_string);h_jieg = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.12,0.45,0.65,0.1],... 'BackgroundColor',[1,1,1],'ForegroundColor',[0 0 1],...'fontsize',24,'visible','off','tag','t_jie g');if ges==numjg_string = '恭喜您!您答对了!';set(h_jieg,'string',jg_string,'visible','on');set(h_tiji,'enable','off')elseif ges<numjg_string = '您输入的数有点小哦!';set(h_jieg,'string',jg_string,'visible','on');elsejg_string = '您输入的数有点大哦!';set(h_jieg,'string',jg_string,'visible','on');endend。
matlab猜数字游戏程序,matlab猜数字⼩游戏matlab 猜数字1 ~100内猜数游戏规则如下:(1)分为三个等级:选1为10次机会,选2为7次机会,选3为5次机会。
直接回车默认为1(2)如果猜对,⽴即推出,并且输出猜对所⽤的次数。
(3)如果所有机会⽤完并且没有猜对,则输出正确答案。
提⽰是否重玩,选0为继续,选1为退出:若选择0,回到选择等级界⾯。
直接回车默认为1matlab 猜数字1 ~100内猜数游戏规则如下:(1)分为三个等级:选1为10次机会,选2为7次机会,选3为5次机会。
直接回车默认为1(2)如果猜对,⽴即推出,并且输出猜对所⽤的次数。
(3)如果所有机会⽤完并且没有猜对,则输出正确答案。
提⽰是否重玩,选0为继续,选1为退出:若选择0,回到选择等级界⾯。
直接回车默认为1具体代码如下:disp('game begin')disp('please choose level')m=1;while(m==1)leval=input('I choose leval:');if isempty(leval)|leval==1i=1;rd=fix(rand.*100);while(i>=1)&(i<=10)disp('please input the number')num=input('the number=');if (num>rd)disp('oh, big');endif (num==rd)disp('oh, you are right')str=['cishu=',num2str(i)];eval(str)break;endif(numdisp('oh,little')endi=i+1;if (i==11)disp('game over')str=['result=',num2str(rd)]; eval(str)disp('try again?');choose=input('0/1');if choose==0clc;m=1;endif isempty(choose)|choose==1 m=0;clc;endendendendif (leval==2)i=1;rd=fix(rand.*100);while(i>=1)&(i<=7)disp('please input the number') num=input('the number=');if (num>rd)disp('oh, big');endif (num==rd)disp('oh, you are right')str=['cishu=',num2str(i)];eval(str)break;endif(numdisp('oh,little')endi=i+1;if (i==8)disp('game over')str=['result=',num2str(rd)]; eval(str)disp('try again?');choose=input('0/1');if choose==0clcm=1;endif isempty(choose)|choose==1 m=0;clcendendendendif (leval==3)i=1;rd=fix(rand.*100);while(i>=1)&(i<=5)disp('please input the number') num=input('the number=');if (num>rd)disp('oh, big');endif (num==rd)disp('oh, you are right')str=['cishu=',num2str(i)];eval(str)break;endif(numdisp('oh,little')endi=i+1;if (i==6)disp('game over')str=['result=',num2str(rd)]; eval(str)disp('try again?');choose=input('0/1');if choose==0clcm=1;endif isempty(choose)|choose==1 m=0;clcendendendendend。
function guessNumberGame(arg)if nargin == 0arg = 'new';endif strcmp(arg,'new')% ÏȲúÉúËĸö²»Í¬µÄÕûÊýnum = zeros(1,4);for i = 1:4while 1temp = randint(1,1,[1,9]);if isempty(find(num==temp))break;endendnum(i) = temp;endsave('e:\guessnumbergame.mat','num'); % ´æÔÚÓ²ÅÌÉÏÁË£¬ÀÁµÃÈ¥findobjÁËfor i = 1:4s(i) = uicontrol(gcf,'style','edit',...'unit','normalized','position',[0.3+(i-1)*0.1,0.68,0.1,0.17],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],... 'fontsize',24,'fontname','times new roman','tag',['t' num2str(i)]);endt1 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.3,0.52,0.4,0.13],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','ÇëÔÚÊäÈë¿òÄÚÊäÈëËĸö²»Í¬µÄ1-9Ö®¼äµÄÕûÊý');t2 = uicontrol(gcf,'style','pushbutton',...'unit','normalized','position',[0.3,0.15,0.15,0.13],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','ÎÒ²Â','callback','guessNumberGame(''submit '')','tag','tsubmit');t3 = uicontrol(gcf,'style','pushbutton',...'unit','normalized','position',[0.55,0.15,0.15,0.13],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','Í˳ö','callback','close');t4 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.3,0.44,0.4,0.062],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','Êý¶Ôµ«Î»²»¶ÔµÄ¸öÊý£º','horizontalalignment ','left');t5 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.3,0.365,0.4,0.062],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','Êý¶ÔÇÒλÒà¶ÔµÄ¸öÊý£º','horizontalalignment ','left');t6 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.3,0.29,0.4,0.062],...'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','ÄúÒѾ-¾º²ÂÁ˵ĴÎÊý£º','horizontalalignment ','left');t7 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.63,0.44,0.07,0.062],... 'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','0','horizontalalignment','left','tag','t7' );t8 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.63,0.365,0.07,0.062],... 'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','0','horizontalalignment','left','tag','t8' );t9 = uicontrol(gcf,'style','text',...'unit','normalized','position',[0.63,0.29,0.07,0.062],... 'BackgroundColor',[1,1,1],'ForegroundColor',[1 0 0],...'fontsize',14,'string','0','horizontalalignment','left','tag','t9');elseif strcmp(arg,'submit')load('e:\guessnumbergame.mat');for i = 1:4s(i) = findobj(gcf,'tag',['t' num2str(i)]); endtsubmit = findobj(gcf,'tag','tsubmit');t7 = findobj(gcf,'tag','t7');t8 = findobj(gcf,'tag','t8');t9 = findobj(gcf,'tag','t9');count = num2str(str2num(get(t9,'string'))+1); set(t9,'string',count)g_num = zeros(1,4);for i = 1:4temp = str2num(get(s(i),'string'));if isempty(temp)msgbox('Çë°´ÒªÇóÊäÈ룡£¡')break;endg_num(i) = temp;endfor i = 1:4temp = find(g_num==g_num(i));if length(temp)>=2msgbox('ÊäÈëÁËÖØ¸´µÄÊý£¡£¡')break;endend% ¸ü¶àµÄÈÝ´í´¦Àí²»ÏëдÁËnum_corect = 0;num_corpos = 0;for i = 1:4indx = find(num==g_num(i));if ~isempty(indx)if indx == inum_corpos = num_corpos + 1;elsenum_corect = num_corect + 1;endendendset(t7,'string',num2str(num_corect))set(t8,'string',num2str(num_corpos))if num_corpos == 4set(tsubmit,'enable','off')msgbox(['¹§Ï²Äú²ÂÖÐÁË£¬ÄúÒ»¹²²ÂÁË' count '´Î£¡']) endend。
MATLAB计算24点游戏代码第一篇:MATLAB计算24点游戏代码clear,closeall clc a=5;b=7;c=10;d=4;%这里输入需要计算的四个数字a,b,c,d f=[a b c d];tic;g=perms(f);[m,n]=size(g);h='+-*/';fori=1:24 for k1=1:4 for k2=1:4 for k3=1:4str11=[num2str(g(i,1)),h(k1),num2str(g(i,2)),h(k2),num2str(g( i,3)),h(k3),num2str(g(i,4))];str22=['(',num2str(g(i,1)),h(k1),num2str(g(i,2)),')',h(k2),num2s tr(g(i,3)),h(k3),num2str(g(i,4))];str33=['(',num2str(g(i,1)),h(k1),num2str(g(i,2)),h(k2),num2str( g(i,3)),')',h(k3),num2str(g(i,4))];str44=['(',num2str(g(i,1)),h(k1),num2str(g(i,2)),')',h(k2),'(',nu m2str(g(i,3)),h(k3),num2str(g(i,4)),')',];A=str2num(str11);B=str2n um(str22);C=str2num(str33);D=str2num(str44);ifA==24||B==24||C==24||D==24 break else end endif A==24||B==24||C==24||D==24 break else end endif A==24||B==24||C==24||D==24 break else end endif A==24||B==24||C==24||D==24 break else end endif A==24answer=str11;elseif B==24answer=str22;elseif C==24answer=str33;elseif D==24answer=str44;elseanswer='无解';enddisp(['计算方法',num2str(answer)])time=toc;disp(['计算耗时',num2str(time),'s'])第二篇:人脸识别MATLAB代码1.色彩空间转换function[r,g]=rgb_RGB(Ori_Face)R=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_ Face(:,:,3);R1=im2double(R);% 将uint8型转换成double型G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;row=size(Ori_Face,1);% 行像素 column=size(Ori_Face,2);% 列像素 for i=1:row for j=1:columnrr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);end end rrr=mean(rr);r=mean(rrr);ggg=mean(gg);g=mean(ggg);2.均值和协方差t1=imread('D:matlab皮肤库1.jpg');[r1,g1]=rgb_RGB(t1);t2=imread('D:matlab皮肤库2.jpg');[r2,g2]=rgb_RGB(t2);t3=imread('D:matlab皮肤库3.jpg');[r3,g3]=rgb_RGB(t3);t4=imread('D:matlab皮肤库4.jpg');[r4,g4]=rgb_RGB(t4);t5=imread('D:matlab皮肤库5.jpg');[r5,g5]=rgb_RGB(t5);t6=imread('D:matlab皮肤库6.jpg');[r6,g6]=rgb_RGB(t6);t7=imread('D:matlab皮肤库7.jpg');[r7,g7]=rgb_RGB(t7);t8=imread('D:matlab皮肤库8.jpg');[r8,g8]=rgb_RGB(t8);t9=imread('D:matlab皮肤库9.jpg');[r9,g9]=rgb_RGB(t9);t10=imread('D:matlab皮肤库10.jpg');[r10,g10]=rgb_RGB(t10);t11=imread('D:matlab皮肤库11.jpg');[r11,g11]=rgb_RGB(t11);t12=imread('D:matlab皮肤库12.jpg');[r12,g12]=rgb_RGB(t12);t13=imread('D:matlab皮肤库13.jpg');[r13,g13]=rgb_RGB(t13);t14=imread('D:matlab皮肤库14.jpg');[r14,g14]=rgb_RGB(t14);t15=imread('D:matlab皮肤库15.jpg');[r15,g15]=rgb_RGB(t15);t16=imread('D:matlab皮肤库16.jpg');[r16,g16]=rgb_RGB(t16);t17=imread('D:matlab皮肤库17.jpg');[r17,g17]=rgb_RGB(t17);t18=imread('D:matlab皮肤库18.jpg');[r18,g18]=rgb_RGB(t18);t19=imread('D:matlab皮肤库19.jpg');[r19,g19]=rgb_RGB(t19);t20=imread('D:matlab皮肤库20.jpg');[r20,g20]=rgb_RGB(t20);t21=imread('D:matlab皮肤库21.jpg');[r21,g21]=rgb_RGB(t21);t22=imread('D:matlab皮肤库22.jpg');[r22,g22]=rgb_RGB(t22);t23=imread('D:matlab皮肤库23.jpg');[r23,g23]=rgb_RGB(t23);t24=imread('D:matlab皮肤库24.jpg');[r24,g24]=rgb_RGB(t24);t25=imread('D:matlab皮肤库25.jpg');[r25,g25]=rgb_RGB(t25);t26=imread('D:matlab皮肤库26.jpg');[r26,g26]=rgb_RGB(t26);t27=imread('D:matlab皮肤库27.jpg');[r27,g27]=rgb_RGB(t27);r=cat(1,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17 ,r18,r19,r20,r21,r22,r23,r24,r25,r26,r27);g=cat(1,g1,g2,g3,g4,g5,g6,g7,g8,g9,g10,g11,g12,g13,g14,g1 5,g16,g17,g18,g19,g20,g21,g22,g23,g24,g25,g26,g27);m=mean( [r,g])n=cov([r,g])3.求质心function [xmean, ymean] = center(bw)bw=bwfill(bw,'holes');area = bwarea(bw);[m n] =size(bw);bw=double(bw);xmean =0;ymean = 0;for i=1:m, for j=1:n,xmean = xmean + j*bw(i,j);ymean = ymean + i*bw(i,j);end;end;if(area==0)xmean=0;ymean=0;elsexmean = xmean/area;ymean = ymean/area;xmean = round(xmean);ymean = round(ymean);end4.求偏转角度function [theta] = orient(bw,xmean,ymean)[m n]=size(bw);bw=double(bw);a = 0;b = 0;c = 0;for i=1:m, for j=1:n,a = a +(jxmean)*(iymean)^2 * bw(i,j);end;end;b = 2 * b;theta = atan(b/(a-c))/2;theta = theta*(180/pi);% 从幅度转换到角度 5.找区域边界function [left, right, up, down] = bianjie(A)[m n] = size(A);left =-1;right =-1;up =-1;down =-1;for j=1:n,for i=1:m,if(A(i,j)~= 0) left = j;break;end;end;if(left ~=-1)break;end;end;for j=n:-1:1, for i=1:m, if(A(i,j)~= 0)right = j;break;end;end;if(right ~=-1)break;end;end;for i=1:m, for j=1:n,if(A(i,j)~= 0) up = i;break;end;end;if(up ~=-1)break;end;end;for i=m:-1:1,for j=1:n,if(A(i,j)~= 0)down = i;break;end;end;if(down ~=-1)break;end;end;6.求起始坐标function newcoord = checklimit(coord,maxval)newcoord = coord;if(newcoord<1)newcoord=1;end;if(newcoord>maxval)newcoord=maxval;end;7.模板匹配function [ccorr, mfit, RectCoord] = mobanpipei(mult, frontalmodel,ly,wx,cx, cy, angle)frontalmodel=rgb2gray(frontalmodel);model_rot = imresize(frontalmodel,[ly wx],'bilinear');% 调整模板大小 model_rot = imrotate(model_rot,angle,'bilinear');% 旋转模板 [l,r,u,d] = bianjie(model_rot);% 求边界坐标 bwmodel_rot=imcrop(model_rot,[l u(r-l)(d-u)]);% 选择模板人脸区域 [modx,mody] =center(bwmodel_rot);% 求质心 [morig, norig] = size(bwmodel_rot);% 产生一个覆盖了人脸模板的灰度图像mfit = zeros(size(mult));mfitbw = zeros(size(mult));[limy, limx] = size(mfit);% 计算原图像中人脸模板的坐标 startx = cx-modx;starty = cy-mody;endx = startx + norig-1;endy = starty + morig-1;startx = checklimit(startx,limx);starty = checklimit(starty,limy);endx = checklimit(endx,limx);endy = checklimit(endy,limy);for i=starty:endy, for j=startx:endx,mfit(i,j)= model_rot(i-starty+1,j-startx+1);end;end;ccorr = corr2(mfit,mult)% 计算相关度 [l,r,u,d] = bianjie(bwmodel_rot);sx = startx+l;sy = starty+u;RectCoord = [sx sy(r-1)(d-u)];% 产生矩形坐标 8.主程序 clear;[fname,pname]=uigetfile({'*.jpg';'*.bmp';'*.tif';'*.gif'},'Please choose a color picture...');% 返回打开的图片名与图片路径名 [u,v]=size(fname);y=fname(v);% 图片格式代表值switch ycase 0errordlg('You Should Load Image File First...','Warning...');case{'g';'G';'p';'P';'f';'F'};% 图片格式若是JPG/jpg、BMP/bmp、TIF/tif或者GIF/gif,才打开I=cat(2,pname,fname);Ori_Face=imread(I);subplot(2,3,1),imshow(Ori_Face);otherwiseerrordlg('You Should Load Image File First...','Warning...');end R=Ori_Face(:,:,1);G=Ori_Face(:,:,2);B=Ori_Face(:,:,3);R1=im2double(R);% 将uint8型转换成double型处理G1=im2double(G);B1=im2double(B);RGB=R1+G1+B1;m=[ 0.4144,0.3174];% 均值 n=[0.0031,-0.0004;-0.0004,0.0003];% 方差 row=size(Ori_Face,1);% 行像素数 column=size(Ori_Face,2);% 列像素数 for i=1:rowfor j=1:columnif RGB(i,j)==0rr(i,j)=0;gg(i,j)=0;elserr(i,j)=R1(i,j)/RGB(i,j);gg(i,j)=G1(i,j)/RGB(i,j);x=[rr(i,j),gg(i,j)];p(i,j)=exp((-0.5)*(x-m)*inv(n)*(x-m)');endend endsubplot(2,3,2);imshow(p);low_pass=1/9*ones(3);image_low=filter2(low_pass, p);subplot(2,3,3);imshow(image_low);% 自适应阀值程序previousSkin2 = zeros(i,j);changelist = [];for threshold = 0.55:-0.1:0.05 two_value = zeros(i,j);two_value(find(image_low>threshold))= 1;change = sum(sum(two_valuel +1);% 宽度 ly =(d-u + 1);% 高度 wratio = ly/wx% 高宽比if((0.8<=wratio)&(wratio<=2))% 如果目标区域的高度/宽度比例大于0.8且小于2.0,则将其选出进行下一步运算S=ly*wx;% 计算包含此区域矩形的面积A=bwarea(bwsegment);% 计算此区域面积if(A/S>0.35)[ccorr,mfit, RectCoord] = mobanpipei(justface,frontalmodel,ly,wx, cx,cy, angle);endif(ccorr>=0.6)mfitbw=(mfit>=1);invbw = xor(mfitbw,ones(size(mfitbw)));source_with_hole = uint8(double(invbw).* double(imsourcegray));final_image = uint8(double(source_with_hole)+ double(mfit));subplot(2,3,5);imshow(final_image);% 显示覆盖了模板脸的灰度图像imsourcegray = final_image;subplot(2,3,6);imshow(Ori_Face);% 显示检测效果图end;if(RectCoord ~=-1)FaceCoord = [FaceCoord;RectCoord];endend end end% 在认为是人脸的区域画矩形[numfaces x] = size(FaceCoord);for i=1:numfaces,hd = rectangle('Position',FaceCoord(i,:));set(hd, 'edgecolor', 'y');end 人脸检测是人脸识别、人机交互、智能视觉监控等工作的前提。
Game_manager.js:Size of the grid: 网格尺寸Clear the game won/lost message:清除游戏信息Restart the game:重启游戏Keep playing after winning (allows going over 2048):继续玩夺冠后(允许将超过2048)Return true if the game is lost, or has won and the user hasn't kept playing:返回true,如果比赛丢失,或者赢得了与用户尚未保存播放Set up the game:设置游戏Reload the game from a previous game if present:从以前的游戏重新载入游戏(如果存在);Reload grid:重置网格Add the initial tiles:添加初始铺Update the actuator:更新驱动器Set up the initial tiles to start the game with:设置初始地砖与开始游戏Adds a tile in a random position:在添加一个随机位置的砖Sends the updated grid to the actuator:发送更新的网格到致动器Clear the state when the game is over (game over only, not win):清除状态时,游戏结束(GAME OVER而已,不是赢)Represent the current game as an object:表示当前游戏为对象Save all tile positions and remove merger info:保存所有瓷砖的位置和删除合并信息Move a tile and its representation:移动动态砖及其表示Move tiles on the grid in the specified direction:移动网格上的瓷砖在指定的方向Don't do anything if the game's over:不要做任何事情,如果本场比赛的过了ave the current tile positions and remove merger information:等皆目前瓷砖的位置和删除信息的合并Traverse the grid in the right direction and move tiles:穿越网格在正确的方向和移动的瓷砖Only one merger per row traversal?:只有每行遍历1合并呢?Converge the two tiles' positions:衔接两地砖的立场Update the score:更新比分The mighty 2048 tile:到2048The tile moved from its original cell! 瓷砖从原来的电池移动!Game over! :游戏结束Get the vector representing the chosen direction:获取表示所选择的方向向量Vectors representing tile movement:代表瓷砖的运动向量Build a list of positions to traverse in the right order:建立位置的列表按照正确的顺序来遍历。
#include <iostream>#include <iomanip>#include <cstdlib>#include <ctime>#include <string>#include <memory>// 2的概率大于4#define random_2_4 (rand()%5==4 ? 4:2)#define random_x(x) (rand()%x)using namespace std;// 矩阵大小const int MAX = 4;const int MAXMAX = MAX*MAX;// 初始数据个数const int INIT_SIZE = 2;// 数据矩阵int _matrix[MAX][MAX];// 合并临时数组int current[MAX];// 数据计数int _count;// 按键操作 => 不使用char...防止不必要的失败... => ch[0]即可... string ch;// 得分...int score;// 打印数组void print();// 操作说明void help();// 初始操作void init();// 随机位置 => 随机数据2/4bool random_data_one();// 上左下右bool b_up();bool b_left();bool b_down();bool b_right();void _up();void _left();void _down();void _right();int main(){init();print();while (b_up() || b_left() || b_down() || b_right()){help();switch (ch[0]){case 'w':_up();break;case 'a':_left();break;case 's':_down();break;case 'd':_right();break;default:cout <<"无效输入..."<< endl << endl; break;}print();}cout << " Game Over !! " << endl;cout << "最终得分Socre => " << score << endl;system("pause");system("pause");system("pause");return 0;}void print(){int j;cout << "-------------------------------------" << endl; cout << "得分Socre => " << score << endl;cout << "-------------------------------------" << endl;for (int i = 0; i < MAX; i++){for ( j = 0; j < MAX; j++){if (_matrix[i][j])cout << setw(5) << _matrix[i][j] << " |";elsecout << setw(7) << " |";}cout << endl;}cout << "-------------------------------------" << endl << endl;; }void help(){cout << "wasd => 上左下右" << endl;cout << "请输入: ";cin >> ch;}void init(){_count = 0;score = 0;srand((int)time(0));for (int i = 0; i < INIT_SIZE; i++)random_data_one();}bool random_data_one(){if (_count == MAXMAX)return false;int left = MAXMAX - _count;int tmp = random_x(left);int num = random_2_4;int k = 0;for (int i = 0; i < MAX; i++){for (int j = 0; j < MAX; j++){if (_matrix[i][j] == 0){if (k++ == tmp){_matrix[i][j] = num;break;}}}}++_count;return true;}bool b_up(){int j;for (int k = 0; k < MAX; k++){// 特殊情况...这一列有空元素...bool flag = false;for (int i = 0; i < MAX - 1; i++){if (_matrix[i][k] == 0)flag = true;else{int j = i + 1;while (j < MAX){if (_matrix[j][k]){if (_matrix[i][k] == _matrix[j][k]) return true;elsebreak;}else{++j;}}}}if (flag){// 空元素上方有元素则为True...// 使用左右夹击法...int i = 0, j = MAX - 1;while (i < MAX){if (_matrix[i][k])++i;elsebreak;}while (j >= 0){if (_matrix[j][k] == 0)--j;elsebreak;}if (i < j)return true;}}return false;}bool b_left(){for (int k = 0; k < MAX; k++){// 特殊情况...这一行有空元素...bool flag = false;for (int i = 0; i < MAX - 1; i++){if (_matrix[k][i] == 0)flag = true;else{int j = i + 1;while (j < MAX){if (_matrix[k][j]){if (_matrix[k][i] == _matrix[k][j]) return true;elsebreak;}else{++j;}}}}if (flag){// 空元素右边有元素则为True...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是空元素位置,j是非空元素位置 while (i < MAX){if (_matrix[k][i])++i;elsebreak;}while (j >= 0){if (_matrix[k][j] == 0)--j;elsebreak;}if (i < j)return true;}}return false;}bool b_down(){for (int k = 0; k < MAX; k++){// 特殊情况...这一列有空元素...bool flag = false;for (int i = MAX - 1; i > 0; i--){if (_matrix[i][k] == 0)flag = true;else{int j = i - 1;while (j >= 0){if (_matrix[j][k]){if (_matrix[i][k] == _matrix[j][k])return true;elsebreak;}else{--j;}}}}if (flag){// 空元素上方有元素则为True... => 下边第一个空元素在上边第一个非空元素下边即可...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是非空位置,j是空元素位置while (i < MAX){if (_matrix[i][k] == 0)++i;elsebreak;}while (j >= 0){if (_matrix[j][k])--j;elsebreak;}if (i < j)return true;}}return false;}bool b_right(){for (int k = 0; k < MAX; k++){// 特殊情况...这一行这一行有空元素...bool flag = false;for (int i = MAX - 1; i > 0; i--){if (_matrix[k][i] == 0)flag = true;else{int j = i - 1;while (j >= 0){if (_matrix[k][j]){if (_matrix[k][i] == _matrix[k][j])return true;elsebreak;}else{--j;}}}}if (flag){// 空元素左边有元素则为True... => 右边第一个空元素在左边第一个非空元素右边即可...// 使用左右夹击法...int i = 0, j = MAX - 1;// i 是非空位置,j是空元素位置while (i < MAX){if (_matrix[k][i] == 0)++i;elsebreak;}while (j >= 0){if (_matrix[k][j])--j;elsebreak;}if (i < j)return true;}}return false;}void _up(){cout << "按下了上键" << endl << endl;if (b_up()){cout << "可以向上合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX); int ii = 0;for (int j = 0; j < MAX; j++){if (_matrix[j][i])current[ii++] = _matrix[j][i]; }for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]) {current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = 0;for ( j = 0; j < MAX; j++){if (current[j])_matrix[ii++][i] = current[j]; }for (; ii < MAX; ii++)_matrix[ii][i] = 0;}random_data_one();}else{cout << "向上无效" << endl << endl; }}void _left(){cout << "按下了左键" << endl << endl;if (b_left()){cout << "可以向左合并" << endl << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = 0; j < MAX; j++){if (_matrix[i][j])current[ii++] = _matrix[i][j];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = 0;for ( j = 0; j < MAX; j++){if (current[j])_matrix[i][ii++] = current[j];}for (; ii < MAX; ii++)_matrix[i][ii] = 0;}random_data_one();}else{cout << "向左无效" << endl << endl; }}void _down(){cout << "按下了下键" << endl << endl;if (b_down()){cout << "可以向下合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = MAX - 1; j >= 0; j--){if (_matrix[j][i])current[ii++] = _matrix[j][i];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = MAX - 1;for ( j = 0; j < MAX; j++){if (current[j])_matrix[ii--][i] = current[j];}for (; ii >= 0; ii--)_matrix[ii][i] = 0;}random_data_one();}else{cout << "向下无效" << endl << endl; }}void _right(){cout << "按下了右键" << endl << endl;if (b_right()){cout << "可以向右合并" << endl;for (int i = 0; i < MAX; i++){memset(current, 0, sizeof(int)*MAX);int ii = 0;for (int j = MAX - 1; j >= 0; j--){if (_matrix[i][j])current[ii++] = _matrix[i][j];}for (int k = 0; k < ii - 1; k++){if (current[k] == current[k + 1]){current[k] *= 2;score += current[k];current[k + 1] = 0;++k;--_count;}}ii = MAX - 1;for ( j = 0; j < MAX; j++){if (current[j])_matrix[i][ii--] = current[j];}for (; ii >= 0; ii--)_matrix[i][ii] = 0;}random_data_one();}else{cout << "向右无效" << endl << endl;}}//</memory></string></ctime></cstdlib></iomanip></iostream>。
说明:本代码为2048游戏matlab代码,程序未进行游戏结束判定,节目如下。
function g2048(action)global totalscore flag score_boardif nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h);totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch actioncase'initialize';figure_h=get(gcf,'UserData');set(figure_h,...'Color',[0.4 0.4 0.4],...'Menubar','none',...'Name','2048',...'NumberTitle','off',...'Position',[200 200 320 355],...'Resize','off');axis('off')game_score=uicontrol(figure_h,...'BackgroundColor',[1 1 1],...'ForegroundColor',[0 0 0], ...'HorizontalAlignment','center',...'FontSize',12,...'Units','points',...'Position',[235 305 65 30],...'String','Score',...'Style','edit',...'Tag','game_score');new_game_h=uicontrol(figure_h,...'Callback','g2048 restart',...'FontSize',12, ...'Units','points',...'Position',[35 30 65 30],...'String','New Game',...'Style','pushbutton');% closeclose_h=uicontrol(figure_h,...'Callback','close(gcf)',...'Fontsize',12, ...'Units','points',...'Position',[225 30 65 30],...'String','Close',...'Style','pushbutton');% rightmove_right=uicontrol(figure_h,...'Callback','g2048 right',...'Fontsize',12, ...'Units','points',...'Position',[255 185 60 30],...'String','Right',...'Style','pushbutton');% leftmove_left=uicontrol(figure_h,...'Callback','g2048 left',...'Fontsize',12, ...'Units','points',...'Position',[5 185 60 30],...'String','Left',...'Style','pushbutton');% upmove_up=uicontrol(figure_h,...'Callback','g2048 up',...'Fontsize',12, ...'Units','points',...'Position',[130 300 60 30],...'String','Up',...'Style','pushbutton');% downmove_down=uicontrol(figure_h,...'Callback','g2048 down',...'Fontsize',12, ...'Units','points',...'Position',[130 80 60 30],...'String','Down',...'Style','pushbutton');% setup the game boardirows=1;for counter=1:16jcols=rem(counter,4);if jcols==0jcols=4;endposition=[40*jcols+40 85+40*irows 40 40]; index=(irows-1)*4+jcols;if jcols==4irows=irows+1;endboard.squares(index)=uicontrol(figure_h,...'FontSize',18,...'FontWeight','bold',...'Units','points',...'Position',position,...'Style','pushbutton',...'Tag',num2str(index));endset(figure_h,'userdata',board);g2048('restart')case'restart'totalscore=0;score_board=zeros(1,16);g2048('addnum') ;g2048('addnum') ;g2048('show')case'show'num_0=find(score_board==0);board=get(gcf,'UserData');set(board.squares,{'string'},num2cell(score_board)')set(board.squares,...'BackgroundColor',[0.701961 0.701961 0.701961],...'Enable','on',...'Visible','on')set(board.squares(num_0),...'BackgroundColor','black',...'Enable','off',...'String',' ');score_handle=findobj(gcf,'Tag','game_score');set(score_handle,...'String',num2str(totalscore),...'Tag','game_score');case'down'C=score_board;for i=1:4A=[score_board(i) score_board(i+4) score_board(i+8) score_board(i+12)];[B score]=move(A);score_board(i)=B(1); score_board(i+4)=B(2);score_board(i+8)=B(3); score_board(i+12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'up'C=score_board;for i=13:16A=[score_board(i) score_board(i-4) score_board(i-8) score_board(i-12)];[B score]=move(A);score_board(i)=B(1); score_board(i-4)=B(2);score_board(i-8)=B(3); score_board(i-12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'right'C=score_board;for i=4:4:16A=[score_board(i) score_board(i-1) score_board(i-2) score_board(i-3)];[B score]=move(A);score_board(i)=B(1); score_board(i-1)=B(2);score_board(i-2)=B(3); score_board(i-3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'left'C=score_board;for i=1:4:13A=[score_board(i) score_board(i+1) score_board(i+2) score_board(i+3)];[B score]=move(A);score_board(i)=B(1); score_board(i+1)=B(2);score_board(i+2)=B(3); score_board(i+3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'addnum'num_0=find(score_board==0);l=length(num_0);if l>0score_board(num_0(ceil(l*rand)))=2+2*(rand<0.1);endendendfunction Y=addnum(X)num_0=find(X==0);l=length(num_0);X(num_0(ceil(l*rand)))=2+2*(rand<0.1);Y=X;endfunction [B score]=move(A)score=0;for k=1:2for i=1:3if A(i)==0for j=i:3A(j)=A(j+1);endA(4)=0;endendendif A(1)==A(2)if A(3)==A(4)A(1)=A(1)+A(2);A(2)=A(3)+A(4);A(3)=0;A(4)=0;score=A(1)+A(2);else A(1)=A(1)+A(2);A(2)=A(3);A(3)=A(4);A(4)=0;score=A(1);endelse if A(2)==A(3)A(1)=A(1);A(2)=A(2)+A(3);A(3)=A(4);A(4)=0;score=A(2);else if A(3)==A(4)A(1)=A(1);A(2)=A(2);A(3)=A(3)+A(4);A(4)=0;score=A(3);else score=0;endendendB=A;end。