我正在尝试为学校制作一个简单的游戏,基本上是一个简单的目标教练。它所要做的就是绘制圆点,单击它们将其杀死,然后添加到您的分数中,然后单击背景而不是圆点结束游戏。现在我有结束游戏的问题,每当我单击圆点时,它就会运行gameend()函数中的代码,只有在单击圆点时才应执行此操作。有什么方法可以确保gameend()函数既保持不变,又仅在单击背景时激活
我尝试使用mouseClicked函数,但是它破坏了我的代码
let x;
let y;
let circle;
let dots = [];
let score = 0;
function setup() {
createCanvas(1080, 800);
xycircle();
}
function draw() {
background(100, 100, 255);
click();
scorer();
for (let dot of dots) {
ellipse(dot.x, dot.y, dot.circle, dot.circle)
}
};
function xycircle() {
for (i = 0; i < 25; i += 1) {
dots.push({
x: random(1080),
y: random(100, 800),
circle: random(25, 50)
})
};
};
function click() {
for (let dot of dots) {
if (dist(dot.x, dot.y, mouseX, mouseY) < dot.circle / 2 &&
mouseIsPressed) {
dots = dots.filter(dot1 => dot1 !== dot)
score++
if (dots.length === 0) {
xycircle();
}
} else if (dist(dot.x, dot.y, mouseX, mouseY) != dot.circle / 2 &&
mouseIsPressed) {
}
};
};
function scorer() {
fill(20, 75, 200);
rect(0, 0, 1080, 75);
fill(0, 0, 0);
text(score, 950, 50)
fill(255, 255, 255);
}
function gameend() {
background(255, 0, 0);
fill(0, 0, 0);
text("GAME OVER", 540, 400);
text("Your score was " + score, 540, 420);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
答案 0 :(得分:0)
创建变量gameover
,该变量会在单击背景时显示:
let gameover = false;
创建一个mousePressed()
事件,而不是调用连续检查是否按下鼠标的函数(click
)。当单击错过点时,该事件将声明变量gameover
:
function mousePressed() {
var hit = false;
for (let dot of dots) {
if (dist(dot.x, dot.y, mouseX, mouseY) < dot.circle / 2 ) {
dots = dots.filter(dot1 => dot1 !== dot)
hit = true;
if (dots.length === 0) {
xycircle();
}
}
};
if ( hit )
score++
else
gameover = true;
}
在draw
函数中,您可以根据变量gameover
的状态绘制点数或“游戏结束”画面:
function draw() {
if ( gameover ) {
gameend();
} else {
background(100, 100, 255);
scorer();
for (let dot of dots) {
ellipse(dot.x, dot.y, dot.circle, dot.circle)
}
}
};
请参见示例,其中我将更改应用于您的原始代码:
let x;
let y;
let circle;
let dots = [];
let score = 0;
let gameover = false;
function setup() {
createCanvas(1080, 800);
xycircle();
}
function draw() {
if ( gameover ) {
gameend();
} else {
background(100, 100, 255);
scorer();
for (let dot of dots) {
ellipse(dot.x, dot.y, dot.circle, dot.circle)
}
}
};
function xycircle() {
for (i = 0; i < 25; i += 1) {
dots.push({
x: random(1080),
y: random(100, 800),
circle: random(25, 50)
})
};
};
function mousePressed() {
var hit = false;
for (let dot of dots) {
if (dist(dot.x, dot.y, mouseX, mouseY) < dot.circle / 2 ) {
dots = dots.filter(dot1 => dot1 !== dot)
hit = true;
if (dots.length === 0) {
xycircle();
}
}
};
if ( hit )
score++
else
gameover = true;
}
function scorer() {
fill(20, 75, 200);
rect(0, 0, 1080, 75);
fill(0, 0, 0);
text(score, 950, 50)
fill(255, 255, 255);
}
function gameend() {
background(255, 0, 0);
fill(0, 0, 0);
text("GAME OVER", 540, 400);
text("Your score was " + score, 540, 420);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>