0

我的 jQuery 作业有严重问题(我是学生和 JS 初学者)。

基本上任务是使用 MV(C)(我们不使用控制器)模式使用 jQuery 创建一个连接四人游戏。

比赛场地是一个二维数组,看起来像这样。

- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 

并且玩家通过按列进行游戏(例如,玩家 1 按 3)

- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , x , - , - , - , - 

玩家 2 按 4

- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , - , - , - , - , - 
- , - , x , o , - , - , - 

等等。

游戏结束时,获胜的四个字母应变为大写。

我被困住了,真的不知道如何继续,所以我创建了一个包含所有代码的 GitHub 存储库。

https://github.com/VeronicaLeeds/connectfour

基本上它会初始化比赛场地,您可以按数字,但 play() 方法将不起作用。

我不知道从 View 调用该函数的任何其他方式。

我试过 View().play , View.play() , play() ...但我总是出错。

if (evt.which == 49) {
   View().play(1);
   return 1;
   console.log('1');
}

play() 函数位于 View.js 文件中。

将永远感激任何帮助。

4

1 回答 1

0

请注意,您应该努力将文件重命名为重要的东西。当某些文件的名称模糊不清时,很难找到相关代码js.js

除此之外,您的函数checkIfWon(arr)injs.js使用 method checkForFour(),该方法接受一个数组作为参数,并根据是否检测到来自同一玩家的 4 个棋子返回 true 或 false。

由于在同一个数组上迭代两次是多余的,因此checkIfWon(arr)如果未检测到 connect-4,则可以返回一个空数组,如果检测到 connect-4,则返回列(大写的连胜记录)。

例如:

// Horizontal
var tempArrayHorizontal = new Array(7);
for (var row = 0; row <= 5; row++) {
    for (var col = 0; col <= 6; col++) { 
        tempArrayHorizontal[col] = playFieldArray[col][row];
    }
    var result = checkForFour(tempArrayHorizontal);
    if (result !== []) {
        for (var col = 0; col <= 6; col++) { // we re-iterate the same way we did when you populated tempArrayHorizontal
            playFieldArray[col][row] = result[col];
        }
        return true;
    }
}

和你的checkForFour功能:

function checkForFour(input) {
    var count = 0;
    for (var i = 0; i < input.length; i++) {
        if (input[i] === currentPlayer) {
            count++;
            if (count === 4) {
                // replace the 4 previous column to uppercase
                input.splice(i-4, 4, currentPlayer.toUpperCase(), currentPlayer.toUpperCase(), currentPlayer.toUpperCase(), currentPlayer.toUpperCase());
                return input;
            }
        } else {
            count = 0;
        }
    }
    return [];
}

我还没有测试过,所以你必须最终确认。

祝你好运!

于 2018-04-30T11:48:32.523 回答