Processing顺序点击Tile游戏故障修复:未完成点击即重置问题
问题修复方案
你的代码核心问题是点击判断逻辑错误:你把网格的位置索引(0-3)直接和目标编号(1-4)做比较,导致只要点击的位置不是目标编号对应的数字(比如第一次要点击1,但你点了位置0,而位置0的Tile可能不是1),就会触发失败重置。
具体修复点:
在mouseClicked()函数里,将判断条件从:
if (clickedIndex == order[currentIndex])
改为:
if (shuffledOrder[clickedIndex] == order[currentIndex])
另外,游戏胜利后gameWon设为true会导致后续点击无响应,需要在胜利后将其重置为false,让游戏可以继续进行。
修复后的完整代码:
PImage[] images = new PImage[4]; int[] order = {1, 2, 3, 4}; int[] shuffledOrder; int currentIndex = 0; boolean gameWon = false; void setup() { size(400, 400); images[0] = loadImage("1.jpg"); images[1] = loadImage("2.jpg"); images[2] = loadImage("3.jpg"); images[3] = loadImage("4.jpg"); shuffleImages(); } void draw() { background(255); int imageSize = width / 2; // Display shuffled images in a 2x2 grid int index = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { image(images[shuffledOrder[index] - 1], j * imageSize, i * imageSize, imageSize, imageSize); index++; } } } void mouseClicked() { int imageSize = width / 2; int clickedIndex = mouseY / imageSize * 2 + mouseX / imageSize; if (!gameWon) { // 修正:判断点击位置的Tile编号是否等于当前目标编号 if (shuffledOrder[clickedIndex] == order[currentIndex]) { currentIndex++; if (currentIndex == 4) { println("You won!"); currentIndex = 0; shuffleImages(); // 重置胜利状态,允许下一轮游戏 gameWon = false; } } else { println("Try again"); currentIndex = 0; shuffleImages(); } } } void shuffleImages() { shuffledOrder = shuffleArray(order); } int[] shuffleArray(int[] array) { int[] newArray = array.clone(); for (int i = newArray.length - 1; i > 0; i--) { int index = (int) random(i + 1); int temp = newArray[index]; newArray[index] = newArray[i]; newArray[i] = temp; } return newArray; }
修复说明:
clickedIndex是你点击的网格位置(0到3,对应2x2网格的四个格子),shuffledOrder[clickedIndex]才是该位置上Tile的实际编号(1-4),和目标序列order[currentIndex]对比才是正确的判断逻辑。- 胜利后重置
gameWon为false,确保玩家可以继续进行下一轮游戏。
内容的提问来源于stack exchange,提问作者broke2broke
相关产品推荐
相关产品推荐

