javascript - 如何让 Phaser 3 输出最终分数
问题描述
我正在创建我的第一个 Phaser 3 游戏,我需要输出最终分数以供另一个 .js 文件使用,该文件将输出到 mysql 数据库。我还需要能够将当前高分从所述数据库导入移相器游戏。
final score is stores and var finalScore database table name is highScores with the columns id, userName, score, date (date is so we can sort high scores by all time high scores,monthly high scores and daily high scores)
但我只需要帮助将 finalScore 从移相器中取出并将 currentHighScore 放入移相器
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Making your first Phaser 3 Game - Part 10</title>
<script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var player;
var stars;
var bombs;
var platforms;
var cursors;
var score = 0;
var gameOver = false;
var scoreText;
// var userName;
var game = new Phaser.Game(config);
function preload() {
this.load.image('sky', 'assets/sky.png');
this.load.image('ground', 'assets/platform.png');
this.load.image('star', 'assets/star.png');
this.load.image('bomb', 'assets/bomb.png');
this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
}
function create() {
// A simple background for our game
this.add.image(400, 300, 'sky');
// The platforms group contains the ground and the 2 ledges we can jump on
platforms = this.physics.add.staticGroup();
// Here we create the ground.
// Scale it to fit the width of the game (the original sprite is 400x32 in size)
platforms.create(400, 568, 'ground').setScale(2).refreshBody();
// Now let's create some ledges
platforms.create(600, 400, 'ground');
platforms.create(50, 250, 'ground');
platforms.create(750, 220, 'ground');
// The player and its settings
player = this.physics.add.sprite(100, 450, 'dude');
// Player physics properties. Give the little guy a slight bounce.
player.setBounce(0.2);
player.setCollideWorldBounds(true);
// Our player animations, turning, walking left and walking right.
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [{ key: 'dude', frame: 4 }],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
// Input Events
cursors = this.input.keyboard.createCursorKeys();
// Some stars to collect, 12 in total, evenly spaced 70 pixels apart along the x axis
stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 70 }
});
stars.children.iterate(function (child) {
// Give each star a slightly different bounce
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
bombs = this.physics.add.group();
// The score
scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
// Collide the player and the stars with the platforms
this.physics.add.collider(player, platforms);
this.physics.add.collider(stars, platforms);
this.physics.add.collider(bombs, platforms);
// Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
this.physics.add.overlap(player, stars, collectStar, null, this);
this.physics.add.collider(player, bombs, hitBomb, null, this);
}
function update() {
if (gameOver) {
var timeStamp = Math.floor(Date.now()) / 1000;
// gets the userName from the player
var userName = prompt("Please enter your name", "name");
//localStorage.setItem("playerName", userName);
// Save score to final score, score will be reset to zero when game restarts
finalScore = score;
console.log("User: " + userName + "'s score is " + finalScore + " at " + timeStamp + ".");
// Reset gameOver to prevent update() loop and prepare game to restart
gameOver = false;
window.confirm("Would you like to play again?");
// add call to start function again
// if (confirm("Press a button!")) {
// this.game.state.restart()
// } else {
return;
// }
}
if (cursors.left.isDown) {
player.setVelocityX(-160);
player.anims.play('left', true);
}
else if (cursors.right.isDown) {
player.setVelocityX(160);
player.anims.play('right', true);
}
else {
player.setVelocityX(0);
player.anims.play('turn');
}
if (cursors.up.isDown && player.body.touching.down) {
player.setVelocityY(-330);
}
}
function collectStar(player, star) {
star.disableBody(true, true);
// Add and update the score
score += 10;
scoreText.setText('Score: ' + score);
if (stars.countActive(true) === 0) {
// A new batch of stars to collect
stars.children.iterate(function (child) {
child.enableBody(true, child.x, 0, true, true);
});
var x = (player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
var bomb = bombs.create(x, 16, 'bomb');
bomb.setBounce(1);
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
bomb.allowGravity = false;
}
}
function hitBomb(player, bomb) {
this.physics.pause();
player.setTint(0xff0000);
player.anims.play('turn');
gameOver = true;
}
// Function to post data to database
// need to get api input format from Zack
module.exports = {
userName: userName,
score: finalScore,
last_date: timeStamp
};
</script>
</body>
</html>
解决方案
使用 Ajax 将高分发送到特定页面,然后您可以在 PHP 中使用 $_POST 将其放入数据库中。您可以使用 PHP 来保存日期、时间、分数、用户名等。确保游戏名称是唯一的,并使用 PHP 来引用您为游戏分数创建的数据库表中的索引。
这是我帮助开发的游戏的示例保存功能(用于 IBP Arcade 或 SMF Arcade):
function submitScore(score)
{
let pathArray = window.location.pathname.split('/'), newpath = '', currentPath = '';
for (i = 0; i < pathArray.length; i++) {
currentPath = pathArray[i].toString().toLowerCase();
if (currentPath == 'arcade' || currentPath == 'games')
break;
newpath += '/' + pathArray[i];
}
scorepost(window.location.protocol + '//' + window.location.hostname.replace(/[/]+$/, '') + '/' + newpath.replace(/^[/]+/, '') + '/index.php?act=Arcade&do=newscore', {
gname : 'html5_game_name',
gscore: score
});
}
您可能需要稍微修改它确定 URL 的方式。上述功能是为 2 个不同的 Arcade 设计的,旨在为包含在父路径或子路径中的网站工作。使用控制台日志在您拥有它的地方调用该函数。
要从数据库中获取高分以便在游戏中访问,您可以使用 PHP 创建一个包含基本搜索数据的 API 页面。使用 javascript 以游戏名称作为参考调用页面,然后使用 DOM 收集数据。API 页面上的 HTML 可以包含在父 pre 标记中。您可以使用 DOM 访问具有日期、分数、用户名等数据的子级。
推荐阅读
- mysql - 在 MySQL 中加入多个表
- python - 使用 python 查找维基百科页面标题的完全匹配
- amazon-web-services - 复合弹性搜索仅在两个来源都存在的情况下
- solr - 在 SOLR 中,我如何提及不应更改起始字符?
- javascript - Docker 抛出 SyntaxError: Unexpected token ':'
- android - 更新后TextView字符串消失
- html - 如何设置图像大小以适应 CSS 和 HTML 并使其看起来相同
- c++ - 释放从函数返回的动态数组
- types - SML 数据类型转换:绑定并不详尽
- haskell - 编写两个 Traversal,对中间层具有只读权限