Why does my card game not work ...?

Hi. I have a problem with the code that I do not know how to fix.
It consists of a game players draw cards, each of their deck, and the first to draw three equal, wins.
But I can not start the game. After naming the players, I get an error: winner is not defined.
If you can tell me how I can fix, I’ll show you the code.
Thank you

//I create the variable types of the numbers, the clubs and the deck
var cards = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var suits = ["diamonds", "hearts", "spades", "clubs"];
var deck = new Array();
var player = new Array();

function getDeck() {
    var deck = new Array();
    //load the deck of cards
    for (var i = 0; i < suits.length; i++) {
        for (var x = 0; x < cards.length; x++) {
            var card = { Value: cards[x], Suit: suits[i] };
            deck.push(card);
        }
    }

    return deck;
}

function deal() {
    // take the last card out of the deck
    var card = deck[deck.length - 1];
    deck.splice(deck.length - 1, 1);
    return card;
}

function shuffle() {
    // change two random cards of position 1000 times
    for (var i = 0; i < 1000; i++) {
        var location1 = Math.floor((Math.random() * deck.length));
        var location2 = Math.floor((Math.random() * deck.length));
        var tmp = deck[location1];

        deck[location1] = deck[location2];
        deck[location2] = tmp;
    }
}

function renderDeck(deck, number) {
    for (var i = 0; i < deck.length; i++) {
        var card = document.createElement("div");
        var value = document.createElement("div");
        var suit = document.createElement("div");
        card.className = "card";
        value.className = "value";
        suit.className = "suit " + deck[i].Suit;

        value.innerHTML = deck[i].Value;
        card.appendChild(value);
        card.appendChild(suit);

        document.getElementById("deck" + number).appendChild(card);
    }
}

function game(deck) {

    var cont = new array();
    for (var i = 1; i < 10; i++) {
        //I create an accountant for each of the numbers in the deck
        cont[i] = 0;
    }

    //score counter
    var score = 0;

    //I create a new deck to contain the cards that I am taking out
    var newDeck = "";

    //while none of the counters reaches 3, the game continues
    while (cont[1] < 3 || cont[2] < 3 || cont[3] < 3 || cont[4] < 3 || cont[5] < 3 || cont[6] < 3 || cont[7] < 3 || cont[8] < 3 || cont[9] < 3 || cont[10] < 3) {

        //I take out the last card in the deck
        newDeck[score] = deck.pop();

        //I look for what value corresponds to the letter and raise the account of your corresponding counter
        if (newDeck[score].value = 1) {
            cont[1]++;
        }

        else if (newDeck[score].value = 2) {
            cont[2]++;
        }

        else if (newDeck[score].value = 3) {
            cont[3]++;
        }

        else if (newDeck[score].value = 4) {
            cont[4]++;
        }

        else if (newDeck[score].value = 5) {
            cont[5]++;
        }

        else if (newDeck[score].value = 6) {
            cont[6]++;
        }

        else if (newDeck[score].value = 7) {
            cont[7]++;
        }

        else if (newDeck[score].value = 8) {
            cont[8]++;
        }

        else if (newDeck[score].value = 9) {
            cont[9]++;
        }

        else {
            cont[10]++;
        }

        //increase the score counter
        score++;
    }

    //I return the score and the deck with the resulting cards
    return score, new Deck;
}

function players() {

    //I wonder how many players will be
    var number = prompt("¿Cuántas personas van a jugar?", "2");

  // depending on how many they are, I create the same number of prompts to ask their names
       // and store them in localStorage

    for (var i = 0; i < number; i++) {
        player[i] = prompt("¿Cómo se llama el jugador número " + i + "?");
    }
    //since localStorage only allows me to save Strings, I use stringify to pass the array
    localStorage.setItem('nickName', JSON.stringify(player));

    //I return the array of players
    return player;
}


function myFunction() {
    players();

    for (var i = 0; i < player.lenght; i++) {
        //create a div to put the information of each player
        var playerTitle = document.createElement("div");
        var playerName = document.createTextNode(player[i]);
        playerTitle.appendChild(playerName);
        playerTitle.classname = "playerTitle";

        document.getElementById("results").appendChild(playerTitle);

        var deckShow = document.createElement("div");
        deckShow.id = "deck" + i;
        document.getElementById("results").appendChild(deckShow);
    }

    //I make the game for each player
    for (var i = 0; i < player.lenght; i++) {


        //initialize the decks
        deck[i] = getDeck();
        shuffle();


        //create the game
        game(deck[i]);
        console.log(game);
        //show the deck
        renderDeck(newDeck, i);
        //save the score in an array to pass it to localStorage
        var finalScore = "";
        finalScore[i] = score;

        //show the result
        document.getElementById("playerTitle" + i).innerHTML = player[i] + " ha conseguido su objetivo en " + score + "turnos.";

        //I generate a tuple to check the winner
        const winner = (player[i], score)

        //I pass the array to localStorage
        localStorage.setItem('score', JSON.stringify(finalScore));

        //I determine the winner

        console.log(players);
        console.log(deck);


    }
    var which = Math.min(...winner.score);
    for (var i = 0; i < player.lenght; i++) {
        if (which == winner[i].score) {

            document.getElementById("finalScore").innerHTML = "El ganador es " + winner[i].player;
        }
        else { }
    }

// HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Lobster|Righteous" rel="stylesheet">
    <title>Cartas - Ejercicio 1 - Alba Jato PEC</title>
    <link rel="stylesheet" href="cartas.css">
</head>
<body>
    <h1 id="title">¡Consigue 3 iguales!</h1>
    <p>Dale al botón e inicia el juego</p>
            <p><button onclick="myFunction()">¡Inicia el juego!</button></p>
            <div id="results"></div>
            <div id="finalScore"></div>
            <script src="cartas.js"></script>
</body>

</html>

// css code
#title {

	font-family: 'Lobster', cursive;
	font-size: 75px;
	padding-left: 25px;
	margin:0;

}

body{
	color: #80727B;
	font-family: 'Righteous', cursive;
	font-size: 25px;
}

#finalScore {
	margin: 25px;
	background-color: #80727B;
	color: white;
	width: 650px;
}

.card
{
	border: solid 1px #aaa;
	border-radius: 9px;
	width: 95px;
	height: 150px;
	float:left;
	background-color: white;
	padding: 3px 3px 3px 3px;
}

.card .value{
	font-size:15pt;
	font-family: sans-serif;
}

.card .suit
{
	background-image: url('http://www.thatsoftwaredude.com/images/post/0f631eeb-6c4a-4bfd-9f86-e0a08ae8584b.png');
	height: 100px;
	width: 90px;
}

.card .diamonds
{
	background-position-y: 100px;
}

.card .hearts
{
	background-position-x: 90px;
}

.card .clubs
{
	background-position-x:90px;
	background-position-y:100px;
}

You don’t have an array called winner, and you try to access that non-existant array in the document.getElementById("finalScore")... line.

You do try to create something called winner in a loop earlier in the code:

//I generate a tuple to check the winner
const winner = (player[i], score)

This is not Python, JS does not have tuples, and this should show as a syntax error.

Can I ask what environment you are writing this code in (CodePen, a text editor, or something else) because there are several syntax errors and several misnamed methods that you should be getting warnings about here. There are a couple of lenghts for example. And you’re randomly interspersing var and const. And there’s the tuple syntax, which is from a completely different programming language.

1 Like

And how could I fix this mess …?
I was guided by an example of a partner to try to solve.
I work with Visual Studio, but he sent it to me by codepen.
Do you have any solution?

I’m on a phone so I can’t run the code to check things, but:

Use an object or an array to replace the code that is specified as a tuple. I think it has to be an object because of how you try to access it afterwards. I’m not sure if the logic is correct overall though, so can’t be sure.

I don’t know about if/what extension you need in basic VS, but in VSCode, out of the box the debug tab in the bottom panel shows issues with the JS code, same as it would for C# or whatever. CodePen will highlight errors as well.

1 Like

Thanks, visual studio shows no errors.
I already tried to solve without success, that’s why I looked for help.
I will keep trying.
Thanks for the support.

So I didn’t have time to try to run the code, but I did dump it into VS, and you are right in that it doesn’t show lint errors, just runtime errors. You need to review the code you’ve written: there are obvious errors that won’t be picked up. At the minute, the winners error is the first runtime issue the code is running into, and that causes an error that immediately crashes the program. Once you fix that you’ll get a series of other runtime errors. Most obvious:

  • lenght - this should be length, there is no method called lenght.
  • if (something = somethingelse) should be if(something === somethingelse), comparison not assignment.
1 Like

Hi, I did several tests, but none of them worked.
As you say, you can not solve the winner problem.
The syntax errors if I correct them, but until I spere the first one, it does not let me continue.
Thanks for the support, I’ll keep trying to fix the winner, but I do not know how.
Thank you

You can not fix the problem, just the syntax errors

No, I didn’t say you can’t solve it, you need to replace it with something that exists in JS. Tuples do not exist in JS, so you need to use an object or an array.

1 Like

And how can I solve the tuples? As I said, I received the code from a partner, and I’m taking my first steps in javascript.

Tuples do not exist in JS, you need to replace the code with an object or an array, I can’t really explain this more clearly. Do you understand what a tuple is? And an array, and an object?

1 Like

A matrix and an object is what it is. What never spoke today was tuple. I’ll see how I solve it. Thank you for the interest shown.
I will try to solve the problem.

@camperextraordinaire I corrected the errors that I commented @DanCouper, but it has more errors

As I assure @ DanCouper4h, it has problems of execution, the code is locked

let cards = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
let suits = ["diamonds", "hearts", "spades", "clubs"];
let deck = new Array();
let player = new Array();

function getDeck() {
	let deck = new Array();
	//cargar la baraja de cartas
	for (let i = 0; i < suits.length; i++) {
		for (let x = 0; x < cards.length; x++) {
			let card = { Value: cards[x], Suit: suits[i] };
			deck.push(card);
		}
	}

	return deck;
}

function deal() {
	// sacar la última carta de la baraja
	let card = deck[deck.length - 1];
	deck.splice(deck.length - 1, 1);
	return card;
}

function shuffle() {
	// cambiar dos cartas aleatorias de posición 1000 veces
	for (let i = 0; i < 1000; i++) {
		let location1 = Math.floor((Math.random() * deck.length));
		let location2 = Math.floor((Math.random() * deck.length));
		let tmp = deck[location1];

		deck[location1] = deck[location2];
		deck[location2] = tmp;
	}
}

function renderDeck(deck, number) {
	for (let i = 0; i < deck.length; i++) {
		let card = document.createElement("div");
		let value = document.createElement("div");
		let suit = document.createElement("div");
		card.className = "card";
		value.className = "value";
		suit.className = "suit " + deck[i].Suit;

		value.innerHTML = deck[i].Value;
		card.appendChild(value);
		card.appendChild(suit);

		document.getElementById("deck" + number).appendChild(card);
	}
}

function game(deck) {

	let cont = new Array();
	for (let i = 1; i < 10; i++) {

		cont[i] = 0;
	}
	let score = 0;

	let newDeck = "";

	while (cont[1] < 3 || cont[2] < 3 || cont[3] < 3 || cont[4] < 3 || cont[5] < 3 || cont[6] < 3 || cont[7] < 3 || cont[8] < 3 || cont[9] < 3 || cont[10] < 3) {
		newDeck[score] = deck.pop();

		if (newDeck[score].value) {
			cont[1]++;
		}

		else if (newDeck[score].value) {
			cont[2]++;
		}

		else if (newDeck[score].value) {
			cont[3]++;
		}

		else if (newDeck[score].value) {
			cont[4]++;
		}

		else if (newDeck[score].value) {
			cont[5]++;
		}

		else if (newDeck[score].value) {
			cont[6]++;
		}

		else if (newDeck[score].value) {
			cont[7]++;
		}

		else if (newDeck[score].value) {
			cont[8]++;
		}

		else if (newDeck[score].value) {
			cont[9]++;
		}

		else {
			cont[10]++;
		}

		score++;
	}

	return score, newDeck;
}

function players() {

	let number = prompt("¿Cuántas personas van a jugar?", "2");

	for (let i = 0; i < number; i++) {
		player[i] = prompt("¿Cómo se llama el jugador número " + i + "?");
	}
	localStorage.setItem('nickName', JSON.stringify(player));
	return player;
}


function myFunction() {
	players();

	for (let i = 0; i < player.length; i++) {
		let playerTitle = document.createElement("div");
		let playerName = document.createTextNode(player[i]);
		playerTitle.appendChild(playerName);
		playerTitle.classname = "playerTitle";

		document.getElementById("results").appendChild(playerTitle);

		let deckShow = document.createElement("div");
		deckShow.id = "deck" + i;
		document.getElementById("results").appendChild(deckShow);
	}

	for (let i = 0; i < player.length; i++) {

		deck[i] = getDeck();
		shuffle();

		game(deck[i]);
		console.log(game);
		renderDeck(newDeck, i);

		let finalScore = "";
		finalScore[i] = score;

		document.getElementById("playerTitle" + i).innerHTML = player[i] + " ha conseguido su objetivo en " + score + "turnos.";

		let winner = (player[i], score)

		localStorage.setItem('score', JSON.stringify(finalScore));



		console.log(players);
		console.log(deck);


	}
	let which = Math.min(...winner.score);
	for (let i = 0; i < player.length; i++) {
		if (which == winner[i].score) {

			document.getElementById("finalScore").innerHTML = "El ganador es " + winner[i].player;
		}
		else { }
	}

}

This isn’t JavaScript:

let winner = (player[i], score) 

So that needs to be either [player[i], score] or {player: player[i], score: score}.

You do this in another place:

return score, newDeck;

This is not JavaScript code. If it is Python, as I assume it is from the tuple comment and syntax, then, again this is Python tuples. You cannot do multiple returns in JS.

I think you are then trying to access the multiple return values - I was trying to figure out some of the logic, and it.makes more sense if I assume you’re trying to access stuff like you do in Python.

There’s more stuff here - there no reason to ever use new Array(), again that looks like Python idioms being translated.

It’s fine to translate Python code to JS, it just needs to be done with more care, it’s not quite 1-1 translatable.

1 Like

Thanks @DanCouper I picked it up thinking it was javascript and I’m starting, that’s why I’m struggling to understand what my partner was trying to do. Change the suggestions that you told me, and it does not stop, but stops the value, which gives it as undefined.
What suggests to me is that I do not keep trying to fix it …?
The truth is that I am being difficult, and of course when commenting on phyton I understand why.
Thanks anyway for the support.