transferring items among several arrays in javascript - javascript

I have got a pretty complicated issue, I tried everything and its not working properly. So the conception is (i just copied the interesting part of it, otherwise it would be few hundred more lines) :
The program is a card game and 24 cards (4 different colors, one is always stronger,it is called ADU) are distributed randomly among 4 players (4 arrays). The table where you put down the cards are represented by "asztal" array. First the human player puts a card, then the computers should reach in this order:
If they have same color and higher value - pick that card
If they have same color and any value - pick that card
If they dont have matching color, any car from the special color set (for being simple, its the first card the loop would find in the array)
If they dont have matching color, nor card from special color set, than the first element of the array (player[0]).
If you run my code, you would see it is not grabbing 1/1/1 card from each array, but sometimes more. And those cards do disappear, and not getting into the asztal array. My code: (https://jsfiddle.net/daxa3pL2/)
function CardA(name,value,adu){
this.name = name;
this.value = value;
};
function CardB(name,value,adu){
this.name = name;
this.value = value;
};
function CardC(name,value,adu){
this.name = name;
this.value = value;
};
function CardD(name,value,adu){
this.name = name;
this.value = value;
};
CardA.prototype.adu = false;
CardB.prototype.adu = false;
CardC.prototype.adu = false;
CardD.prototype.adu = false;
var a9 = new CardA("Tök kilenc",0);
var a10 = new CardA("Tök tíz",10);
var aal = new CardA("Tök alsó",2);
var afel = new CardA("Tök felső",3);
var akir = new CardA("Tök király",4);
var aasz = new CardA("Tök ász",11);
var b9 = new CardB("Levél kilenc",0);
var b10 = new CardB("Levél tíz",10);
var bal = new CardB("Levél alsó",2);
var bfel = new CardB("Levél felső",3);
var bkir = new CardB("Levél király",4);
var basz = new CardB("Levél ász",11);
var c9 = new CardC("Makk kilenc",0);
var c10 = new CardC("Makk tíz",10);
var cal = new CardC("Makk alsó",2);
var cfel = new CardC("Makk felső",3);
var ckir = new CardC("Makk király",4);
var casz = new CardC("Makk ász",11);
var d9 = new CardD("Szív kilenc",0);
var d10 = new CardD("Szív tíz",10);
var dal = new CardD("Szív alsó",2);
var dfel = new CardD("Szív felső",3);
var dkir = new CardD("Szív király",4);
var dasz = new CardD("Szív ász",11);
CardC.prototype.adu = true;
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
asztal.push(player1.splice(0,1)[0]);
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
if (asztal.length == 1) {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1){
for (i = 0; i < player2.length; i++) {
if (player2[i].adu == true) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1) {
asztal.push(player2.splice(0,1)[0])
return
}
};
var player3card1 = function() {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0]) && player3[i].value > asztal[0].value) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
if (asztal.length == 2) {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2){
for (i = 0; i < player3.length; i++) {
if (player3[i].adu == true) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2) {
asztal.push(player3.splice(0,1)[0])
return
}
};
var player4card1 = function() {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0]) && player4[i].value > asztal[0].value) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
if (asztal.length == 3) {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3){
for (i = 0; i < player4.length; i++) {
if (player4[i].adu == true) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3) {
asztal.push(player4.splice(0,1)[0])
return
}
};
player2card1();
player3card1();
player4card1();
console.log(player1);
console.log(player2);
console.log(player3);
console.log(player4);
console.log(asztal);

So I debugged your code and there are two fundamental mistakes I found:
1: When you use the splice inside a loop, the indices will change. So, when you do for example
asztal.push(player2.splice(i,i+1)[0])
and put it inside a loop, the indices for player2 matching your condition will change as soon as you do the splice. So the next iteration of your loop will give incorrect results/ miss an index of an object that should be removed.
A possible solution to this is that instead of splice, inside your for-loops, just insert elements into asztal, and DON'T splice the parent. Then outside the loop, splice them from from the players using a FILTER function as follows:
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push({name: player2[i].name, value: player2[i].value, prototype: player2[i].prototype});
player2[i].name = "delete";
return
}
}
player2.filter((each)=>{return each.name!== "delete"});
2: The second mistake (that I don't think is the problem here but still can cause trouble) is your use of "==". In Javascript, try to use '===' as far as possible as it also checks the type along with equality.

A little refactoring can go a long way to making this clear.
// define a card type class
function CardType(type, adu)
{
// This simply says that if ADU is undefined (not passed) then
// ADU should be set to false by default
this.adu = (typeof adu === 'undefined' ? false : adu);
this.type = type;
}
function Card(name, value, type)
{
this.name = name;
this.value = value;
this.type = type;
}
// Define our card types
var CardA = new CardType("A");
var CardB = new CardType("B");
var CardC = new CardType("C", true);// set to be ADU
var CardD = new CardType("D");
// Define our cards
var a9 = new Card("Tök kilenc",0, CardA);
var a10 = new Card("Tök tíz",10, CardA);
var aal = new Card("Tök alsó",2, CardA);
var afel = new Card("Tök felső",3, CardA);
var akir = new Card("Tök király",4, CardA);
var aasz = new Card("Tök ász",11, CardA);
var b9 = new Card("Levél kilenc",0, CardB);
var b10 = new Card("Levél tíz",10, CardB);
var bal = new Card("Levél alsó",2, CardB);
var bfel = new Card("Levél felső",3, CardB);
var bkir = new Card("Levél király",4, CardB);
var basz = new Card("Levél ász",11, CardB);
var c9 = new Card("Makk kilenc",0, CardC);
var c10 = new Card("Makk tíz",10, CardC);
var cal = new Card("Makk alsó",2, CardC);
var cfel = new Card("Makk felső",3, CardC);
var ckir = new Card("Makk király",4, CardC);
var casz = new Card("Makk ász",11, CardC);
var d9 = new Card("Szív kilenc",0, CardD);
var d10 = new Card("Szív tíz",10, CardD);
var dal = new Card("Szív alsó",2, CardD);
var dfel = new Card("Szív felső",3, CardD);
var dkir = new Card("Szív király",4, CardD);
var dasz = new Card("Szív ász",11, CardD);
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
// It doesn't really make sense to splice the array because
// you are changing the array.
// asztal.push(player1.splice(0,1)[0]);
// This line can be replaced with a simple:
asztal.push(player1[0]);
// This function has lots of redundant code and we can simplify it greatly
// as well as generalize it to work for each player
function getNextCard(player, card){
// By default we take the first card unless we find a better one along the way.
var matchCase2 = null, // same type, any value
matchCase3 = null, // special set
matchCase4 = player[0]; // any card
for(i = 0; i < player.length; i++)
{
// Check our first case
if(player[i].type.type == card.type.type &&
player[i].value > card.value){
return player[i];
}
if(matchCase2 === null && player[i].type.type == card.type.type){
matchCase2 = player[i];
}
if(matchCase3 === null && player[i].type.adu === true){
matchCase3 = player[i];
}
}
if(matchCase2 !== null) return matchCase2;
if(matchCase3 !== null) return matchCase3;
return matchCase4;
}
console.log(getNextCard(player2, asztal[0]));
console.log(getNextCard(player3, asztal[0]));
console.log(getNextCard(player4, asztal[0]));

Related

How do I get the next value from a javascript array to compare against the current value in a for loop

I have a snippet of code that compares two dates and if they're the same it sets a boolean to true. I am getting an error on the line: var nextFolioArrive = new Date(this.folios[i+1].folioDepart);
TypeError: Cannot read property "folioDepart" from undefined. (line 50, file "propertyObject")
However it throws no error when I define:
var folioDepart = new Date(this.folios[i].folioDepart);
I was wondering if I can't "look ahead" in an array like that, not sure why it would be an issue.
property.prototype.isTurn = function(){
for (var i=0;i<this.folios.length;i++){
var folioArrive = new Date(this.folios[i].folioArrive);
var folioDepart = new Date(this.folios[i].folioDepart);
var nextFolioArrive = new Date(this.folios[i+1].folioDepart);
if(folioDepart == nextFolioArrive && folioArrive == TODAY){
Logger.log("turn day: " +this.turnDay);
return this.turnDay = true;
}
Logger.log("turn day: false" );
}
}
Here is all the code in the property object, I feel like I am making a silly syntax mistake or over looking something small.
var TODAY = new Date();
TODAY.setHours(0,0,0,0)
var propertyList = new Array();
function property(name,address) {
//Default variables
//Object variables
this.name = name;
this.address = address;
this.workOrders = new Array();
this.folios = new Array();
this.GIH = false;
this.turnDay = false;
propertyList.push(this);
property.prototype.listArrivals = function(){
Logger.log(this.name);
for(var i=0;i<this.folios.length;i++){
Logger.log(this.folios[i].folioID);
}
}
property.prototype.listWorkorders = function(){
Logger.log(this.name);
for(var i=0;i<this.workOrders.length;i++){
Logger.log(this.workOrders[i].workorderID);
}
}
property.prototype.getGIH = function(){
for (var i = 0;i<this.folios.length;i++){
var folioArrive = new Date(this.folios[i].folioArrive);
var folioDepart = new Date(this.folios[i].folioDepart);
if(TODAY >= folioArrive && TODAY <= folioDepart && this.GIH == false){
return this.GIH = true;
}
}
}
property.prototype.isTurn = function(){
for (var i=0;i<this.folios.length;i++){
var folioArrive = new Date(this.folios[i].folioArrive);
var folioDepart = new Date(this.folios[i].folioDepart);
var k = i+1;
var nextFolioArrive = new Date(this.folios[k].folioDepart);
if(folioDepart == nextFolioArrive && folioArrive == TODAY){
Logger.log("turn day: " +this.turnDay);
return this.turnDay = true;
}
Logger.log("turn day: false" );
}
}
}
I should have included my testing environment.
function myFunction() {
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
var tempPropertyList = [];
var tempWorkOrderList = [];
var tempFolioList = [];
var i;
var j;
var k;
var property1 = new property("property1","123 street");
var property2 = new property("property2","123 ave");
// folio(ID,type,propName,address,arrive,depart)
var folio1 = new folio("303245","type","property1","123 street","03/14/2019", "03/30/2019");
var folio2 = new folio("303243","type","property2","123 ave","03/26/2019", "03/30/2019");
var folio3 = new folio("303244","type","property1","123 street","03/30/2019", "04/10/2019");
var folio4 = new folio("303246","type","property2","123 ave","03/20/2019", "03/25/2019");
var folio5 = new folio("303247","type","property1","123 street","03/01/2019", "03/14/2019");
//workOrder(ID,propName,type,description,due,notes) {
var wo1 = new workOrder("12","property1","Maint","workOrder1","03/14/2019","");
var wo2 = new workOrder("13","property2","Maint","workOrder2","03/20/2019","");
var wo3 = new workOrder("14","property1","Maint","workOrder3","03/19/2019","");
var wo4 = new workOrder("15","property1","Maint","workOrder4","02/02/2019","");
var wo5 = new workOrder("16","property2","Maint","workOrder5","03/14/2019","");
var wo6 = new workOrder("17","property2","Maint","workOrder6","03/14/2019","");
var wo7 = new workOrder("18","property1","Maint","workOrder7","03/15/2019","");
var wo8 = new workOrder("19","property1","Maint","workOrder8","03/16/2019","");
var wo9 = new workOrder("10","property2","Maint","workOrder9","04/01/2019","");
var wo10 = new workOrder("11","property2","Maint","workOrder10","05/05/2019","");
//push objects to arrays
tempWorkOrderList.push(wo1,wo2,wo3,wo4,wo5,wo6,wo7,wo8,wo9,wo10);
tempFolioList.push(folio1,folio5,folio2,folio3,folio4);
tempPropertyList.push(property1,property2);
for (i=0;i<tempPropertyList.length;i++){
tempPropertyList[i].isTurn();
for (j=0;j<tempWorkOrderList.length;j++){
if (tempWorkOrderList[j].workorderProperty == tempPropertyList[i].name){
tempPropertyList[i].workOrders.push(tempWorkOrderList[j]);
}
}
for (k=0;k<tempFolioList.length;k++){
if(tempFolioList[k].folioProperty == tempPropertyList[i].name){
tempPropertyList[i].folios.push(tempFolioList[k]);
}
}
tempPropertyList[i].isTurn();
}
}
Check the existance of the object first before using its property
property.prototype.isTurn = function(){
for (var i=0;i<this.folios.length;i++){
var folioArrive = new Date(this.folios[i].folioArrive);
var folioDepart = new Date(this.folios[i].folioDepart);
// check next folio
if (typeof this.folios[i+1] != 'undefined') {
var nextFolioArrive = new Date(this.folios[i+1].folioDepart);
if(folioDepart == nextFolioArrive && folioArrive == TODAY){
Logger.log("turn day: " +this.turnDay);
return this.turnDay = true;
}
Logger.log("turn day: false" );
}
}
}

Google spreadsheet custom function returns nothing

I have a problem debugging the code. It's working if I define values by myself instead of taking it from properties and spreadsheet. I am new to JavaScript so it can be really basic error.
What I am trying to do with this function:
Taking name of person, date and name of school from the spreadsheet
Getting arrays data from the properties that was saved with other function. The saving line in that function looks like this:
PropertiesService.getScriptProperties().setProperty('Mokyklo‌​s', JSON.stringify(Mokyklos));
It's 6 arrays of full names, array of date, array of school names and array of numbers. The numbers array is used to return the answer.
function ApmokMokMokykloje(mokytojas, data, mokykla) {
Utilities.sleep(Math.random() * 1000);
var MokytojaiL = PropertiesService.getScriptProperties().getProperty('MokytojaiL');
var Mokytojai1 = PropertiesService.getScriptProperties().getProperty('Mokytojai1');
var Mokytojai2 = PropertiesService.getScriptProperties().getProperty('Mokytojai2');
Utilities.sleep(Math.random() * 1000);
var Mokytojai3 = PropertiesService.getScriptProperties().getProperty('Mokytojai3');
var Mokytojai4 = PropertiesService.getScriptProperties().getProperty('Mokytojai4');
var Mokytojai5 = PropertiesService.getScriptProperties().getProperty('Mokytojai5');
Utilities.sleep(Math.random() * 1000);
var Datos = PropertiesService.getScriptProperties().getProperty('Datos');
var Mokyklos = PropertiesService.getScriptProperties().getProperty('Mokyklos');
var ApmokMokSkaiciai = PropertiesService.getScriptProperties().getProperty('ApmokMokSkaiciai');
var mokytojaiL = MokytojaiL;
mokytojaiL = JSON.parse(mokytojaiL);
var mokytojai1 = Mokytojai1;
mokytojai1 = JSON.parse(mokytojai1);
var mokytojai2 = Mokytojai2;
mokytojai2 = JSON.parse(mokytojai2);
var mokytojai3 = Mokytojai3;
mokytojai3 = JSON.parse(mokytojai3);
var mokytojai4 = Mokytojai4;
mokytojai4 = JSON.parse(mokytojai4);
var mokytojai5 = Mokytojai5;
mokytojai5 = JSON.parse(mokytojai5);
var datos = Datos;
datos = JSON.parse(datos);
var mokyklos = Mokyklos;
mokyklos = JSON.parse(mokyklos);
var skaicius = ApmokMokSkaiciai;
skaicius = JSON.parse(skaicius);
for(var i = 0; i < mokyklos.length; i++) {
if(data==datos[i] && mokykla==mokyklos[i]) {
if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i])) {
return skaicius[i]; // returns blank
}
}
}
}
The code below works fine.
function testas3(mokytojas, data, mokykla) {
// the same values from spreadsheet
var datapvz="2017-11-04T22:00:00.000Z";
var mokyklapvz="Zalioji mokykla";
var mokytojaspvz="Penivilas Gremlinavičius";
// the same values from properties
var datos = [];
datos[0]="2017-11-08T22:00:00.000Z";
datos[1] = "2017-11-15T22:00:00.000Z";
datos[2] = "2017-11-11T22:00:00.000Z";
datos[3] = "2017-11-03T22:00:00.000Z";
datos[4] = "2017-11-04T22:00:00.000Z";
var mokyklos = [];
mokyklos[0] = "Mokykla nuostabioji";
mokyklos[1] = "Mylimiausioji mokyklele";
mokyklos[2] = "Dar viena mokyykla";
mokyklos[3] = "Raudonoji";
mokyklos[4] = "Zalioji mokykla";
var mokytojaiL = [];
mokytojaiL[0] = "Cristopher Rangel";
mokytojaiL[1] = "Alessandra Knox";
mokytojaiL[2] = "Germtautas Falalavičius";
mokytojaiL[3] = "Lenkgaudė Trikojytė";
mokytojaiL[4] = "Penivilas Gremlinavičius";
var mokytojai1 = [];
mokytojai1[0] = "Mantvydas Špukys";
mokytojai1[1] = "Išeikbaida Visursėkmytė";
mokytojai1[2] = "Svaidgaudė Praperduvienė";
mokytojai1[3] = "Mantvinas Žirgmyla";
mokytojai1[4] = "Mantvinas Žirgmyla";
var mokytojai2 = [];
mokytojai2[0] = "Griovbaida Nepriteklytė";
mokytojai2[1] = "Išeikbaida Visursėkmytė";
mokytojai2[2] = "Griovbaida Nepriteklytė";
mokytojai2[3] = "Arjautauta Fragmentavičiutė";
mokytojai2[4] = "Kastuvaldas Parašiutauskas";
var mokytojai3 = [];
mokytojai3[0] = "Rustautas Celiulionis";
mokytojai3[1] = "Androbauda Parankpapaitė";
mokytojai3[2] = "Arjauvilė Katrakojytė";
mokytojai3[3] = null;
mokytojai3[4] = "Rustautas Celiulionis";
var mokytojai4 = [];
mokytojai4[0] = null;
mokytojai4[1] = null;
mokytojai4[2] = null;
mokytojai4[3] = "Arjauvilė Katrakojytė";
var mokytojai5 = [];
var skaicius = [];
skaicius[0]="99";
skaicius[1]="98";
skaicius[2]="87";
skaicius[3]="89";
skaicius[4]="89";
for(var i = 0; i < mokyklos.length; i++) {
if(datapvz==datos[i] && mokyklapvz==mokyklos[i]) {
if ((mokytojaspvz==mokytojaiL[i]) || (mokytojaspvz==mokytojai1[i]) || (mokytojaspvz==mokytojai2[i]) || (mokytojaspvz==mokytojai3[i]) || (mokytojaspvz==mokytojai4[i]) || (mokytojaspvz==mokytojai5[i]))
{
return skaicius[i]; // returns 89
}
}
}
}
I think the problem is that you're comparing a Date object (from the spreadsheet...e.g., from cell F$1) with a string literal (from your saved JSON object). To make them match, you should call toJSON() on the date object before comparing, like this:
var date = data.toJSON();
for(var i = 0; i < mokyklos.length; i++) {
if(date==datos[i] && mokykla==mokyklos[i]) {
if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i])) {
return skaicius[i];
}
}
}

How do I get JavaScript to recognize whether an object is in an array?

New to JavaScript objects. In the code below, I'm able to create and populate a list of book objects that each person has "checked out". However I am unable to "return" the books because I can't get seem to identify which patron's array the book is "checked out" in. I'm using
if (object in array) . . .
I got this from one of the previous answers. The statement block with the if never executes. Thanks for your help!
function Book(title, pub_date, call_number, authors){
this.title = title;
this.availability = true;
this.pub_date = pub_date;
this.current_date = null;
this.check_out_date = null;
this.call_number = call_number;
this.authors = authors;
}
Book.prototype.checkOut = function(){
this.availability = false;
var rdom = (Math.random() * 31 +1).toFixed(0);
var current_date = new Date();
this.check_out_date = new Date(current_date - rdom*24*3600*1000);
}
Book.prototype.checkIn = function(){
this.availability = true;
}
Book.prototype.isOverdue = function(){
var current_date = new Date();
if ((current_date - this.check_out_date)/1000/3600/24 > 14)
return true;
else
return false;
}
function Author(first_name, last_name){
this.first_name = first_name;
this.last_name = last_name;
}
function Patron(firstname, lastname, lib_card){
this.firstname = firstname;
this.lastname = lastname;
this.lib_card = lib_card;
this.books_out = [];
this.fine = 0;
}
Patron.prototype.readBook = function(book){
this.books_out.push(book);
}
Patron.prototype.returnBook = function(book){
this.books_out.pop(book);
}
var redAuthors, blueAuthors, greenAuthors, yellowAuthors, purpleAuthors
var redAuthor1 = new Author('John', 'Smith');
var redAuthor2 = new Author('James', 'Sullivan');
var redAuthors = [redAuthor1, redAuthor2];
var blueAuthors = greenAuthors = yellowAuthors = purpleAuthors = redAuthors;
redBook = new Book('Lakes', 1963, 456789, redAuthors);
blueBook = new Book('Rivers', 1964, 123456, blueAuthors);
greenBook = new Book('Streams', 1965, 234567, greenAuthors);
yellowBook = new Book('Ponds', 1966, 345678, yellowAuthors);
purpleBook = new Book('Brooks', 1967, 567891, purpleAuthors);
var catalog = [redBook, blueBook, greenBook, yellowBook, purpleBook]
var patron1 = new Patron('Sally', 'Hudson', '1');
var patron2 = new Patron('Rachel', 'Hung', '2');
var patron3 = new Patron('Andy', 'Cunningham', '3');
var patron4 = new Patron('Steve', 'Cote', '4');
var patron5 = new Patron ('Ted', 'Mitrou', '5');
var patrons = [patron1, patron2, patron3, patron4, patron5]
for (var day_count = 0; day_count < 10; day_count++){
for (var book_count = 0; book_count < 5; book_count++){
if (catalog[book_count].availability == true){
for (var pat_count = 0; pat_count < 5; pat_count++){
if (patrons[pat_count].books_out.length <= 1){
catalog[book_count].checkOut();
patrons[pat_count].readBook(catalog[book_count]);
break;
}
else
continue;
}
}
else {
catalog[book_count].checkIn();
for (pat_counter = 0; pat_counter < 5; pat_counter++){
if (catalog[book_count] in patrons[pat_counter].books_out){
if (catalog[book_count].isOverdue)
patrons[pat_counter].fine += 5;
patrons[pat_counter].books_out.returnBook(catalog[book_count]);
}
}
}
}
}
for (var k = 0; k < 5; k++){
console.log("Patron: " + patrons[k].firstname + " " + patrons[k].lastname);
console.log("Books checked out: ")
for (l = 0; l < patrons[k].books_out.length; l++) {
console.log(patrons[k].books_out[l].title);
}
console.log("Fine: $" + patrons[k].fine);
console.log();
}
You can use indexOf:
if (array.indexOf(object) > -1)
x in y would only return true if x is a string containing the name of a property on y.

why will lines 56 and 67 not work? (.votess +=1;)

var imgs = ['bmw.jpg', 'bugatti.jpg', 'classic.jpg', 'concept.jpg', 'corvette.jpg', 'dino.jpg', 'lambo.jpg', 'mcclaren.jpg', 'p1.jpg', 'porsche.jpg', 'rally.jpg', 'audi.jpg'];
// var imgs_count = {'bmw.jpg': 0, 'bugatti.jpg': 0, 'classic.jpg': 0, 'concept.jpg': 0, 'corvette.jpg': 0, 'dino.jpg': 0, 'lambo.jpg': 0, 'mcclaren.jpg': 0, 'p1.jpg': 0, 'porsche.jpg': 0,'rally.jpg': 0, 'audi.jpg':0}
// for (var i in imgs_count) {
// imgs_count[i]
// }
var allCars = [];
var votes;
function Car(file) {
this.file = file;
this.votes = 0;
allCars.push(this);
}
var bmw = new Car('bmw.jpg');
var bugatti = new Car('bugatti.jpg');
var classic = new Car('classic.jpg');
var concept = new Car('concept.jpg');
var corvette = new Car('corvette.jpg');
var dino = new Car('dino.jpg');
var lambo = new Car('lambo.jpg');
var mcclaren = new Car('mcclaren.jpg');
var p1 = new Car('p1.jpg');
var porsche =new Car('porsche.jpg');
var rally = new Car('rally.jpg');
var audi = new Car('audi.jpg');
var idx1 = 0;
var idx2 = 0;
var path = 'cars/';
var done = false;
function getRandomImage() {
idx1 = Math.floor(Math.random()*imgs.length);
var img1 = imgs[idx1];
idx2 = idx1;
while (idx2 == idx1) {
idx2 = Math.floor(Math.random()*imgs.length);
}
img2 = imgs[idx2];
document.getElementById('choice1').setAttribute('src', path + img1);
document.getElementById('choice2').setAttribute('src', path + img2);
}
function setOnClicks(id) {
document.getElementById(id).addEventListener('click', function(event) {
var choice = event.target.id;
if (choice === 'choice1') {
console.log(allCars);
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
this.allCars[idx1].votes += 1;
console.log(idx1);
console.log(this.allCars[idx1].votes)
if ( allCars[idx1].votes=3) {
done = true;
}
}
if (choice === 'choice2') {
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
console.log(idx2);
console.log(this.allCars[idx2].votes);
this.allCars[idx2].votes += 1;
if (allCars[idx2].votes == 3) {
done = true;
}
}
if (!done)
getRandomImage();
});
}
getRandomImage();
setOnClicks('choice1');
setOnClicks('choice2')l
You're overwriting your global allCars with a local var declaration of the same name:
var allCars = img.slice(5,img.length);
you are creating a local variable allCars under click event, while this.allCars is point to the allCars variable under window object
var allCars = img.slice(5,img.length); // this is a local variable
this.allCars[idx1].votes += 1; // this is same as window.allCars
console.log(idx1);

Html5/javascript/easeljs game project.Lots of code.I need a way out

I am working on a card game with HTML5 canvas and javascript with create.js library. The problem i have is that, I have an onclick function that deletes the clicked card from player's hand(removes the object from the array with splice and then redraws the canvas/redraws on canvas the new array of player's cards without the deleted one). When i do this for first time it does well.But if I click again on the card that it should be for example at index 1 in the array(after the splice method) it doesn't work.
Look at this code:
Here is my code for class Card:
function Card(suit,rank,imageFrontUrl,imageBackUrl)
{
this.imageFront = new createjs.Bitmap(imageFrontUrl);
this.imageBack = new createjs.Bitmap(imageBackUrl);
this.suit = suit;
this.rank = rank;
}
function Deck(){
this.cards = new Array();
this.makeDeck = function()
{
this.cards[0]= new Card("clubs",1,"images/114.png","images/155.png");
this.cards[1]= new Card("clubs",2,"images/115.png","images/155.png");
this.cards[2]= new Card("clubs",3,"images/116.png","images/155.png");
this.cards[3]= new Card("clubs",4,"images/117.png","images/155.png");
this.cards[4]= new Card("clubs",5,"images/118.png","images/155.png");
this.cards[5]= new Card("clubs",6,"images/119.png","images/155.png");
...
}
this.shuffleDeck = function()
{
var j,k;
for (j = 0; j < this.cards.length; j++) {
k = Math.floor(Math.random() * this.cards.length);
temp = this.cards[j];
this.cards[j] = this.cards[k];
this.cards[k] = temp;
}
}
this.dealCardsPlayer = function()
{
var playerDeck = new Array();
for(var i = 0; i<6;i++)
{
var x = this.cards.pop();
playerDeck.push(x);
}
return playerDeck;
}
}
Here is my code for class Player:
function Player()
{
this.playerTurn = false;
this.id = this;
this.name = this;
this.score = this;
this.playerHand = new Array();
this.playerTakenCards = new Array();
this.playerPickCard = function(n)
{
var card = this.playerHand(n);
return card;
}
this.tempArray = this;}
Here is my init function:
function init(){
var canvas = document.getElementById("tutorialCanvas");
var stage = new createjs.Stage(canvas);
var deck = new Deck();
var player1 = new Player();
deck.makeDeck();
deck.shuffleDeck();
player1.playerHand = deck.dealCardsPlayer();
function drawPlayerCards(){
var rotation=280;
for(var i =0;i<player1.playerHand.length;i++)
{
player1.playerHand[i].imageFront.x=330;
player1.playerHand[i].imageFront.y=750;
player1.playerHand[i].imageFront.regX = 0;
player1.playerHand[i].imageFront.regY = 96;
player1.playerHand[i].imageFront.rotation = rotation;
rotation = player1.playerHand[i].imageFront.rotation+20;
stage.addChild(player1.playerHand[i].imageFront);
}
}
createjs.Ticker.addEventListener("tick", stage);}
And here is the function i have problem with:
player1.playerHand[1].imageFront.addEventListener('click',function(event)
{
stage.removeAllChildren();
player1.playerHand.splice(1,1);
drawTableDeck();
drawPlayerCards();
}
After some researching I realized that the function works just for the first bitmap player1.playerHand[1].imageFront . If i change the array with the first onclick event and after that player1.playerHand[1].imageFront is some other image/bitmap, it doesn't work for it. Please help!
Why are you "hardcoding" the index of a card in your hand?
player1.playerHand.forEach(function(card) {
card.imageFront.addEventListener("click", function() {
var index = player1.playerHand.indexOf(card);
if (index != -1) {
stage.removeAllChildren();
player1.playerHand.splice(index, 1);
drawPlayerCards();
}
});
});
Some other notes:
It's a convention to use [] instead of new Array()
We normally put the opening brace { on the same line
Your Player constructor has an error: this.playerHand[n] instead of this.playerHand(n)

Categories