教你用Matlab制作黄金矿工小游戏

 更新时间:2022年03月02日 14:32:41   作者:slandarer  
黄金矿工作为经典的单机小游戏,一直深受大家的喜爱。本文将用Matlab制作这一款经典的游戏,文中的实现步骤讲解详细,感兴趣的可以了解一下

效果

步骤

图片准备

本文所使用图片在这

背景构建

function goldMiner
Mainfig=figure('units','pixels','position',[50 100 750 500],...
                       'Numbertitle','off','menubar','none','resize','off',...
                       'name','goldMiner');
axes('parent',Mainfig,'position',[0 0 1 1],...
   'XLim', [0 750],...
   'YLim', [0 500],...
   'NextPlot','add',...
   'layer','bottom',...
   'Visible','on',...
   'YDir','reverse',...
   'XTick',[], ...
   'YTick',[]);

bkgPic=imread('.\pic\bkg.png');
image([0,750],[0,500],bkgPic)

[manPic,~,manAlp]=imread('.\pic\man.png');
image([400-60,400+60],[49.5-45,49.5+45],manPic,'AlphaData',manAlp)

绘制爪子

由于爪子要不断调整角度因此用surface格式绘制,我们需要将爪子图片矩阵范围调整至[0,1],并将透明处数值调成nan

[clawPic,~,clawAlp]=imread('.\Pic\claw.png');
clawPic=double(clawPic)./255;
clawPicR=clawPic(:,:,1);
clawPicG=clawPic(:,:,2);
clawPicB=clawPic(:,:,3);
clawPicR(clawAlp<1)=nan;
clawPicG(clawAlp<1)=nan;
clawPicB(clawAlp<1)=nan;
clawPic(:,:,1)=clawPicR;
clawPic(:,:,2)=clawPicG;
clawPic(:,:,3)=clawPicB;

clawPos=[380,75];
ropePos=[380,75];

[xgrid,ygrid]=meshgrid((1:size(clawAlp,2))./2,(1:size(clawAlp,1))./2);
xgrid=xgrid-size(clawAlp,2)/4;

thetaList=linspace(-2*pi/5,2*pi/5,50);
thetaIndex=1;
theta=thetaList(thetaIndex);%当前爪子转动角度
v=0;%爪子下移速度
dir=1;%1或-1爪子转动方向
grabbing=false;%是否正在抓取石块

cost=cos(theta);
sint=sin(theta);
rotateX=cost.*xgrid+sint.*ygrid;
rotateY=cost.*ygrid-sint.*xgrid;

drawClawHdl=surface(rotateX+clawPos(1),rotateY+clawPos(2),...
            zeros(size(clawAlp)),clawPic,...
            'EdgeColor','none');
drawLineHdl=plot([clawPos(1),ropePos(1)],[clawPos(2),ropePos(2)],'k','LineWidth',2);

让爪子转起来

爪子旋转就是单纯的使用旋转矩阵:

fps=20;
game=timer('ExecutionMode', 'FixedRate', 'Period',1/fps, 'TimerFcn', @minergame);
start(game)

    function minergame(~,~)
        if ~grabbing
            switch 1
                case thetaIndex==1,dir=1;
                case thetaIndex==50,dir=-1;
            end
            thetaIndex=thetaIndex+dir;
            theta=thetaList(thetaIndex);
            cost=cos(theta);
            sint=sin(theta);
            rotateX=cost.*xgrid+sint.*ygrid;
            rotateY=cost.*ygrid-sint.*xgrid;
        else
        end
    end

绘制石块

stoneName={'gold','gold','stone1','stone2','diamond'};
stonePic{length(stoneName)}=[];
stoneAlp{length(stoneName)}=[];
for i=1:length(stoneName)
    [C,~,Alp]=imread(['.\pic\',stoneName{i},'.png']);
    stonePic{i}=C;
    stoneAlp{i}=Alp;
end
stoneV=[-2,-3,-3,-3,-5];%拿起石头后爪子移动速度
stonePrice=[800,500,200,100,1000];
stoneSize=[50,50;30,30;24,20;15,12;8,8];


stonePos=[200,300;400,350;500,200;50,240;50,300;
          700,420;170,180];
stoneType=[1,2,3,4,5,1,2];
stoneTag=1:length(stoneType);
stoneXrange=[stonePos(:,1)-stoneSize(stoneType',1),stonePos(:,1)+stoneSize(stoneType',1)];
stoneYrange=[stonePos(:,2)-stoneSize(stoneType',2),stonePos(:,2)+stoneSize(stoneType',2)];

for i=1:length(stoneTag)
    drawStone(stonePos(i,:),stoneType(i),stoneTag(i))   
end

    function drawStone(pos,i,j)
        image([-stoneSize(i,1),stoneSize(i,1)]+pos(1),...
              [-stoneSize(i,2),stoneSize(i,2)]+pos(2),...
              stonePic{i},...
              'AlphaData',stoneAlp{i},...
              'UserData',j)  
    end

点击下箭头移动爪子

set(gcf, 'KeyPressFcn', @key)

	function key(~,event)
        switch event.Key
            case 'downarrow'
                grabbing=true;v=4;
        end
    end

function minergame(~,~)
        if ~grabbing
            %这里是让爪子转动的一堆代码
            %。。。。。。。。。。。。。
            %。。。。。。。。。。。。。
        else
            cost=cos(theta);
            sint=sin(theta);
            clawPos=clawPos+[sint,cost].*v;
        end
        set(drawClawHdl,'XData',rotateX+clawPos(1),'YData',rotateY+clawPos(2));
        set(drawLineHdl,'XData',[clawPos(1),ropePos(1)],'YData',[clawPos(2),ropePos(2)]);
    end

爪子与石头和边缘碰触判断

function n=touchThing(clawPos)
        n=0;
        if clawPos(1)<20||clawPos(1)>730||clawPos(2)>480
            n=-1;     
        end
        flagX=clawPos(1)>=stoneXrange(:,1)&clawPos(1)<=stoneXrange(:,2);
        flagY=clawPos(2)>=stoneYrange(:,1)&clawPos(2)<=stoneYrange(:,2);
        flagXY=flagX&flagY;
        if any(flagXY)
            n=find(flagXY);
        end
    end

抓取石块和显示金钱

holdOnType=0;
drawHoldOnHdl=image([0,1],[0,1],ones(1,1),'AlphaData',zeros(1,1));

text(10,40,'Money:','FontSize',20,'Color',[1 1 1],'FontName','Cambria','FontWeight','bold')
money=0;
moneyStrHdl=text(110,40,'$0','FontSize',20,'Color',[0.5137 0.7882 0.2157],'FontName','Cambria','FontWeight','bold');    

	function minergame(~,~)
        if ~grabbing
            switch 1
                case thetaIndex==1,dir=1;
                case thetaIndex==50,dir=-1;
            end
            thetaIndex=thetaIndex+dir;
            theta=thetaList(thetaIndex);
            cost=cos(theta);
            sint=sin(theta);
            rotateX=cost.*xgrid+sint.*ygrid;
            rotateY=cost.*ygrid-sint.*xgrid;
        else
            cost=cos(theta);
            sint=sin(theta);
            clawPos=clawPos+[sint,cost].*v;
            
            n=touchThing(clawPos+5.*[sint,cost]);
            if n==-1
                v=-abs(v);
            elseif n>0
                delete(findobj('UserData',stoneTag(n)));
                v=stoneV(stoneType(n));
                holdOnType=stoneType(n);
                stonePos(n,:)=[];
                stoneType(n)=[];
                stoneTag(n)=[];
                stoneXrange(n,:)=[];
                stoneYrange(n,:)=[];
                set(drawHoldOnHdl,...
                    'XData',[-stoneSize(holdOnType,1),stoneSize(holdOnType,1)]+clawPos(1)+norm(stoneSize(holdOnType,:))*sint,...
                    'YData',[-stoneSize(holdOnType,2),stoneSize(holdOnType,2)]+clawPos(2)+norm(stoneSize(holdOnType,:))*cost,...
                    'CData',stonePic{holdOnType},'AlphaData',stoneAlp{holdOnType});
            end  
            
            if clawPos(2)<=ropePos(2)
                clawPos=ropePos;
                grabbing=false;
                if holdOnType>0
                    money=money+stonePrice(holdOnType);
                    set(moneyStrHdl,'String',['$',num2str(money)])
                end
                holdOnType=0;
                set(drawHoldOnHdl,'XData',[0,1],...
                                  'YData',[0,1],...
                                  'CData',ones(1,1),...
                                  'AlphaData',zeros(1,1));                  
            end
            if holdOnType~=0
                set(drawHoldOnHdl,...
                    'XData',[-stoneSize(holdOnType,1),stoneSize(holdOnType,1)]+clawPos(1)+norm(stoneSize(holdOnType,:))*sint,...
                    'YData',[-stoneSize(holdOnType,2),stoneSize(holdOnType,2)]+clawPos(2)+norm(stoneSize(holdOnType,:))*cost);
            end
        end
        
        
        set(drawClawHdl,'XData',rotateX+clawPos(1),'YData',rotateY+clawPos(2));
        set(drawLineHdl,'XData',[clawPos(1),ropePos(1)],'YData',[clawPos(2),ropePos(2)]);
    end

完整代码

function goldMiner
Mainfig=figure('units','pixels','position',[50 100 750 500],...
                       'Numbertitle','off','menubar','none','resize','off',...
                       'name','goldMiner');
axes('parent',Mainfig,'position',[0 0 1 1],...
   'XLim', [0 750],...
   'YLim', [0 500],...
   'NextPlot','add',...
   'layer','bottom',...
   'Visible','on',...
   'YDir','reverse',...
   'XTick',[], ...
   'YTick',[]);

bkgPic=imread('.\pic\bkg.png');
image([0,750],[0,500],bkgPic)

[manPic,~,manAlp]=imread('.\pic\man.png');
image([400-60,400+60],[49.5-45,49.5+45],manPic,'AlphaData',manAlp)

[clawPic,~,clawAlp]=imread('.\Pic\claw.png');
clawPic=double(clawPic)./255;
clawPicR=clawPic(:,:,1);
clawPicG=clawPic(:,:,2);
clawPicB=clawPic(:,:,3);
clawPicR(clawAlp<1)=nan;
clawPicG(clawAlp<1)=nan;
clawPicB(clawAlp<1)=nan;
clawPic(:,:,1)=clawPicR;
clawPic(:,:,2)=clawPicG;
clawPic(:,:,3)=clawPicB;

clawPos=[380,75];
ropePos=[380,75];

[xgrid,ygrid]=meshgrid((1:size(clawAlp,2))./2,(1:size(clawAlp,1))./2);
xgrid=xgrid-size(clawAlp,2)/4;

thetaList=linspace(-2*pi/5,2*pi/5,50);
thetaIndex=1;
theta=thetaList(thetaIndex);v=0;
dir=1;grabbing=false;

cost=cos(theta);
sint=sin(theta);
rotateX=cost.*xgrid+sint.*ygrid;
rotateY=cost.*ygrid-sint.*xgrid;

drawClawHdl=surface(rotateX+clawPos(1),rotateY+clawPos(2),...
            zeros(size(clawAlp)),clawPic,...
            'EdgeColor','none');
drawLineHdl=plot([clawPos(1),ropePos(1)],[clawPos(2),ropePos(2)],'k','LineWidth',2);
%stone part======================================================
stoneName={'gold','gold','stone1','stone2','diamond'};
stonePic{length(stoneName)}=[];
stoneAlp{length(stoneName)}=[];
for i=1:length(stoneName)
    [C,~,Alp]=imread(['.\pic\',stoneName{i},'.png']);
    stonePic{i}=C;
    stoneAlp{i}=Alp;
end
stoneV=[-2,-3,-3,-3,-5];
stonePrice=[800,500,200,100,1000];
stoneSize=[50,50;30,30;24,20;15,12;8,8];


stonePos=[200,300;400,350;500,200;50,240;50,300;
          700,420;170,180];
stoneType=[1,2,3,4,5,1,2];
stoneTag=1:length(stoneType);
stoneXrange=[stonePos(:,1)-stoneSize(stoneType',1),stonePos(:,1)+stoneSize(stoneType',1)];
stoneYrange=[stonePos(:,2)-stoneSize(stoneType',2),stonePos(:,2)+stoneSize(stoneType',2)];

for i=1:length(stoneTag)
    drawStone(stonePos(i,:),stoneType(i),stoneTag(i))   
end

    function drawStone(pos,i,j)
        image([-stoneSize(i,1),stoneSize(i,1)]+pos(1),...
              [-stoneSize(i,2),stoneSize(i,2)]+pos(2),...
              stonePic{i},...
              'AlphaData',stoneAlp{i},...
              'UserData',j)  
    end

holdOnType=0;
drawHoldOnHdl=image([0,1],[0,1],ones(1,1),'AlphaData',zeros(1,1));

text(10,40,'Money:','FontSize',20,'Color',[1 1 1],'FontName','Cambria','FontWeight','bold')
money=0;
moneyStrHdl=text(110,40,'$0','FontSize',20,'Color',[0.5137 0.7882 0.2157],'FontName','Cambria','FontWeight','bold');

%==========================================================================    
set(gcf, 'KeyPressFcn', @key)
fps=20;
game=timer('ExecutionMode', 'FixedRate', 'Period',1/fps, 'TimerFcn', @minergame);
start(game)

    function minergame(~,~)
        if ~grabbing
            switch 1
                case thetaIndex==1,dir=1;
                case thetaIndex==50,dir=-1;
            end
            thetaIndex=thetaIndex+dir;
            theta=thetaList(thetaIndex);
            cost=cos(theta);
            sint=sin(theta);
            rotateX=cost.*xgrid+sint.*ygrid;
            rotateY=cost.*ygrid-sint.*xgrid;
        else
            cost=cos(theta);
            sint=sin(theta);
            clawPos=clawPos+[sint,cost].*v;
            
            n=touchThing(clawPos+5.*[sint,cost]);
            if n==-1
                v=-abs(v);
            elseif n>0
                delete(findobj('UserData',stoneTag(n)));
                v=stoneV(stoneType(n));
                holdOnType=stoneType(n);
                stonePos(n,:)=[];
                stoneType(n)=[];
                stoneTag(n)=[];
                stoneXrange(n,:)=[];
                stoneYrange(n,:)=[];
                set(drawHoldOnHdl,...
                    'XData',[-stoneSize(holdOnType,1),stoneSize(holdOnType,1)]+clawPos(1)+norm(stoneSize(holdOnType,:))*sint,...
                    'YData',[-stoneSize(holdOnType,2),stoneSize(holdOnType,2)]+clawPos(2)+norm(stoneSize(holdOnType,:))*cost,...
                    'CData',stonePic{holdOnType},'AlphaData',stoneAlp{holdOnType});
            end  
            
            if clawPos(2)<=ropePos(2)
                clawPos=ropePos;
                grabbing=false;
                if holdOnType>0
                    money=money+stonePrice(holdOnType);
                    set(moneyStrHdl,'String',['$',num2str(money)])
                end
                holdOnType=0;
                set(drawHoldOnHdl,'XData',[0,1],...
                                  'YData',[0,1],...
                                  'CData',ones(1,1),...
                                  'AlphaData',zeros(1,1));                  
            end
            if holdOnType~=0
                set(drawHoldOnHdl,...
                    'XData',[-stoneSize(holdOnType,1),stoneSize(holdOnType,1)]+clawPos(1)+norm(stoneSize(holdOnType,:))*sint,...
                    'YData',[-stoneSize(holdOnType,2),stoneSize(holdOnType,2)]+clawPos(2)+norm(stoneSize(holdOnType,:))*cost);
            end
        end
        
        
        set(drawClawHdl,'XData',rotateX+clawPos(1),'YData',rotateY+clawPos(2));
        set(drawLineHdl,'XData',[clawPos(1),ropePos(1)],'YData',[clawPos(2),ropePos(2)]);
    end

    function n=touchThing(clawPos)
        n=0;
        if clawPos(1)<20||clawPos(1)>730||clawPos(2)>480
            n=-1;     
        end
        flagX=clawPos(1)>=stoneXrange(:,1)&clawPos(1)<=stoneXrange(:,2);
        flagY=clawPos(2)>=stoneYrange(:,1)&clawPos(2)<=stoneYrange(:,2);
        flagXY=flagX&flagY;
        if any(flagXY)
            n=find(flagXY);
        end
    end

    function key(~,event)
        switch event.Key
            case 'downarrow'
                grabbing=true;v=4;
        end
    end
end

以上就是教你用Matlab制作黄金矿工小游戏的详细内容,更多关于Matlab黄金矿工游戏的资料请关注脚本之家其它相关文章!

相关文章

  • 实例分享cmake编译一个简单c++项目(demo)

    实例分享cmake编译一个简单c++项目(demo)

    下面通过一个小例子来说明cmake编译一个c++项目,生成可执行文件,需要的朋友可以参考下
    2020-02-02
  • 求斐波那契(Fibonacci)数列通项的七种实现方法

    求斐波那契(Fibonacci)数列通项的七种实现方法

    本篇文章是对求斐波那契(Fibonacci)数列通项的七种实现方法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • 深入理解C语言的new[]和delete[]

    深入理解C语言的new[]和delete[]

    new和delete既是C++中的关键字也是一种特殊的运算符。这篇文章主要介绍了C++的new和delete详解,需要的朋友可以参考下
    2021-09-09
  • VC中CWinThread类以及和createthread API的区别分析

    VC中CWinThread类以及和createthread API的区别分析

    这篇文章主要介绍了VC中CWinThread类以及和createthread API的区别分析,较为详细的讲述了CWinThread类的原理,并以实例形式对AfxBeginThread函数的内部实现进行了解释说明,需要的朋友可以参考下
    2014-10-10
  • C++ opencv图像平滑滤波器使用示例

    C++ opencv图像平滑滤波器使用示例

    这篇文章主要为大家介绍了C++ opencv数字图像处理图像平滑滤波器的使用示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • UE4 Unlua 调用异步蓝图节点AIMoveTo函数示例详解

    UE4 Unlua 调用异步蓝图节点AIMoveTo函数示例详解

    这篇文章主要为大家介绍了UE4 Unlua 调用AIMoveTo函数示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • C++ pair的用法实例详解

    C++ pair的用法实例详解

    这篇文章主要介绍了C++ pair的用法实例详解的相关资料,需要的朋友可以参考下
    2017-07-07
  • C语言课程设计之抽奖系统

    C语言课程设计之抽奖系统

    这篇文章主要为大家详细介绍了C语言课程设计之抽奖系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-12-12
  • C语言详细讲解qsort函数的使用

    C语言详细讲解qsort函数的使用

    排序方法有很多种:选择排序,冒泡排序,归并排序,快速排序等。看名字都知道快速排序是目前公认的一种比较好的排序算法。因为他速度很快,所以系统也在库里实现这个算法,便于我们的使用。这就是qsort函数
    2022-04-04
  • C语言实现页面置换算法(FIFO、LRU)

    C语言实现页面置换算法(FIFO、LRU)

    这篇文章主要介绍了通过C语言实现的两种页面置换算法:先进先出(FIFO)页面置换算法和最近最久未使用(LRU)页面置换算法。文中的代码具有一定的学习或工作价值,快来跟随小编学习一下吧
    2021-12-12

最新评论