2016 - 2024

感恩一路有你

制作翻板小游戏代码详解

浏览量:4715 时间:2024-03-23 20:24:51 作者:采采

上一篇文章介绍了制作翻板小游戏的准备工作,这一篇将重点讲解代码部分。在这个阶段,我们将深入了解随机值获取、计时器的使用和鼠标点击事件等主要知识点。

初始化参数及定义计时器

首先,在主时间轴中加入以下代码段:

```actionscript

var numAry:Array new Array(); // 数组,用于存放数字

var count:int 18; // 板数量

var first_id:int -1; // 第一个点击的板编号

var second_id:int -1; // 第二个点击的板编号

var timer:Timer new Timer(100, 1); // 计时器,用于复原翻过的板

var over_count:int 0; // 已经完成的数量

(TimerEvent.TIMER_COMPLETE, CheckSame);

```

这部分代码主要是用于初始化参数并定义计时器。

初始化元件及显示数字

接着采取一系列操作来初始化元件,并显示数字,同时为重新开始游戏添加鼠标事件:

```actionscript

function initSence():void {

btn_ false;

btn_(, ReplayGame);

for (var i:int 0; i < count; i ) {

numAry.push(int(i/2));

this["m" i].mc_id i;

this["m" i].visible true;

this["m" i].isClick false;

this["m" i].addEventListener(, ChangeState);

}

numAry Random(numAry);

for (i 0; i < count; i ) {

this["m" i].txt.text numAry[i].toString();

this["m" i] false;

}

}

```

编写鼠标点击板的代码

下一步是编写鼠标点击板的代码,用于处理点击事件和板的状态变化:

```actionscript

function ChangeState(e:MouseEvent):void {

var obj:MovieClip as MovieClip;

var t:int _id;

if ( true) {

return;

}

true;

if (first_id -1 second_id -1) {

first_id t;

true;

return;

}

if (first_id ! -1 second_id -1) {

second_id t;

true;

();

}

}

```

编写计时器事件

针对计时器事件的编写如下,用于检查是否匹配成功:

```actionscript

function CheckSame(e:TimerEvent):void {

if (numAry[first_id] numAry[second_id]) {

this["m" first_id].visible false;

this["m" second_id].visible false;

over_count 2;

if (over_count count) {

btn_ true;

}

} else {

this["m" first_id] false;

this["m" second_id] false;

}

this["m" first_id].isClick false;

this["m" second_id].isClick false;

first_id -1;

second_id -1;

}

```

获取随机数组的方法

最后,实现获取随机数组的方法,确保每局游戏的元素位置不同:

```actionscript

function Random(ary:Array):Array {

var tempAry:Array new Array();

while (ary.length > 0) {

var temp:int int(Math.random() * 10000) % ary.length;

tempAry.push(ary[temp]);

ary.splice(temp, 1);

}

return tempAry;

}

```

一旦全部代码编写完成,运行程序即可开始游戏。你还可以通过增加按钮和游戏计时等功能来完善这款小游戏。让玩家在娱乐的同时也能锻炼记忆力和专注力。

版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。