用App Designer 制作2048小游戏
用App Designer制作的2048,MATLAB版本是2020b。记录下创作思路,以免日后忘记。
APP界面设计
APP界面如下,为了好玩,还加入了游戏进行时播放音乐的功能。
下面是游戏结束界面:

除了按钮和开关部分,其余都可用标签控件制作。游戏结束界面在制作时将其Visible属性设为Off(确保在主界面上层),当判定游戏结束时再将Visible属性修改为On即可。
app.gameOverLabel.Visible = 'on'; app.gameOverLabel2.Visible = 'on'; app.gameOverLabel3.Visible = 'on';

规则设计
temp = ~app.theMatrix(4-i,:).*app.theMatrix(5-i,:); app.theMatrix(4-i,:) = app.theMatrix(4-i,:) + temp; app.theMatrix(5-i,:) = app.theMatrix(5-i,:) - temp;
zeroIndex = find(app.theMatrix == 0);
后端到前端
要把矩阵映射到游戏主界面,有两个需求:一是对应位置的数字显示,其中“0”不显示;二是不同数字对应着不同的背景颜色。这个只需要对每个方格的Text属性和BackGroundColor属性依次赋值就行,注意Text属性应当用字符串类型赋值,为此可以使用string()函数将数值矩阵转换为字符串矩阵。
strMatrix = string(app.theMatrix);
特别地,零元素应当转换成空字符串。
strZeroIndex = strMatrix == "0"; strMatrix(strZeroIndex) = "";
每进行一步操作都要将主界面更新一遍,在此更新中分数界面应当一并更新。
按钮回调
按前面所说的方式分别设计向上键、向下键、向左键和向右键的回调函数,包含两部分:一是对矩阵进行修改,二是将修改后的矩阵映射到主界面。点击按钮的任务用键盘也能完成,我们可以添加键盘回调,并在其中关联按钮回调。使用WindowKeyRelease将会按键释放时执行回调。
function UIFigureWindowKeyRelease(app, event) key = event.Key; switch(key) case {"uparrow","w"} app.buttonUpButtonPushed(); case {"downarrow","s"} app.buttonDownButtonPushed(); case {"leftarrow","a"} app.buttonLeftButtonPushed(); case {"rightarrow","d"} app.buttonRightButtonPushed(); end end
f = fopen(app.dataPath,'r'); if f>0 app.bestScore = fread(f,'int32'); fclose(f); end
运行方式
function startupFcn(app) app.loadMusic(); app.scoreStart(); app.nextStep(); app.nextStep(); end
首先,用loadMusic()函数加载音乐,之后我们可以用开关来控制音乐的暂停和播放。接下来用scoreStart()将得分清零,并从文件中读取最高分。然后使用nextStep()刷新界面,因为游戏初始有两个“2”,而nextStep()只能产生一个,所以使用两次。
关于批量创建控件
Num matlab.ui.control.Label
其中,Num是控件名,后面的 matlab.ui.control.Label 表明了Num是Label控件。之后,我们写一个创建控件的函数。
function createNum(app) for i=1:4 for j=1:4 app.Num(i,j) = uilabel(app.UIFigure); app.Num(i,j).BackgroundColor = [0.902 0.902 0.8]; app.Num(i,j).HorizontalAlignment = 'center'; app.Num(i,j).FontName = 'Calibri'; app.Num(i,j).FontSize = 40; app.Num(i,j).Position = [-60+100*j 440-100*i 90 90]; app.Num(i,j).Text = ''; end end end
注意需要在properties中声明Num的类型才能对控件的属性进行点索引。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/232150.html原文链接:https://javaforall.net
