JavaScript Chessboard程序

时间:2014-08-07 17:08:02

标签: javascript

这是我的任务:编写一个程序,创建一个代表8×8网格的字符串,使用换行符分隔行。在网格的每个位置都有一个空格或#字符。角色应该成为棋盘。

将此字符串传递给console.log应该显示如下内容:

    # # # #
     # # # #
    # # # #
     # # # #
    # # # #
     # # # #
    # # # #
     # # # #

我的尝试低于评论以解释我的逻辑。我接近但我永远无法得到上面的模式。我的逻辑怎么了?

//declar empty board
var board = "";

//use outter loop to control rows
for (var y = 1; y < 5; y++) {
    //use innerloop to generate the #'s horizonatlly
    for(var x = 1; x < 5; x++) {
        //if the row is even then put a space in front
        //of the board string and then generate the board
        // with the #'s
        if (y % 2 === 0) {
            board = " " + board;
            board += "#";
        }
        //else generate the board without a space in front
        //of the #'s
        else {
            board += "#";
        }
    }
    //generate a new line 
    board += "\n";
}

console.log(board);

11 个答案:

答案 0 :(得分:3)

我决定玩得开心并编写自己的解决方案:

var board = "";
var evenRow = "# # # # ";
var oddRow = " # # # #";

for ( var i = 0; i < 8; i++ ) {

    if ( i%2 == 0 ) board += evenRow + '\n';
    else board += oddRow + '\n';
}

console.log(board);

注意:国际象棋棋盘的正确方向是右下方的白色方块,这是答案的建议输出的90度旋转。

答案 1 :(得分:0)

上面的解决方案很适合用于循环。让循环播放很有趣。

&#13;
&#13;
var board = "";
var even = " # # # #";
var odd = "# # # #";
var i = 1;
while (i <= 8) {
  if (i % 2 == 0) {
    console.log(even);
  } else {
    console.log(odd);
  }
  var i = i + 1;
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

解决方案:

Pull request creation failed. Validation failed: A pull request already exists for...

答案 3 :(得分:0)

这是我的解决方案,可以产生所需的准确输出

// declare size and an empty "board" string
var size = 8;
var board = "";

// Outerloop for rows
for (let i = 1; i <= size; i++) {
  // inner loop for columns
  for (let j = 1; j <= size; j++) {
    if ((i + j) % 2 == 0) { // check if col is even
      board += " ";
    } else { // if col is odd
      board += "#";
    }
  }
  board += "\n"; // jump to next row
}
console.log(board);

答案 4 :(得分:0)

let size = 8;

let board = "";

for (let y = 0; y < size; y++) {

  for (let x = 0; x < size; x++) {

    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }
  }
  board += "\n";
}

console.log(board);

答案 5 :(得分:0)

我想出了这个实现,我根据所需的网格大小使用循环创建所需的字符串行,最后使用另一个循环将它们与新行连接以输出最终结果。

//I Came Up With This

const gridSize = 8 ;  //your grid size

var str1 = "" ;  //first line of string  eg. # # # #
var str2 = "" ;  //second line of string eg.# # # #
var str = "" ;   //final string

//making str1 and str2 according to gridSize
for(var i = 0 ; i < gridSize ; i++){
    if(i%2==0){
        str1 += " " ;
        str2 += "#" ;
    }

    else{
        str1 += "#" ;
        str2 += " " ;
    }
}

//concatenating str1 and str2 with new line to final output str.
for(var i = 0 ; i < gridSize ; i++){
    if(i%2==0){
        str += str1+"\n" ;
    }

    else{
        str += str2+"\n" ;
    }
}
//printing final output.
console.log(str);

答案 6 :(得分:-1)

这是我的解决方案:

&#13;
&#13;
var size = 8;
var block = '#';
var space = ' ';

for (var i = 1; i <= size; i++) {
  var line = '';

  for (var y = 1; y <= size; y++) {
    if (i % 2) {
      if (y % 2) {
        line = line + space;
      } else {
        line = line + block;
      }
    } else {
      if (y % 2) {
        line = line + block;
      } else {
        line = line + space;
      }
    }
  }
  console.log(line);
}
&#13;
&#13;
&#13;

答案 7 :(得分:-1)

var x = "";
var y = "";
for (var i = 0; i <= 4; i++) {
  x = "#" + " " + "#" + " " + "#" + " " + "#";
  y = " " + "#" + " " + "#" + " " + "#" + " " + "#";
  console.log(x);
  console.log(y);
}

答案 8 :(得分:-1)

这是我的解决方案......

var datepickerCalendarDirective = function datepickerCalendarDirective() {
        return {
            scope: {
                searchResponse: '='
            },
            restrict: 'E',
            templateUrl: './templates/directive.datepickerCalendar.tmpl.html',
            link: function link(scope, element, attrs, $filter, policySessionService) {

                scope.$watch('searchResponse', function () {

                    scope.dt = new Date();

                    if (!scope.searchResponse) return '';

                    /* setup the date picker options object.
                     * this takes a customClass function which sets the 
                     * css class of the trips/events on the datepicker
                     */
                    scope.options = {
                        customClass: getSelectedDates,
                        maxDate: new Date(),
                        showWeeks: false,
                        startingDay: 1 };
                }, true);

                /* Iterate over each trip in the reponse and return either
                * a trip or incident css class to the customClass param
                * of the datepicker options object
                */
                function getSelectedDates(data) {
                    if (scope.searchResponse.data[0] && data.mode === 'day') {
                        var trips = $filter('orderBy')(scope.searchResponse.data[0].tripDates, 'JourneyDate'),
                            journeyDate;

                        for (var i = 0; i < trips.length; i++) {
                            journeyDate = new Date(trips[i].JourneyDate).setHours(0, 0, 0, 0);

                            if (journeyDate === new Date(data.date).setHours(0, 0, 0, 0)) {
                                // return the appropriate css class for the trip type (trip or incident)
                                if (trips[i].IncidentRecorded) {
                                    return 'incident';
                                } else {
                                    return 'trip';
                                }
                            }
                        }
                    }
                    return '';
                }

                // });
            }
        };
    };

答案 9 :(得分:-2)

这个实现如何简单直接

function chessBoard(size) {
  for(var i = 0; i < size; i++) {
      if (i % 2 === 0) {
         console.log('' + '# # # #');
       } else {
         console.log(' ' + '# # # #');
       }
    }
 }

chessBoard(8);

答案 10 :(得分:-3)

这很简单...... 2个循环...第一个循环计算列数,第二个循环每列重复“#”4次。与“#”的距离是字符“#”之间的距离。当列数为奇数时,距离将在“#”之前。变量“chr”是将这些重复内容保存到每一列中。

<select class="form-control input-sm" ng-model="selectedDay" ng-options="day.id as day.name for day in daysOfWeek" ng-change="triggerDate(dt)"></select>