Conways Game of Life errors in Javascript - javascript

I'm currently coding conways game of life in JavaScript, but have encountered some errors which I do not know how to fix. Was wondering if anyone could help me out on them?
there are currently 4 errors showing on google chrome inspector which are as follows:
Uncaught TypeError: Cannot read property 'length' of undefined - "for(var i =0; i< this.checkneighbours.length; i++){ "
GoL.update # life.js:72 - which is -" for(var i =0; i < this.checkneighbours.length; i++){ "
GoL.updateAll # life.js:88 which is - " this.update(i,j); "
(anonymous function) # life.js:115 which is - "gameoflife.updateAll(); "
I think they might fall under the same category I'm not sure.
Here is my code:
//object constructor
function cell(){
this.alive = Math.random() >0.7;
this.neighbours = 0; //number of live neighbours
this.checkneighbours = [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[1,0],[0,1],[1,1]];
}
function GoL(size){
this.size = size;
this.grid = this.makeGrid(size);
};
GoL.prototype.makeGrid = function(size){
var grid = [];
for(var i=0; i<size; i++){
var row=[];
for(var j =0; j<size; j++){
row.push(new cell());
}
grid.push(row);
}
return grid;
};
GoL.prototype.drawGrid = function(){
console.log("\033[2J");
for(var i=0;i<this.size;i++){
var row =this.grid[i];
var rowCell="";
for(var j=0;j<this.size;j++){
var cell = row[j];
if(cell.alive){
rowCell += "X|";
}else{
rowCell += " |";
}
}
console.log(rowCell);
}
};
GoL.prototype.underpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours <2){
return true;
}else{
return false;
}
};
GoL.prototype.overpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours >3){
return true;
}else{
return false;
}
};
GoL.prototype.backtolife = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours ===3 && !cell.alive){
return true;
}else{
return false;
}
};
GoL.prototype.update = function(ro,col){
var cell = this.grid[ro][col];
cell.num_of_neighbours = 0;
for(var i =0; i<this.checkneighbours.length; i++){
var checkneighbour = this.checkneighbours[i];
var neighbour1 = direction[0];
var neighbour2 = direction[1];
if(neighbour1>=0 && neighbour1 < this.size && neighbour2 >=0 && neighbour2 < this.size){
var currentneighbour = this.grid[ro + neighbour1][col+neighbour2];
if(currentneighbour.alive){
cell.num_of_neighbours++;
}
}
}
};
GoL.prototype.updateAll = function(){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.update(i,j);
}
}
}
GoL.prototype.cellstatus = function(ro,col){
var cell = this.grid[ro][col];
if(this.underpopulation(ro,col) || this.overpopulation(ro,col)){
cell.alive = false;
}else if(this.backtolife(ro,col)){
cell.alive = true;
}
};
GoL.prototype.allcellstatus = function(ro,col){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.cellstatus(i,j);
}
}
};
var gameoflife = new GoL(40);
var interval = setInterval(function(){
gameoflife.drawGrid();
gameoflife.updateAll();
gameoflife.allcellstatus();
},1000);
Any help would be appreciated!

some thoughts
GoL.prototype.update = function (ro, col) {
var cell = this.grid[ro][col];
cell.num_of_neighbours = 0;
for (var i = 0; i < cell.checkneighbours.length; i++) { // change this to cell
var direction = cell.checkneighbours[i]; // change this to cell, rename 'checkneighbour' to 'direction'
var neighbour1 = direction[0];
var neighbour2 = direction[1];
if (neighbour1 >= 0 && neighbour1 < this.size && neighbour2 >= 0 && neighbour2 < this.size) {
var currentneighbour = this.grid[ro + neighbour1][col + neighbour2]; // add here some error checking for out of range!
if (currentneighbour.alive) {
cell.num_of_neighbours++;
}
}
}
};

Related

vue show js 's error :TypeError: "this is undefined"

I want to make a dynamic water pipe with water flowing. The front picture is an error message.
The following picture is a method in the method in the vue page. I don't know if it will report an error. If you don't call this method, nothing will be reported.
The following code is the js file that introduces the vue page
//构造函数
function Createline(config) {
this.c = 0;
this.lines = [];
var self = this;
//初始化线
(function (self){
if(config.fx == "w"){
var number = config.canvas_w / (config.width + config.width/2 + config.jiange*2);
number = Math.ceil(number) + 1;
for(var n = 0 ; n < number ; n++){
var mxx = config.canvas_w - n*(config.width+config.width/2+config.jiange*2);
var lines_data = {
mx:mxx,
lx:mxx - config.width,
my:config.my,
ly:config.ly,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data);
var lines_data2 = {
mx:mxx-config.width-config.jiange,
lx:mxx-config.width-config.jiange-config.width/2,
my:config.my,
ly:config.ly,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data2);
}
}
if(config.fx == "h"){
var number = config.canvas_w / (config.width + config.width/2 + config.jiange*2);
number = Math.ceil(number) + 1;
for(var n = 0 ; n < number ; n++){
var myy = config.canvas_h - n*(config.width+config.width/2+config.jiange*2);
var lines_data3 = {
mx:config.mx,
lx:config.lx,
my:myy,
ly:myy - config.width,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data3);
var lines_data4 = {
mx:config.mx,
lx:config.lx,
my:myy-config.width-config.jiange,
ly:myy-config.width-config.jiange-config.width/2,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data4);
}
}
})(self);
}
//开始
Createline.prototype.begin = function (element,config) {
var canvasObj = document.getElementById(element);
var self = this;
var canvas = {
line_w: config.line_w || 3, //线条厚度
vx: config.vx || 0,//x轴运动速度
vy:config.vy || 0,//Y轴速度
color:config.color || "blue",//线条颜色
canvas_w:config.canvas_w || 0,//画布宽度
canvas_h:config.canvas_h || 0,//画布高度
mx: config.mx || 0,//线的开始位置X坐标
my: config.my || 0,//线的开始位置Y坐标
lx: config.lx || 0,//线的结束位置X坐标
ly: config.ly || 0,//线的结束位置Y坐标
fx:config.fx || "w",//运动方向 w 水平 ,h: 垂直
width:config.width || 20,//线的长度
jiange:config.jiange || 10, //线的间隔
}
if(canvasObj.getContext("2d")){
canvas.ctx = canvasObj.getContext("2d"),
canvasObj.width = canvas.canvas_w;
canvasObj.height = canvas.canvas_h;
}else{
console.log("当前环境不支持canvas");
return null;
}
setInterval(function(){
self.createline(self,canvas);
if(canvas.fx == "w"){
self.updateline_w(self,canvas);
}
if(canvas.fx == "h"){
self.updateline_h(self,canvas);
}
self.addline(self,canvas);
},config.time);
return canvas.ctx;
}
//画线
Createline.prototype.createline = function(self,canvas){
var content = canvas.ctx;
content.clearRect(0,0,canvas.canvas_w,canvas.canvas_h);
for(var i = 0 ; i < self.lines.length ; i++){
content.beginPath();
content.moveTo(self.lines[i].mx,self.lines[i].my);
//线经过的转折点或结束点
content.lineTo(self.lines[i].lx,self.lines[i].ly);
//线条宽度
content.lineWidth = canvas.line_w;
content.strokeStyle = canvas.color;
content.stroke();
//线条颜色
content.closePath();
//画线
}
}
//改变数据 水平运动
Createline.prototype.updateline_w = function(self,canvas){
for (var i = 0 ; i < self.lines.length ; i++) {
self.lines[i].mx = self.lines[i].mx + self.lines[i].vx;
self.lines[i].lx = self.lines[i].lx + self.lines[i].vx;
}
//超出画布的线条从数组内删除,减少系统消耗
var cnt = [];
for (var j = 0 ;j < self.lines.length ; j++) {
if(self.lines[j].lx > canvas.canvas_w){
cnt.push(j);
}
}
for(var k = 0; k < cnt.length ; k++){
self.lines.splice(k,1);
}
}
//改变数据 垂直运动
Createline.prototype.updateline_h = function(self,canvas){
for (var i = 0 ; i < self.lines.length ; i++) {
self.lines[i].my = self.lines[i].my + lines[i].vy;
self.lines[i].ly = self.lines[i].ly + lines[i].vy;
}
//超出画布的线条从数组内删除,减少系统消耗
var cnt = [];
for (var j = 0 ;j < self.lines.length ; j++) {
if( self.lines[j].ly > canvas.canvas_h){
cnt.push(j);
}
}
for(var k = 0; k < cnt.length ; k++){
self.lines.splice(k,1);
}
}
//增加线
Createline.prototype.addline = function(self,canvas){
var length = self.lines.length;
//横线
if(canvas.fx == "w"){
//判断是否需要生成线
if(self.lines[length-1].lx > 0){
//起点位置 等于 左右一根线的坐标减去间隔
var ww = self.lines[length - 1].lx - canvas.jiange;
//判断长短
if(self.c == 0){
var jg = canvas.width;
self.c = 10;
}else{
var jg = canvas.width/2;
self.c = 0;
}
var lxx = ww - jg;
var data = {
mx:ww,
lx:lxx,
my:canvas.my,
ly:canvas.ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}
//垂直
if(canvas.fx == "h"){
if(length>0){
//判断是否需要生成线
if(self.lines[length-1].ly > 0){
//起点位置 等于 左右一根线的坐标减去间隔
var my = self.lines[length - 1].ly - canvas.jiange;
//判断长短
if(c == 0){
var jg = canvas.width;
c = 10;
}else{
var jg = canvas.width/2;
c = 0;
}
var ly = my - jg;
var data = {
mx:canvas.mx,
lx:canvas.lx,
my:my,
ly:ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}else{
var data = {
mx:canvas.mx,
my:canvas.my,
lx:canvas.lx,
ly:canvas.ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}
}
export{
Createline
}
You need to use new when creating a instance for a constructor that uses this:
var cre = new Createline(data);
When a function is executed using new it does the following:
function User(name) {
// this = {}; (implicitly)
// add properties to this
this.name = name;
this.isAdmin = false;
// return this; (implicitly)
}

How to EXCLUDE MasterPage items when bulk exporting all text Frames

When I'm exporting all text frames from a file, the script sees the textframes in the masterpage and messes up the calculation and gives an error at the end because those frames are locked and can't be exported.
var myDoc = app.activeDocument;
var myFolder = myDoc.filePath;
var myImage = myDoc.textFrames;
var JPEGFolder = new Folder(myFolder+"/"+app.activeDocument.name+"_"+"JPEG");
if (!JPEGFolder.exists)
JPEGFolder.create();
var PromFolder = new Folder(myFolder+"/"+app.activeDocument.name+"_"+"Promethean");
if (!PromFolder.exists)
PromFolder.create();
var ToplamSoru = 0 ;
for (var i=0; myImage.length>i; i++)
{
app.select(myImage[i]);
ToplamSoru = ToplamSoru +1;
}
var Cevapli = (ToplamSoru/2-4);
alert(Cevapli);
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.maximum;
app.jpegExportPreferences.exportResolution = 150;
for (var p=0; p < myDoc.pages.length; p++)
{
for (var i=0; myImage.length>i; i++)
{
if ( i <= Cevapli -1){
if( i < 9)
{
app.select(myImage[i]);
var SoruNo = myImage[i].contents.substring(1,2);
app.selection[0].exportFile(ExportFormat.JPG, File(JPEGFolder+"/"+SoruNo+".JPEG"), false);
}
else
{
app.select(myImage[i]);
var SoruNo = myImage[i].contents.substring(1,3);
app.selection[0].exportFile(ExportFormat.JPG, File(JPEGFolder+"/"+SoruNo+".JPEG"), false);
}
}
else{
//alert(Cevapli);
if( i < 9 + Cevapli+1)
{
app.select(myImage[i]);
var SoruNo = myImage[i].contents.substring(1,2);
app.selection[0].exportFile(ExportFormat.JPG, File(PromFolder+"/"+SoruNo+".JPEG"), false);
}
else
{
app.select(myImage[i]);
var SoruNo = myImage[i].contents.substring(1,3);
app.selection[0].exportFile(ExportFormat.JPG, File(PromFolder+"/"+SoruNo+".JPEG"), false);
}
}
}
}
alert ("Done")
Basically, when i run the code, everything is OK and exported as wanted, but when there are more than the fixed number of text frames in the masterpage, it will be screwed up once again.
var Cevapli = (ToplamSoru/2-4);
Is where i decrease the value of the variable because there are 2 master pages with 4 different locked text frames.
How can i actually make the code exlude the items in the masterpages altogether?
The working code below:
var myDoc = app.activeDocument;
var myFolder = myDoc.filePath;
var TotalQuestions = 0 ;
var JPEGFolder = new Folder(myFolder+"/"+app.activeDocument.name+"_"+"JPEG");
var PromFolder = new Folder(myFolder+"/"+app.activeDocument.name+"_"+"Promethean");
var TotalPages = 0;
var Extension = prompt("Başına ne koyalım?","fen-");
if (!JPEGFolder.exists)
JPEGFolder.create();
if (!PromFolder.exists)
PromFolder.create();
for (i=0; i< app.documents[0].pages.length; i++)
{
TotalPages = TotalPages+1;
for (ii=0; ii< app.documents[0].pages[i].textFrames.length; ii++)
{
app.select(app.documents[0].pages[i].textFrames[ii]);
TotalQuestions = TotalQuestions +1;
}
}
//alert(ToplamSoru);
var Cevapli = TotalPages/2;
//alert(Cevapli);
app.jpegExportPreferences.jpegQuality = JPEGOptionsQuality.maximum;
app.jpegExportPreferences.exportResolution = 72;
var result = confirm ("Devam?", false,"EU Thingie");
if(result ==true){
for (i=0; i < app.documents[0].pages.length; i++){
// CEVAPLI //
if(i < Cevapli){
//alert(i+" "+ii+" IF");
for (ii=0; ii < app.documents[0].pages[i].textFrames.length; ii++){
var QID = app.documents[0].pages[i].textFrames[ii].contents.substring(1,3);
if( QID < 10){
app.select(app.documents[0].pages[i].textFrames[ii]);
var Less = app.documents[0].pages[i].textFrames[ii].contents.substring(1,2);
app.selection[0].exportFile(ExportFormat.JPG, File(PromFolder+"/"+Extension+Less+".JPEG"), false);
}
else{
app.select(app.documents[0].pages[i].textFrames[ii]);
var More = app.documents[0].pages[i].textFrames[ii].contents.substring(1,3);
app.selection[0].exportFile(ExportFormat.JPG, File(PromFolder+"/"+Extension+More+".JPEG"), false)
}
}
}
// CEVAPSIZ //
else{
//alert(i+" "+ii+" ELSE");
for (ii=0; ii < app.documents[0].pages[i].textFrames.length; ii++){
var QID = app.documents[0].pages[i].textFrames[ii].contents.substring(1,3);
if( QID < 10){
app.select(app.documents[0].pages[i].textFrames[ii]);
var Less = app.documents[0].pages[i].textFrames[ii].contents.substring(1,2);
app.selection[0].exportFile(ExportFormat.JPG, File(JPEGFolder+"/"+Extension+Less+".JPEG"), false);
}
else{
app.select(app.documents[0].pages[i].textFrames[ii]);
var More = app.documents[0].pages[i].textFrames[ii].contents.substring(1,3);
app.selection[0].exportFile(ExportFormat.JPG, File(JPEGFolder+"/"+Extension+More+".JPEG"), false)
}
}
}
}
}
//alert ("Done")
This will loop through the pages and every textFrame on each page. The text frames from Master Pages will be ignored.
for (i=0; i< app.documents[0].pages.length; i++){
for (ii=0; ii< app.documents[0].pages[i].textFrames.length; ii++){
$.writeln(app.documents[0].pages[i].textFrames[ii].contents);
}
}

SCRIPT16389: SCRIPT16389: Unspecified error. Edge Console

I know that some other questions posted are related to this topic but their answers don't help me.
I'm trying to implement battleship in js and while debugging I get SCRIPT16389: SCRIPT16389: Unspecified error. in the microsoft edge console.
Here's my js code so far: (I'm a beginner in javascript so sorry if serious mistakes)
var board = null;
var boats = null;
var rows = 8;
var columns = 8;
$(document).ready(function(){
if(typeof(Storage)!=="undefined"){
boats = JSON.parse(localStorage.getItem("boats"));
console.log(boats);
if(boats===null){
boats = [
{size:2, letter:'f', name:'fragate'},
{size:3, letter:'b', name:'buque'},
{size:3, letter:'s', name:'submarine'},
{size:4, letter:'d', name:'destructor'},
{size:5, letter:'p', name:'portplanes'},
];
localStorage.setItem("boats", JSON.stringify(boats));
}
rows = parseInt(localStorage.getItem("rows"));
columns = parseInt(localStorage.getItem("columns"));
if(isNaN(rows)|| isNaN(columns)){
rows = 8;
columns = 8;
localStorage.setItem("rows", 8);
localStorage.setItem("columns", 8);
}
}else {
console.log("We don't have localStorage")
}
});
function createMatrix(row,col){
var matrix;
matrix = new Array(row);
for (var i=0; i<row; i++){
matriz[i] = new Array(col);
}
return matrix;
}
function createFullMatrix(row,col,inside){
var matrix = new Array(row);
for(var i=0; i<row; i++){
matrix[i] = new Array(col);
for(var j=0; j<col; j++){
matrix[i][j]=inside;
}
}
return matrix;
}
function matrix2console(matrix){
var aux;
for(var i=0; i<matrix.length; i++){
aux = "";
for(var j=0; j<matrix[i].length; j++){
aux+=matrix[i][j]+'\t';
}
console.log(aux);
}
}
function createBoard(){
var html='<table>';
for(var i=0; i<rows; i++){
html+='<tr>';
for (var j=0; j<columns; j++){
html+='<td id="cel_'+i+'_'+j+'" class = "water"+ onclick=shoot("celd_'+i+'_'+j+'",'+i+','+j+')></td>';
}
html+='</tr>';
}
html+='</table>'
document.getElementById("match").innerHTML=html;
}
function createBoardjQ(){
$("#match").empty();
var table = $("<table />");
for(var i=0; i<rows; i++){
var row = $("<tr/>");
for(var j=0; j<columns; j++){
var celd = $('<td id="celd_'+i+'_'+j+'" onclick=shoot("celd_'+i+'_'+j+'",'+i+','+j+') > </td>');
celd.addClass("water");
row.append(celd);
}
table.append(row);
}
$("#match").append(table);
}
function createMatch(){
board = createMatrix(rows,columns);
startMatrix('a',board);
setBoats(board);
createBoardjQ();
matrix2console(board);
}
function shoot(celd, i, j){
switch (board[i][j]) {
case 'a':
board[i][j]= 'A';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('miss')
break;
case 'b':
board[i][j]= 'B';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
break;
case 'd':
board[i][j]= 'd';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
break;
case 'f':
board[i][j]= 'F';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
break;
case 'p':
board[i][j]= 'P';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
break;
case 's':
board[i][j]= 'S';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
break;
}
}
function startMatrix(data, matrix){
for(var i=0; i<matrix.length;){
for(var j=0; j<matrix[i].length;){
matrix[i][j]=data;
}
}
}
function dice(value){
var random;
random = Math.floor(Math.random()*(value));
return random;
}
function coin(){
return (dice(2));
}
function setBoats(matrix){
for (var i=0; i<boats.length; i++){
var boats = boats[i];
do{
var free=true;
var direction = coin();
if(!direction){
var row = dice(matrix.length);
var col = dice(matrix[row].length-boat.size);
for(var j=0; j<boat.size;j++){
if(matrix[row][j]!='a'){
free = false;
}
}
if(free){
for(var j=0; j<boat.size; j++){
matrix[row][j+col]=boat.letter;
}
}
}else{
var row = dice(matrix.length-boat.size);
var col = dice(matrix[row].length);
var row = dice(matrix.length);
var col = dice(matrix[row].length-boat.size);
for(var j=0; j<boat.size;j++){
if(matrix[j+row][col]!='a'){
free = false;
}
}
if(free){
for(var j=0; j<boat.size; j++){
matrix[j+row][col]=boat.letter;
}
}
}
}while(!free);
}
}
After correcting a number of typos and reviewing the logic, the primary issue reported was in startMatrix() where the for loops were not incrementing their counters. This caused an infinite loop.
Consider the following to fix:
function startMatrix(data, matrix) {
var singleRow, singleCol;
for (var r = 0; r < matrix.length; r++) {
for (var c = 0; c < matrix[r].length; c++) {
matrix[r][c] = data;
}
}
console.log("SM: Matrix Complete", matrix);
}
Full example: https://jsfiddle.net/Twisty/L1m6jw5q/58/
HTML
<div id="match">
</div>
CSS
#match td {
width: 20px;
height: 20px;
}
#match .water {
background-color: #ccf;
}
#match .miss {
background-color: #eee;
}
#match .boats {
background-color: #ccc;
}
JavaScript
var board = null;
var boats = null;
var rows = 8;
var columns = 8;
function createMatrix(row, col) {
var matrix;
matrix = new Array(row);
for (var i = 0; i < row; i++) {
matrix[i] = new Array(col);
}
console.log("CM: New Matrix Created", matrix);
return matrix;
}
function startMatrix(data, matrix) {
var singleRow, singleCol;
for (var r = 0; r < matrix.length; r++) {
for (var c = 0; c < matrix[r].length; c++) {
matrix[r][c] = data;
}
}
console.log("SM: Matrix Complete", matrix);
}
function createFullMatrix(row, col, inside) {
var matrix = new Array(row);
for (var i = 0; i < row; i++) {
matrix[i] = new Array(col);
for (var j = 0; j < col; j++) {
matrix[i][j] = inside;
}
}
return matrix;
}
function matrix2console(matrix) {
var aux;
for (var i = 0; i < matrix.length; i++) {
aux = "";
for (var j = 0; j < matrix[i].length; j++) {
aux += matrix[i][j] + '\t';
}
console.log(aux);
}
}
function createBoardjQ() {
$("#match").empty();
var table = $("<table />");
for (var i = 0; i < rows; i++) {
var row = $("<tr/>");
for (var j = 0; j < columns; j++) {
var celd = $('<td id="celd_' + i + '_' + j + '" data-shoot="celd_' + i + '_' + j + ',' + i + ',' + j + '"></td>');
celd.addClass("water");
row.append(celd);
}
table.append(row);
}
$("#match").append(table);
}
function createMatch() {
console.log("CMa: Make Board");
board = createMatrix(rows, columns);
console.log("CMa: Start Matrix", 'a', board);
startMatrix('a', board);
console.log("CMa: Set Boats", board);
setBoats(board);
console.log("CMa: Create Board jQ");
createBoardjQ();
console.log("CMa: Matrix to Console");
matrix2console(board);
}
function shoot(celd, i, j) {
switch (board[i][j]) {
case 'a':
board[i][j] = 'A';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('miss');
console.log("Miss");
break;
case 'b':
board[i][j] = 'B';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('boats');
console.log("Hit");
break;
case 'd':
board[i][j] = 'd';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('boats');
console.log("Hit");
break;
case 'f':
board[i][j] = 'F';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('boats');
console.log("Hit");
break;
case 'p':
board[i][j] = 'P';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('boats');
console.log("Hit");
break;
case 's':
board[i][j] = 'S';
$('#' + celd).removeClass('water');
$('#' + celd).addClass('boats');
console.log("Hit");
break;
}
}
function dice(value) {
var random;
random = Math.floor(Math.random() * (value));
return random;
}
function coin() {
return (dice(2));
}
function setBoats(matrix) {
var i, j, row, col, free;
for (i = 0; i < boats.length; i++) {
var boat = boats[i];
do {
free = true;
var direction = coin();
if (!direction) {
row = dice(matrix.length);
col = dice(matrix[row].length - boat.size);
for (j = 0; j < boat.size; j++) {
if (matrix[row][j] != 'a') {
free = false;
}
}
if (free) {
for (j = 0; j < boat.size; j++) {
matrix[row][j + col] = boat.letter;
}
}
} else {
row = dice(matrix.length - boat.size);
col = dice(matrix[row].length);
//row = dice(matrix.length);
//col = dice(matrix[row].length - boat.size);
for (j = 0; j < boat.size; j++) {
var k = (j + row) >= 1 ? (j + row) - 1 : 0;
console.log(j, row, k, boat.size);
if (k > matrix.length) {
free = false;
} else {
if (matrix[k][col] != 'a') {
free = false;
}
}
}
if (free) {
for (j = 0; j < boat.size; j++) {
matrix[j + row][col] = boat.letter;
}
}
}
} while (!free);
}
}
$(document).ready(function() {
if (typeof(Storage) !== "undefined") {
boats = JSON.parse(localStorage.getItem("boats"));
console.log(boats);
if (boats === null) {
boats = [{
size: 2,
letter: 'f',
name: 'fragate'
},
{
size: 3,
letter: 'b',
name: 'buque'
},
{
size: 3,
letter: 's',
name: 'submarine'
},
{
size: 4,
letter: 'd',
name: 'destructor'
},
{
size: 5,
letter: 'p',
name: 'portplanes'
},
];
localStorage.setItem("boats", JSON.stringify(boats));
}
rows = parseInt(localStorage.getItem("rows"));
columns = parseInt(localStorage.getItem("columns"));
if (isNaN(rows) || isNaN(columns)) {
rows = 8;
columns = 8;
localStorage.setItem("rows", 8);
localStorage.setItem("columns", 8);
}
console.log(rows, columns);
createMatch();
$(".water").click(function(e) {
console.log("Firing Shot", $(this));
var c = $(this).data("shoot").split(",");
shoot(c[0], c[1], c[2]);
});
} else {
console.log("We don't have localStorage");
}
});
Once the infinite loop was addressed, there was another logical error in setBoards(). Basically, there was a point where j + row would be greater than the index of matrix. You will want to review it and maybe even draw it out to make sure boats do not get placed off the board (which was always my favorite way to beat my brother at Battleship as a kid).
I also moved the click callback to jQuery. Just made it easier, so I stored the shot data in a data attribute for each cell. Easy to parse out and pass to shoot() for each click.
Hope that helps.

variable assignment doesn't work javascript

In the following code, the console.log from the line 92 and 93 (switchPosition function) doesn't provide the same result. I am, I have to admit, stuck.
Any thoughts, ideas, explanations?
Thanks you for the time taken,
var Carrousel = (function () {
var self = {},
config = {
item: 3, // item to be displayed
scroll: 2 // number of items to be scrolled
},
container = null,
items = null,
nbItems = null,
nbSlide = null,
position = [],
searchPositionDepending = []
;
self.init = function (opts) {
options = opts || {}
execute();
}
// Private Method
execute = function () {
container = document.getElementById('carrousel');
items = document.getElementsByClassName('flux');
var containerWidth = container.offsetWidth;
var containerHeight = items[0].offsetHeight * 1.5;
container.style.height = '' + containerHeight + '';
nbItems = document.getElementsByClassName('flux').length;
nbSlide = nbItems / config.item;
// Initialisation du Carrousel
for (i = 0; i < nbItems; i++) {
items[i].style.width = '' + (containerWidth / config.item) + '';
items[i].style.display = 'none';
items[i].style.position = 'absolute';
items[i].style.top = "0";
items[i].style.left = "0";
items[i].setAttribute('data-position', '' + (i + 1) + '');
items[i].setAttribute('data-number', '' + i + '');
}
searchPosition();
placement();
document.getElementById('next').onclick = function () {
next();
searchPosition();
switchPosition();
placement();
// position();
}
document.getElementById('previous').onclick = function () {
// previous();
// searchPosition();
// position();
}
}
searchPosition = function () {
for (i = 0; i < config.item; i++) {
searchPositionDepending[i] = (function () { //Appending a function searchPosition per item displayed
for (j = 1; j <= config.item; j++) { //Passing through the first items to get their position
if (items[i].dataset.position === '' + j + '') {
position[j] = items[i];
return true;
} else {
}
}
;
})();
}
}
switchPosition = function () {
for (i = 0, j = 0; i < nbItems; i++, j++) {
if (items[i].dataset.position === '' + j + '') {
position[i] = position[i];
}
}
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Replacing in good order, except for the one that are place into the variable position[];
items[i] = items[j];
}
for (i = (nbItems - config.item +1), j = 1; i <= nbItems; i++, j++) { //Replacing in good order the one that are place into variable position[];
items[i] = position[j];
console.log(i);
console.log(j);
console.log(position[j]);
console.log(items[i]);
}
for (i = 0; i < nbItems; i++) {
console.log(items[i]);
}
console.log(items[10]);
}
placement = function () {
for (i = 1; i <= config.item; i++) {
var rect = items[0].getBoundingClientRect();
item_width = Math.floor(rect.width);
item_height = Math.floor(rect.height);
var x = item_width * (i - 1) * 1.1;
items[i].style.display = 'block';
items[i].style.transform = "translate3D(" + x + "px, 0px, 0px)";
}
}
next = function () {
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Updating all dataset position, except for the items that are displayed.
items[i].dataset.position = j;
}
for (i = 1, j = 2; i <= config.item; i++, j--) {
position[i].dataset.position = nbItems - j;
position[i].style.display = "none";
}
}
return self;
})();

Can't fix errors in my javascript code

I am currently programming the conway game of life in Javascript but have encountered a few errors which I can't seem to find the solution to. the errors are:
Uncaught TypeError: Cannot read property '1' of undefined - which is this line - var currentneighbour = cell.grid[ro + neighbour1][col+neighbour2];
GoL.update - which is the same line as above
GoL.updateAll - which is this line - this.update(i,j);
(anonymous function) - which is this line at the bottom- gameoflife.updateAll();
I don't know why I am getting these errors, and followed a tutorial which seems to work for them.
here is my code for the game.
//object constructor
function cell(){
this.alive = Math.random() >0.7;
this.neighbours = 0; //number of live neighbours
this.checkneighbours = [[-1,-1],[-1,0],[0,-1],[-1,1],[1,-1],[1,0],[0,1],[1,1]];
}
function GoL(size){
this.size = size;
this.grid = this.makeGrid(size);
};
GoL.prototype.makeGrid = function(size){
var grid = [];
for(var i=0; i<size; i++){
var row=[];
for(var j =0; j<size; j++){
row.push(new cell());
}
grid.push(row);
}
return grid;
};
GoL.prototype.drawGrid = function(){
console.log("\033[2J");
for(var i=0;i<this.size;i++){
var row =this.grid[i];
var rowCell="";
for(var j=0;j<this.size;j++){
var cell = row[j];
if(cell.alive){
rowCell += "X|";
}else{
rowCell += " |";
}
}
console.log(rowCell);
}
};
GoL.prototype.underpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours <2){
return true;
}else{
return false;
}
};
GoL.prototype.overpopulation = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours >3){
return true;
}else{
return false;
}
};
GoL.prototype.backtolife = function(ro,col){
var cell = this.grid[ro][col];
if(cell.neighbours ===3 && !cell.alive){
return true;
}else{
return false;
}
};
GoL.prototype.update = function(ro,col){
var cell = this.grid[ro][col];
cell.num_of_neighbours = 0;
for(var i =0; i<cell.checkneighbours.length; i++){
var checkneighbour = cell.checkneighbours[i];
var neighbour1 = checkneighbour[0];
var neighbour2 = checkneighbour[1];
if(neighbour1>=0 && neighbour1 < this.size && neighbour2 >=0 && neighbour2 < this.size){
var currentneighbour = cell.grid[ro + neighbour1][col+neighbour2];
if(currentneighbour.alive){
cell.num_of_neighbours++;
}
}
}
};
GoL.prototype.updateAll = function(){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.update(i,j);
}
}
}
GoL.prototype.cellstatus = function(ro,col){
var cell = this.grid[ro][col];
if(this.underpopulation(ro,col) || this.overpopulation(ro,col)){
cell.alive = false;
}else if(this.backtolife(ro,col)){
cell.alive = true;
}
};
GoL.prototype.allcellstatus = function(ro,col){
for(var i=0; i<this.size;i++){
for(var j=0; j<this.size;j++){
this.cellstatus(i,j);
}
}
};
var gameoflife = new GoL(40);
var interval = setInterval(function(){
gameoflife.drawGrid();
gameoflife.updateAll();
gameoflife.allcellstatus();
},1000);
It's a typo.
var currentneighbour = cell.grid[ro + neighbour1][col + neighbour2];
should be
var currentneighbour = this.grid[ro + neighbour1][col + neighbour2];
An unrelated nearby bug: you are setting cell.num_of_neighbours++; but trying to read cell.neighbours.
Fiddle with those changes applied: https://jsfiddle.net/nw4Lw7z9/1/ There's still something very wrong with the game logic, those patterns don't match Conway's at all, but at least it's giving some output now...

Categories

Resources