360 : Adding coins
Balthazar:
Adding coins that the player can gather.
Balthazar:
We'll need a coin image to display.
Copy the following files into your project:
Balthazar:
The player should start out with 0 coind.
function init_player() {
...
_player.platform = null;
_player.health_max = 50;
_player.health = _player.health_max;
_player.coins = 0;
_player.dir = 1;
...
}
Balthazar:
And we can scatter some coins around level 1.
function init_level1() {
...
// Create the items.
var item_data = [
// [x, y, width, height, type, image]
[530, 358, 18, 20, "key", "key"],
[465, 270, 16, 23, "potion", "potion"],
[50, 250, 20, 20, "coin", "coin"],
[530, 190, 20, 20, "coin", "coin"],
[230, 120, 20, 20, "coin", "coin"],
];
add_items(level, item_data);
...
}
Balthazar:
When the player collides with a coin, we need to increment the current coin count.
function check_item_collisions() {
var level = _levels[_game.current_level];
var items = level.items;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.found) {
if (collide(item, _player)) {
if (item.type == "key") {
level.player_has_key = true;
} else if (item.type == "potion") {
adjust_health(30);
} else if (item.type == "coin") {
_player.coins++;
} else if (item.type == "finish") {
_game.game_over = true;
_game.game_win = true;
}
item.found = true;
}
}
}
}
Balthazar:
And we need to update the status bar at the top of the screen.
function init_game() {
...
// Status images
_game.img_key = new Image();
_game.img_key.src = _game.imagedir_items + "key.png";
_game.img_coin = new Image();
_game.img_coin.src = _game.imagedir_items + "coin.png";
_game.img_player = new Image();
_game.img_player.src = _game.imagedir_player + "icon.png";
}
Balthazar:
Note that we need to move the player icons over to make room for the coin info.
function draw_status(ctx) {
...
// If the player has the key, draw it in the status area.
var level = _levels[_game.current_level];
if (level.player_has_key) {
ctx.drawImage(_game.img_key, _game.meter_width + 15, 11);
}
ctx.drawImage(_game.img_coin, _game.width - 58, 11);
ctx.fillStyle = "#606060";
ctx.font = "16px Helvetica";
ctx.fillText("x" + _player.coins, _game.width - 37, 26);
// Draw player icons to indicate how many extra lives remain.
for (var i = 0; i < _game.player_lives-1; i++) {
ctx.drawImage(_game.img_player, _game.width - 30 - (i * 20), 12);
ctx.drawImage(_game.img_player, _game.width - 80 - (i * 20), 12);
}
}
Congratulations! You've earned the Treasure IV - Coin badge!
GOTO 370