Example 2. Random

Instead of changing frames in order (as in Example 1), in response to click, now there are randomly changed. They will be changed to a random value, which does not happen to be the current value.


This is the html file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex02</title>
  <link rel="stylesheet" type="text/css" href="css/ex02.css">
  <script type="text/javascript" src="js/phaser.min.js"></script>
</head>
<body>
  <div align="center" id="ex02"></div>
  <div align="center" id="frame"></div>
  <script type="text/javascript" src="js/ex02.js"></script>
</body>
</html>

The css file is identical to that in example 1.


This is the javascript file:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Ex02. Random

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex02',
               { preload: preload, create: create});
var colorBox;

function preload() {
    game.load.spritesheet('fourColors', 'images/ex02.png', 16, 16, 4);
}

function create() {
    game.stage.backgroundColor = "#00FFFF";
    colorBox = game.add.sprite(game.world.centerX, game.world.centerY, 'fourColors');
    colorBox.scale.setTo(10,10);
    colorBox.anchor.setTo(0.5, 0.5);
    colorBox.inputEnabled = true;
    colorBox.events.onInputDown.add(changeColor, this);
    displayFrame(colorBox.frame);
}

function changeColor() {
    var oldFrame = colorBox.frame;
    var newFrame = game.rnd.integerInRange(0, 3);
    while (newFrame == oldFrame) {
        newFrame = game.rnd.integerInRange(0, 3);
    }
    colorBox.frame = newFrame;
    displayFrame(colorBox.frame)
}

function displayFrame(frame) {
    document.getElementById("frame").innerHTML = "frame = " + frame;
}

Now we use rnd.integerInRange(0,3) function to get a random value from 0 to 3.


The while loop will ensure that we do not select same value.

No comments:

Post a Comment