गेम स्कोर
लाल वर्ग को स्थानांतरित करने के लिए बटन दबाएं:
स्कोर की गणना करें
एक गेम में स्कोर को बनाए रखने के कई तरीके हैं, हम आपको दिखाएंगे कि कैनवास पर स्कोर कैसे लिखा जाता है।
पहले स्कोर घटक बनाएं:
उदाहरण
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 160);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
कैनवास तत्व पर टेक्स्ट लिखने का सिंटैक्स एक आयत बनाने से अलग है। इसलिए हमें कंस्ट्रक्टर को एक अतिरिक्त तर्क का उपयोग करके कंपोनेंट कंस्ट्रक्टर को कॉल करना चाहिए, कंस्ट्रक्टर को यह बताना चाहिए कि यह कंपोनेंट "टेक्स्ट" प्रकार का है।
घटक निर्माता में हम परीक्षण करते हैं कि घटक "पाठ" प्रकार का है, और
fillText
विधि के बजाय विधि का उपयोग करें fillRect
:
उदाहरण
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
...
}
अंत में हम updateGameArea फ़ंक्शन में कुछ कोड जोड़ते हैं जो कैनवास पर स्कोर लिखता है। हम frameNo
स्कोर की गणना करने के लिए संपत्ति का उपयोग करते हैं:
उदाहरण
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
myGameArea.stop();
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].speedX = -1;
myObstacles[i].newPos();
myObstacles[i].update();
}
myScore.text = "SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}