Problems writing script for blackjack game - javascript

I'm trying to write a script for a Black Jack game but have run into some problems. This is the code I've included in the head:
<script type="text/javascript">
var J = 10;
var Q = 10;
var K = 10;
var A = 11;
var deck = [1,2,3,4,5,6,7,8,9,10,J,Q,K,A];
function deal() {
var test = "hello";
var f_card = Math.floor(Math.random() * deck.length);
var s_card = Math.floor(Math.random() * deck.length);
var card1 = deck[f_card];
var card2 = deck[s_card];
if (card1 == J) {
card1 = "Jack";
}
else if (card1 == Q) {
card1 = "Queen";
}
else if (card1 == K) {
card1 = "King"
}
else if (card1 == A) {
card1 = "Ace"
}
if (card2 == J) {
card2 = "Jack";
}
else if (card2 == Q) {
card2 = "Queen";
}
else if (card2 == K) {
card2 = "King"
}
else if (card2 == A) {
card2 = "Ace"
}
var bucket = card1 + ", " + card2;
var res = f_card + s_card
document.getElementById("result").innerHTML = bucket;
document.getElementById("test").innerHTML = f_card + ", " + s_card;
if (res == 22) {
alert("Blackjack!")
}
}
</script>
The body reads as follows:
<body>
<form>
<input type="button" value ="Deal" onclick="deal()" /><br /><br />
</form>
<div id = "result">
</div><br />
<div id = "test">
</div>
</body>
I added the "test" div to see what was happening inside the deal, and it looks like "Jack" is being assigned to all array value above 9. How can I have the other if statements processed as well? Any help at all would be much appreciated.

Put your J,Q,K,A in quotes:
var deck = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A'];
if (card1 == 'J') {
card1 = "Jack";
}
etc..

if (card1 == J) {
card1 = "Jack";
}
else if (card1 == Q) {
card1 = "Queen";
}
else if (card1 == K) {
card1 = "King"
}
Lets say you have a card == 10 (Jack / Queen / King)
You test with ifs.
the first if is hit because 10 == J
Even if it is a Queen / King (which also == 10)
Because the Jack is hit in the if statement the other ifs dont get run

Instead of card1 and card2 in if else ladder use "original card ID", ie
switch (f_card){
case 10: card1 = "Jack";
break;
case 11: card1 = "Queen";
break;
case 12: card1 = "King";
break;
case 13: card1 = "Ace";
break;
}

Related

Farm Clicker game - Gold's value is increasing more than necessary

I'm trying to make a Farm Clicker game myself with Javascript. (In other words, as you click the Add Gold button, the user earns 1 gold and can obtain passive gold by buying some animals according to the number of gold he has.) But there is a problem with the program: If I save 50 gold and buy a goat, the gold suddenly increases more than necessary. The problem is most likely in the section that says setInterval, but I still couldn't find the exact solution.
HTML
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
JS
// global variables
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else
{
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
goldToAdd=0;
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
}
So here the problem is in the passiveGold Function.It runs in to a infinite loop because after you are buying an animal the animal count is obviously greater than 0.So the if condition will be evaluated to true always inside the passiveGold function and as a result of that it runs into a infinite loop.
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
So here i just did a small modification by adding return statements into every if condition code blocks.So that after executing once it will return to the main function.
// global variables
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else
{
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
goldToAdd=0;
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
}
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
Hope I solved your problem.And if you need anything to be clarified let me know.
There are two main issues with the gold incrementation here. There's a brace out of place leading to (I think) the setInterval be created several times (each time checkGold is called, in fact). Secondly, the goldToAdd amount is not zero at the start of passiveGold. I've also edited addGold so that two gold counters don't turn up when you hit 0 gold. Snippet below:
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
if(document.getElementById("goldCounter") == null) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
myContent.appendChild(goldCounter);
}
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
checkGold();
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
goldToAdd = 0;
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
<div id="content"></div>
I've refactored your code and broke it down and remade it. i've made the logic simpler and more like an actual game loop demo
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
</body>
// global state
let game_state = {
gold: 50,
animals: {
goats: 0,
pigs: 0,
cows: 0
},
}
// global variables
const content = document.getElementById("content");
let passiveGoldInterval = null;
// helper functions
function addGold(value){
game_state.gold += value;
updateUI();
}
function buyAnimal(animal){
switch(animal){
case 'goat':
if(game_state.gold >= 50){
addGold(-50);
game_state.animals.goats++;
}
break;
case 'pig':
if(game_state.gold >= 90){
addGold(-90);
game_state.animals.pigs++;
}
break;
case 'cow':
if(game_state.gold >= 120){
addGold(-120);
game_state.animals.cows++;
}
break;
default: // do nothing
}
updateUI();
}
// background function
function passiveGold(){
addGold(game_state.animals.goats * 5); // add gold for goats
addGold(game_state.animals.pigs * 10); // add gold for pigs
addGold(game_state.animals.cows * 15); // add gold for cows
}
// game state management (init)
function init(){
passiveGoldInterval = setInterval(passiveGold, 10000); // calss this function every 10 seconds
updateUI();
}
function updateUI(){
if (!(document.getElementById("addButton"))) {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
content.appendChild(myButton);
}
if (!(document.getElementById("goldCounter"))) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + game_state.gold;
content.appendChild(goldCounter);
} else
{
document.getElementById("goldCounter").innerHTML = "Gold: " + game_state.gold;
}
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
content.appendChild(itemBar);
}
// animals (display counts)
if (game_state.animals.goats >= 1 && !(document.getElementById("goats"))) {
let myElement1 = document.createElement("div");
myElement1.id = "goats";
myElement1.innerHTML = "Goat Quantity: " + game_state.animals.goats;
document.getElementById('itemBar').appendChild(myElement1);
} else if(document.getElementById("goats")) {
document.getElementById("goats").innerHTML = "Goat Quantity: " + game_state.animals.goats;
}
if (game_state.animals.pigs >= 1 && !(document.getElementById("pigs"))) {
let myElement2 = document.createElement("div");
myElement2.id = "pigs";
myElement2.innerHTML = "Pig Quantity: " + game_state.animals.pigs;
document.getElementById('itemBar').appendChild(myElement2);
} else if(document.getElementById("pigs")) {
document.getElementById("pigs").innerHTML = "Pig Quantity: " + game_state.animals.pigs;
}
if (game_state.animals.cows >= 1 && !(document.getElementById("cows"))) {
let myElement3 = document.createElement("div");
myElement3.id = "cows";
myElement3.innerHTML = "Cow Quantity: " + game_state.animals.cows;
document.getElementById('itemBar').appendChild(myElement3);
} else if(document.getElementById("cows")) {
document.getElementById("cows").innerHTML = "Cow Quantity: " + game_state.animals.cows;
}
// display buttons if match
// button container
if(!(document.getElementById("buttonBar"))){
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
content.appendChild(buttonBar);
}
// goats buy
if(game_state.gold >= 50){
if(!(document.getElementById("goatBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("goatBuyButton")){
document.getElementById("goatBuyButton").remove();
}
}
// pigs buy
if(game_state.gold >= 90){
if(!(document.getElementById("pigBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("pigBuyButton")){
document.getElementById("pigBuyButton").remove();
}
}
// cows buy
if(game_state.gold >= 120){
if(!(document.getElementById("cowBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("cowBuyButton")){
document.getElementById("cowBuyButton").remove();
}
}
}
init();

Converting text to small number javascript

I am trying to make a real time chat system. I am sending messages and saving them to the database. But before saving the message into database i need to encrypt it with using NTRU for Integers algorithm. In order to use this algorithm i have to convert text into numbers. I already tried to convert to ASCII code but its creating too big number for algorithm. Is there any way to convert text into small numbers? Saving into database with parent.send_message(chat_input.value)
create_chat(){
var parent = this;
var title_container = document.getElementById('title_container')
var title = document.getElementById('title')
title_container.classList.add('chat_title_container')
title.classList.add('chat_title')
var chat_container = document.createElement('div')
chat_container.setAttribute('id', 'chat_container')
var chat_inner_container = document.createElement('div')
chat_inner_container.setAttribute('id', 'chat_inner_container')
var chat_content_container = document.createElement('div')
chat_content_container.setAttribute('id', 'chat_content_container')
var chat_input_container = document.createElement('div')
chat_input_container.setAttribute('id', 'chat_input_container')
var chat_input_send = document.createElement('button')
chat_input_send.setAttribute('id', 'chat_input_send')
chat_input_send.setAttribute('disabled', true)
chat_input_send.innerHTML = `<i class="far fa-paper-plane"></i>`
var chat_input = document.createElement('input')
chat_input.setAttribute('id', 'chat_input')
chat_input.setAttribute('maxlength', 11)
chat_input.placeholder = `${parent.get_name()}. Say hello..`
chat_input.onkeyup = function(){
if(chat_input.value.length > 0){
chat_input_send.removeAttribute('disabled')
chat_input_send.classList.add('enabled')
chat_input_send.onclick = function(){
chat_input_send.setAttribute('disabled', true)
chat_input_send.classList.remove('enabled')
if(chat_input.value.length <= 0){
return
}
parent.create_load('chat_content_container')
chat_input.value = chat_input.value.toLocaleUpperCase()
parent.send_message(chat_input.value)
chat_input.value = ''
chat_input.focus()
}
I was able to solve my problem with this code
// Vocabulary
let vocabulary = new Array();{
vocabulary[10] = "A";
vocabulary[11] = "B";
vocabulary[12] = "C";
vocabulary[13] = "D";
vocabulary[14] = "E";
vocabulary[15] = "F";
vocabulary[16] = "G";
vocabulary[17] = "H";
vocabulary[18] = "I";
vocabulary[19] = "J";
vocabulary[20] = "K";
vocabulary[21] = "L";
vocabulary[22] = "M";
vocabulary[23] = "N";
vocabulary[24] = "O";
vocabulary[25] = "P";
vocabulary[26] = "Q";
vocabulary[27] = "R";
vocabulary[28] = "S";
vocabulary[29] = "T";
vocabulary[30] = "U";
vocabulary[31] = "V";
vocabulary[32] = "W";
vocabulary[33] = "X";
vocabulary[34] = "Y";
vocabulary[35] = "Z";
vocabulary[36] = " ";
vocabulary[37] = "a";
vocabulary[38] = "b";
vocabulary[39] = "c";
vocabulary[40] = "d";
vocabulary[41] = "e";
vocabulary[42] = "f";
vocabulary[43] = "g";
vocabulary[44] = "h";
vocabulary[45] = "i";
vocabulary[46] = "j";
vocabulary[47] = "k";
vocabulary[48] = "l";
vocabulary[49] = "m";
vocabulary[50] = "n";
vocabulary[51] = "o";
vocabulary[52] = "p";
vocabulary[53] = "q";
vocabulary[54] = "r";
vocabulary[55] = "s";
vocabulary[56] = "t";
vocabulary[57] = "u";
vocabulary[58] = "v";
vocabulary[59] = "w";
vocabulary[60] = "x";
vocabulary[61] = "y";
vocabulary[62] = "z";
vocabulary[63] = "!";
}
// Converting Text into numbers
var number = "";
for(var z = 0 ; z < chat_input.value.length ; z++)
{
for(var i = 10 ; i < 64 ; i++) {
if(chat_input.value.charAt(z) == vocabulary[i]) {
var test = i;
test = test.toString();
number = number + test;
}
}
}
// Seperating numbers into array
var numbers = new Array() ;
var index = 0 ;
while(number.length !== 0) {
if (number.length == 3) {
numbers[index] = number.substring(0, 3);
number = number.substring(3,number.length);
} else if (number.length == 2) {
numbers[index] = number.substring(0, 2);
number = number.substring(2,number.length);
} else if (number.length == 1) {
numbers[index] = number.substring(0, 1);
number = number.substring(1,number.length);
} else
numbers[index] = number.substring(0, 4);
number = number.substring(4,number.length);
index++;
}
//Encrpyting numbers and getting cipher text
var indexofe = 0 ;
var ciphertextz = new Array();
while(indexofe !== numbers.length) {
ciphertextz[indexofe] = parent.Encrypt(numbers[indexofe]);
indexofe++;
}

I need a button NOT to disapear

I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.write("\u2663");
}
if (slot1 == 1) {
document.write("\u2665");
}
if (slot1 == 2) {
document.write("\u2666");
}
if (slot1 == 3) {
document.write("\u2660");
}
if (slot1 == 4) {
document.write("7");
}
}
</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
When you write document.write() the screen refreshes, so I guess you could do something like this:
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
if (slot1 == 4) {
document.getElementById('value').innerHTML = "7";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Slightly optimized version of otrebla's code, see it in action:
function slots() {
var slot1 = Math.floor(Math.random() * 5);
var value = document.getElementById('value');
switch (slot1) {
case 0:
value.innerHTML = "\u2663";
break;
case 1:
value.innerHTML = "\u2665";
break;
case 2:
value.innerHTML = "\u2666";
break;
case 3:
value.innerHTML = "\u2660";
break;
case 4:
value.innerHTML = "7";
break;
}
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Why doesn't my external JavaScript file work when I load my html page?

I separated my html and JavaScript code. I placed my JavaScript code into a separate file and use 'script' tags to reference it in my html file. I have two functions within my JavaScript code one is used to create an autofill which means if I start typing text within a text box the function gives me a possible name that I may be wanting to write underneath the text box and the other creates a clock that gives the current time. Here are my JavaScript and html files respectively. Can you tell me what the problem is?
function Complete(obj, evt) {
var names = new Array("albert","alessandro","chris");
names.sort();
if ((!obj) || (!evt) || (names.length == 0)) {
return;
}
if (obj.value.length == 0) {
return;
}
var elm = (obj.setSelectionRange) ? evt.which : evt.keyCode;
if ((elm < 32) || (elm >= 33 && elm <= 46) || (elm >= 112 && elm <= 123)) {
return;
}
var txt = obj.value.replace(/;/gi, ",");
elm = txt.split(",");
txt = elm.pop();
txt = txt.replace(/^\s*/, "");
if (txt.length == 0) {
return;
}
if (obj.createTextRange) {
var rng = document.selection.createRange();
if (rng.parentElement() == obj) {
elm = rng.text;
var ini = obj.value.lastIndexOf(elm);
}
} else if (obj.setSelectionRange) {
var ini = obj.selectionStart;
}
for (var i = 0; i < names.length; i++) {
elm = names[i].toString();
if (elm.toLowerCase().indexOf(txt.toLowerCase()) == 0) {
obj.value += elm.substring(txt.length, elm.length);
break;
}
}
if (obj.createTextRange) {
rng = obj.createTextRange();
rng.moveStart("character", ini);
rng.moveEnd("character", obj.value.length);
rng.select();
} else if (obj.setSelectionRange) {
obj.setSelectionRange(ini, obj.value.length);
}
}
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
switch(intHours){
case 0:
intHours = 12;
hours = intHours+":";
ap = "A.M.";
break;
case 12:
hours = intHours+":";
ap = "P.M.";
break;
case 24:
intHours = 12;
hours = intHours + ":";
ap = "A.M.";
break;
default:
if (intHours > 12) {
intHours = intHours - 12;
hours = intHours + ":";
ap = "P.M.";
break;
}
if(intHours < 12) {
hours = intHours + ":";
ap = "A.M.";
}
}
if (intMinutes < 10) {
minutes = "0"+intMinutes+":";
} else {
minutes = intMinutes+":";
}
if (intSeconds < 10) {
seconds = "0"+intSeconds+" ";
} else {
seconds = intSeconds+" ";
}
timeString = hours+minutes+seconds+ap;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 100);
}
window.onload = tick;
<HTML>
<HEAD>
<H1 STYLE="text-align:center;" STYLE="font-family:verdana;">FDM Markets</H1>
<H2 STYLE="text-align:center;">Trading Platofrm</H2></br>
<STYLE type="text/css">
#p1 span {
width: 65px;
display: block;
float: left;
}
</STYLE>
<BODY>
<SCRIPT type="text/javascript" src="jscodeloginpage.js"></SCRIPT>
<p1>Login</p1></br>
</br>
<FORM name="anyForm">
Username: <input type="text" name="anyName" size="15" onKeyUp="Complete(this, event)"></br>
Password: <input type="text" size="15" name="password_box">
</FORM>
<div id=Clock style=font-size: 12"> </div>
</BODY>
</HTML>
Okay, I put your code into a jsbin. Most issues were found with help of it's code debugger / error console.
You had a few variables that were out of scope, meaning:
if(x){
var a = 1;
}
if(y){
doSomethingWith(a);
/*
* JavaScript can't access `a` here, since it was declared in the scope of the
* previous `if`. That instance of `a` only exists within that first `if`.
*/
}
You had a misplaced break in your switch/case's default section, and some other minor issues.
See the jsbin I linked to for a working example. I also made some modifications to your HTML. This line:
<div id=Clock style=font-size: 12"> </div>
Was missing a few "'s:
<div id="Clock" style="font-size: 12"> </div>
Also, </br> isn't a valid tag, you were probably looking for <br />
Here's your edited JS:
function Complete(obj, evt) {
var names = new Array("albert","alessandro","chris");
names.sort();
var elm = (obj.setSelectionRange) ? evt.which : evt.keyCode;
if (!obj ||
!evt ||
names.length === 0 ||
obj.value.length === 0 ||
elm < 32 ||
(elm >= 33 && elm <= 46) ||
(elm >= 112 && elm <= 123)) {
return;
}
var txt = obj.value.replace(/;/gi, ",");
elm = txt.split(",");
txt = elm.pop();
txt = txt.replace(/^\s*/, "");
if (txt.length === 0) {
return;
}
var ini, rng;
if (obj.createTextRange) {
rng = document.selection.createRange();
if (rng.parentElement() == obj) {
elm = rng.text;
ini = obj.value.lastIndexOf(elm);
}
} else if (obj.setSelectionRange) {
ini = obj.selectionStart;
}
for (var i = 0; i < names.length; i++) {
elm = names[i].toString();
if (elm.toLowerCase().indexOf(txt.toLowerCase()) === 0) {
obj.value += elm.substring(txt.length, elm.length);
break;
}
}
if (obj.createTextRange) {
rng = obj.createTextRange();
rng.moveStart("character", ini);
rng.moveEnd("character", obj.value.length);
rng.select();
} else if (obj.setSelectionRange) {
obj.setSelectionRange(ini, obj.value.length);
}
}
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
switch(intHours){
case 0:
intHours = 12;
hours = intHours+":";
ap = "A.M.";
break;
case 12:
hours = intHours+":";
ap = "P.M.";
break;
case 24:
intHours = 12;
hours = intHours + ":";
ap = "A.M.";
break;
default:
if (intHours > 12) {
intHours = intHours - 12;
hours = intHours + ":";
ap = "P.M.";
}
if(intHours < 12) {
hours = intHours + ":";
ap = "A.M.";
}
break;
}
if (intMinutes < 10) {
minutes = "0"+intMinutes+":";
} else {
minutes = intMinutes+":";
}
if (intSeconds < 10) {
seconds = "0"+intSeconds+" ";
} else {
seconds = intSeconds+" ";
}
timeString = hours+minutes+seconds+ap;
Clock.innerHTML = timeString;
window.setTimeout(tick, 100);
}
window.onload = tick;

Categories

Resources