Issue with check, bet, or fold function in Poker game( javascript ) - javascript

I am very new to Javascript, and have a question about one of my functions(checkOrBet). I am trying to make a Texas Hold'em poker game, and the part that doesn't seem to be working is where I test for a regular pair. It doesn't seem to recognize that a pair has been made, when the cards are dealt to the deck.
function game() {
function Playert(name, chips) {
this.name = name;
this.chips = chips;
this.firstCard = [];
this.secondCard = [];
this.blind = {};
// this.turnpos = 0; //1 for current turn
//will be computer's response when prompted during the flop
this.checkOrBet = function checkOrBet() {
var response;
//Ace High
if (this.firstCard.rank == "A") {
response = "call";
console.log("Ace High!");
} else if (this.secondCard.rank == "A") {
response = "call";
console.log("Ace High!");
}
//Tests for a pocket pair
if (this.firstCard.rank == this.secondCard.rank) {
response = "call";
console.log("Pocket pairs!");
}
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || communityCards.cards[1].rank || communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
}
}
function Pot(chipsp) {
this.chipsp = 0;
}
//clears text every time start button is pressed
function clearBox() {
document.getElementById("computer").innerHTML = "";
document.getElementById("flop").innerHTML = "";
document.getElementById("hand1").innerHTML = "";
}
clearBox();
//players start with chips, low blind, big blind.
var computer = new Playert("Computer", 200);
var player = new Playert("Player1", 200);
//Need a deck to deal the cards for the players.
var deck = new Stack();
//player's hand
var phand = new Stack();
//computer's hand
var chand = new Stack();
//game cards
var gamehand = new Stack();
//make pot
var pot1 = new Pot();
//community cards variable
var communityCards = new Stack();
deck.makeDeck(1);
deck.shuffle(1);
//deal 2 cards to player hand
if (phand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
phand.addCard(deck.deal());
}
}
//grab player div by the ID
playerhand = document.getElementById("hand1");
//create p element to show cards in player div
var pdoc = document.createElement("p");
//create text node to append to p element
var ptext = document.createTextNode(phand.cards);
//append text node to p element
pdoc.appendChild(ptext);
//append p element with cards to the hand1 div
playerhand.appendChild(pdoc);
//deal cards to computer's hand
if (chand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
chand.addCard(deck.deal());
}
}
//tie computer's hand to firstCard/secondCard
computer.firstCard = chand.cards[0];
computer.secondCard = chand.cards[1];
console.log(computer.firstCard.rank);
console.log(computer.secondCard.rank);
//grab computer div by id
d = document.getElementById("computer");
//create p element to show cards in computer div
var cdoc = document.createElement("p");
//create text node to append to p element
var ctext = document.createTextNode(chand.cards.toString());
//append text node to p element
cdoc.appendChild(ctext);
//append p element to computer div
d.appendChild(cdoc);
//grab game cards div
g = document.getElementById("flop");
//create p element for appending
var fdoc = document.createElement("p");
//create text node to append to paragraph element
//choose which player has the blind
function blinds() {
var small = 5;
var big = 10;
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
player.blind = small;
player.chips -= small;
computer.blind = big;
computer.chips -= big;
pot1.chipsp += 15;
} else if (random == 2) {
player.blind = big;
player.chips -= big;
computer.blind = small;
computer.chips -= small;
pot1.chipsp += 15;
}
}
blinds();
//Show chips for player
var chips = document.getElementById("hand1");
var chipsp = document.createElement("p");
var chipsn = document.createTextNode("You have " + player.chips +
" chips");
chipsp.appendChild(chipsn);
chips.appendChild(chipsp);
//Show chips for the computer
var cchips = document.getElementById("computer");
var pchips = document.createElement("p");
var chipsnc = document.createTextNode("You have " + computer.chips +
" chips");
pchips.appendChild(chipsnc);
cchips.appendChild(pchips);
//grab computer hand div for printing out chips
function grab(x) {
d = document.getElementById(x);
return d;
}
//grab computer div
var cblind = grab("computer");
//create p element
var cpblind = document.createElement("p");
//create text node
var ctblind = document.createTextNode("Computer's blind is" + " " +
computer.blind);
//append text to p
cpblind.appendChild(ctblind);
//append p to computer div
cblind.appendChild(cpblind);
//grab hand1 for showing player blind
var ghand1 = grab("hand1");
//create element
var ghand2 = document.createElement("p");
//create text node
var ghand3 = document.createTextNode("Player's blind is" + " " + player
.blind);
//append text to para
ghand2.appendChild(ghand3);
//append p to div
ghand1.appendChild(ghand2);
//if computer gets the blind of 5,call no matter what
if (computer.blind = 5) {
computer.chips -= 5;
}
//if player is low blind, prompt for call, fold, or bet
if (player.blind == 5) {
var cfb = prompt("Would you like to call, fold, or bet?");
switch (cfb) {
case "call":
//do something
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
chipsn.nodeValue = "You have " + player.chips + " chips";
player.turnpos = 1; //has acted
break;
case "fold":
//do something
computer.chips += pot1.chipsp;
break;
case "bet":
//do something
break;
default:
//do something
}
//start flop round
//draw 3 cards from the deck / switch statement for check,fold, bet?
//prompt computer and player on what they want to do
} else if (player.chips = 10) {
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
}
//print flop cards to flop div
var flopc = document.getElementById("flop");
var flopcr = document.createElement("p");
var floptn = document.createTextNode(communityCards.cards.toString());
flopcr.appendChild(floptn);
flopc.appendChild(flopcr);
//print pot to flop div
var potf = document.createElement("p");
var pottn = document.createTextNode("The pot is " + pot1.chipsp);
potf.appendChild(pottn);
flopc.appendChild(potf);
//if player has acted, prompt computer to check, bet or fold
// if (player.turnpos == 1) {
//computer evaluates hands
//}
//test function
computer.checkOrBet();
}

Go with this :
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || this.firstCard.rank == communityCards.cards[1].rank || this.firstCard.rank == communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
same for the second card.

Related

How to do a descending for-loop countdown that creates <p> element with given number on each iteration?

This might seem insanely basic. But I'm struggling with this simple creation of an for-loop since no p Element is created on any loop-iteration. I don't know how to display the newly created p Element in my div Element (.output).
It should create an p element to my div on each iteration, showing the current value of i. When it's 10, it should say something like "Countdown has started" and at the end "Countdown Ended!". Here is a small sample (rest of html omitted):
<div class="output"></div>
<script>
let output = document.querySelector(".output");
output.innerHTML = '';
countBegin= "Countdown has started";
countEnd = "Countdown has ended";
countBet = "Countdown at ";
function countD() {
for (let i = 10; i<= 0; i--) {
var para = document.createElement("p");
if (i === 10) {
para.textContent = countBegin + i;
} else if (i === 0) {
para.textContent = countEnd;
} else {
para.textContent = countBet + i;
}
output.appendChild(para);
}
}
countD();
</script>
</body>
I would expect to see at least one line as an output in the browser window but sadly there isn't any.
Since you're looping from 10 to 0, the loop condition should be i >= 0:
let output = document.querySelector(".output");
output.innerHTML = '';
countBegin = "Countdown has started";
countEnd = "Countdown has ended";
countBet = "Countdown at ";
function countD() {
for (let i = 10; i >= 0; i--) {
var para = document.createElement("p");
if (i === 10) {
para.textContent = countBegin;
} else if (i === 0) {
para.textContent = countEnd;
} else {
para.textContent = countBet + i;
}
output.appendChild(para);
}
}
countD();
<div class="output"></div>

simple matching game using javascript

I am making a simple game using javascript. The game essentially is matching the correct colour to the item of food. For example, there is 5 items of food on a picnic blanket and 5 colours written out. The player has to match the correct colour to the food. I feel i have all the correct code, but when i started styling it, everything disappeared and now i can't get it working again. SO i dont know where i have gone missing!
i have a jfiddle with all the code, but the images don't appear (i dont know how to add them on jfiddle) any help is much appreciated!
http://jsfiddle.net/febidrench/395hvqqu/ this is the jfiddle
this is the javascript
var colours = ["Red", "Pink", "Purple", "Yellow", "Orange", "Green"];
//this function shuffles our country array
function shuffleArray(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex ;
//while the array hasn't ended
while (0 !== currentIndex) {
//find a random element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = temporaryValue;
}
//returns the shuffled array
return arr;
}
//variables for the fuctionality of the game
var selectedFood;
var score;
var count;
var wordClicked;
var winningScore;
//the game init fuction will contain the difficulty level within it that will be passed when the function is called
function gameInit(difficulty) {
// calculates the number of correct
winningScore = Math.round(difficulty/3*2);
// the score variable
score = 0;
//count = the difficulty
count = difficulty;
// is the map clicked yes/no
wordClicked = false;
//gamecountries and gamemaps
var gameFoods = [];
var gameColours = [];
// shuffles the existing countries array
gameFoods = shuffleArray(colours)
//cuts the number of countries to the difficulty level
gameFoods = gameFoods.slice(0, difficulty);
//loops through the countries and displays the attached flags
for (i = 0; i<gameFoods.length; i++ )
{
document.getElementById('gameFoods').innerHTML += "<div class='picnicFoods' id='" + gameFoods[i] + "' onclick='foodClick(this.id)'><img src='food/" + gameFoods[i] + ".gif'></div>" ;
}
//reshuffles the countries
gameColours = shuffleArray(gameCountries)
//loops through the countries and displays the attached maps
for (j = 0; j<gameColours.length; j++ )
{
document.getElementById('gameColour').innerHTML += "<div class='picnicColours' id='map-" + gameColours[j] + "' onclick='colourClick(this.id)'><img src='colours/" + gameColours[j] + ".gif'></div>" ;
}
}
//when a flag is clicked
function foodClick(foodClickedId)
{
//set the mapclicked function is true to stop the function being activated again
colourClicked = true;
//sets the selectedFlag to the id of the clicked flag
selectedFood = foodClickedId;
// removes the flag after 5 seconds after the click
setTimeout(function(){
document.getElementById(foodClickedId).style.display = "none";
}, 5000);
}
//when a map is clicked
function colourClick(colourClickId)
{
//if a flag has been clicked
if (colourClicked == true){
// if there remains elements to match
if (count > 0){
//does the map and flag clicked match
if( "map-" + selectedFood == colourClickId)
{
//add one to the score
score = score + 1;
//remove 1 from the count
count = count - 1;
//show the popup and score
document.getElementById("popupBox").innerHTML =
"<div>Correct</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//if the game isn't over close the popup and let the player continue, this is tracked by the count
if (count != 0)
{
setTimeout(function(){
//hide the related map to the selected flag
document.getElementById("map-" + selectedFood).style.display = "none";
//allow the users to select the next flag in the game.
colourClicked = false;
document.getElementById("gamePopup").style.display = "none";
document.getElementById("popupBox").style.display = "none";
}, 5000);
}
else{
//if the game is over call the game over function
gameOver();
}
}
else {
//if the answer doesn't match do not increase score but still reduce count
score = score ;
count = count - 1;
//show that the player got it wrong and show their score
document.getElementById("popupBox").innerHTML =
"<div>Incorrect</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//if the game isn't over close the popup and let the player continue, this is tracked by the count
if (count != 0)
{
setTimeout(function(){
//remove the correct map so the user cannot select it in further questions but leave the incorrect one
document.getElementById("map-" + selectedFood).style.display = "none";
//allow the user to continue playing the game
colourClicked = false;
document.getElementById("gamePopup").style.display = "none";
document.getElementById("popupBox").style.display = "none";
}, 5000);
}
else{
//else show the game is over
gameOver();
}
}
}
}
}
//if the game has ended
function gameOver (){
//store the win or lose message
var gameMessage;
//if the score is less than the winning score the player loses
if (score < winningScore){
gameMessage = "You Lose"
}
//otherwise they win
else {gameMessage = "You Win"}
//show the game over popup with the score
document.getElementById("popupBox").innerHTML =
"<div>Game Over</div><div>" + gameMessage +
"</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//after 5 seconds redirect the user to the level select menu
setTimeout(function(){
window.location = "level.html";
}, 5000);
}

Why doesn't it work for rows 7-13

The program is a Seat reservation program rows 1 and 2 are first class, row 3-9 are business class and rows 10 through 13 are economy. They are initialized to * and become X when it is reserved. and alert you if the seat is already filled.
The rows will fill for the first 6 rows but it ignores request for row 7 and beyond. But i know it goes to the appropriate function because if i request Economy with row 3 (which is invalid) it alerts me. But if i ask for first class with row7 it will act like nothing has been requested.
It won't let me post the html code but it will display as row1-13 on the left and A - F across the top. I use drop down list and I set the values to the corresponding for the options to their corresponding spot in a the 2-d array (eg if i select row 5 and seat c the value of row 5 is 5 and the value of C is 3)
var rowSeat;
function start()
{
rowSeat = new Array(14);
for(var i = 0; i <rowSeat.length; i++)
{
rowSeat[i] = new Array(7);
}
var j = 65;
for(var i = 1; i <rowSeat[0].length; i++)
{
rowSeat[0][i] = String.fromCharCode(j);
j++;
}
rowSeat[0][0] = " ";
for(var i = 1; i <rowSeat.length; i++)
{
rowSeat[i][0] = "Row "+i;
}
for(var i = 1; i <rowSeat.length; i++)
{
for(var j = 1; j <rowSeat[i].length; j++)
{
rowSeat[i][j] = "*";
}
}
display();
var subButton = document.getElementById("submitButton");
subButton.addEventListener("click", assign, false);
}
function display()
{
var results = "";
results+="<table>"
for(var i in rowSeat)
{
results+="<tr>";
for(var j in rowSeat[i])
{
results += "<td>" +rowSeat[i][j]+ "</td>";
}
results += "</tr>";
}
results+="</table>"
var show2 = document.getElementById( "show2" );
show2.innerHTML = results;
}
function assign()
{
var inputField = document.getElementById("classAssign");
var classType = inputField.options[inputField.selectedIndex].value;
if (classType == "FirstClass")
{
fClassSearch();
}
else if (classType == "Business")
{
bClassSearch();
}
else
{
eClassSearch();
}
display();
}
function fClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var test = document.getElementById( "test" );
test.innerHTML = row +" "+ seat;
if (row >2){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 1 and 2 are First Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function bClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
if (row <3 ||row >9){
var show2 = document.getElementById( "show" );
show.innerHTML = "Invalid choice only row 3 through 9 are BusinessClass";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
function eClassSearch(){
var inputField = document.getElementById("seatAssign");
var seat = inputField.options[inputField.selectedIndex].value;
var inputField2 = document.getElementById("rowAssign");
var row = inputField.options[inputField2.selectedIndex].value;
var show1 = document.getElementById( "show" );
if (row <10){
show1.innerHTML = "Invalid choice only rows 10 through 13 are Economy Class";
}
else {
if(rowSeat[row][seat] == "*")
{
rowSeat[row][seat] = "X";
show.innerHTML = "Your Seat choice was accepted and Reserved";
}
else{
show.innerHTML = "Your choice was already reserved please make another choice";
}
}
}
window.addEventListener("load",start, false);
</script>
var row = inputField.options[inputField2.selectedIndex].value;
inputField.options should be inputField2.options
inputField.options only goes to 6 because you only have 6 seats wide, but you are trying to look at the row in the seat list.

change numbers from dynamic elements

I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element...
var button = $('#add');
button.click(function()
{
var filmnamn = $('#name');
var filmnamnet = filmnamn.val();
var betyg = $('#star');
var betyget = betyg.val();
betyget = Number(betyget);
if(filmnamnet == 0)
{
$('#name').css('background-color', 'red');
}
if(betyget == 0)
{
$('#star').css('background-color', 'red');
}
if(betyget == 0 || filmnamnet == 0)
{
alert("Vänligen fyll i fälten korrekt");
}
else
{
var array = new Array();
array.unshift(betyget);
array.unshift(filmnamnet);
film_array.unshift(array);
betyg_array.unshift(array);
updateFilmList();
}
});
var film_list = $("#filmlista");
var film_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var filmen = film_array[0][0];
var grade = film_array[0][1];
var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>';
film_list.append(element);
changeNumber();
}
And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem?
function changeNumber(){
var elements= document.getElementsByClassName("betyg");
for (var i=0; i<elements.length; i++) {
var element = elements[i];
var length = parseInt(element.innerHTML);
var x=Array(length+1).join("*");
element.innerHTML=x;
}
}

Javascript to create multiple div elements onclick

I need help with this app. I want the user to choose a name, color and number. When the form is submitted, boxes of the chosen color and number are generated. More boxes can be added and the originals are not erased. Each box has random positioning and a unique id.
Here is my effort: http://jsfiddle.net/christopherpl/gnVj6/
//Invoke functions only after page has fully loaded
window.onload = init;
//Create an array that will be populated by the user generated boxes
var boxes = [];
//Create a global counter variable that keeps track of the number of
//boxes generated
var counter = 0;
//Create a Box constructor function with parameters, to create box objects
//for each box that's generated
function Box(id, name, color, x, y) {
this.id = id;
this.name = name;
this.color = color;
this.x = x;
this.y = y;
}
//Set up the onclick event handler for the generate button input
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = generate;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
//Get boxes' name from user
function generate() {
var data = document.forms.data;
var textInput = document.getElementById("name");
var name = textInput.value;
if (name == null || name == "") {
alert("Please give your Amazing Box a name");
return;
}
//Get color option from user
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (!color) {
alert("Pick a color");
return;
}
//Get number of boxes to be generated from user
var amountArray = data.elements.amount;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
//Create and append the new <div> element
var div = document.createElement("div");
//Randomly position each <div> element
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
//Give each <div> element a unique id
var newId = div;
newId = counter++;
id = newId;
//Add the style, including the background color selected
//by the user.
div.style.left = x + "px";
div.style.top = y + "px";
div.style.backgroundColor = color;
div.setAttribute("class", "box");
scene.appendChild(div);
div.innerHTML = "Box of " + name + "<br />(click me)";
//Create an onclick event displaying the
//details of each box generated
div.onclick = function() {
alert("You clicked on a box with id " + id +
", named Box of " + name + ", whose color is " + color +
" at position " + div.style.top + ", " + div.style.left)
}
//Form reset
data = document.getElementById("data");
data.reset();
}
}
}
//Clear the boxes from scene div
function clear() {
var sceneDivs = document.querySelectorAll("div#scene div");
for (var i = 0; i < sceneDivs.length; i++) {
var scene = document.getElementById("scene");
var cutList = document.getElementsByTagName("div")[1];
scene.removeChild(cutList);
}
}
In your code, when you do this loop:
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
/* make the div */
}
}
You are always just making one box. What you need to do is a second loop, using the value of the radio button as the length of the loop. Something like:
var totalBoxes = 0;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
totalBoxes = amountArray[i].value;
}
}
for (i = 0; i < totalBoxes; i++) {
/* make the div */
}
That way you will get 5 boxes if the user checked the 5 box, and so on.

Categories