I have a loop that creates cards until the dealer's score is exactly 17. But there is a problem, it creates either exactly 17 or more. I tried to solve it by reloading the page, but I don't think it's the best solution. There is a dealer variable that stores points. There are cards card A has a weight of 11, cards with the letters J, K, Q have a weight of 10, and cards on which a number is depicted have the same weight as the number itself. In the cycle, you need to collect cards until the dealer's points (dealer variable) becomes 17. And now I don't know how to stop the cycle when the points already exceed 17. Cards are selected randomly
let dealer = 0
let player = 0
let value = [2,3,4,5,6,7,8,9,10,'A','J','K','Q']
let type = ['ПИКИ','ТРЕФИ','ЧЕРВИ','БУБЕН']
let coloda = []
for (let index = 0; index < value.length; index ) {
for (let i2 = 0; i2 < type.length; i2 ) {
coloda.push(value[index] ' ' type[i2])
}
}
coloda.sort(()=> Math.random() - 0.5)
console.log(coloda)
function start(){
while(dealer < 17){
let random = Math.floor(Math.random()* coloda.length)
let addcard = document.createElement('div')
addcard.classList.add('card')
addcard.textContent = coloda[random]
document.querySelector('.dealer').appendChild(addcard)
sum(random)
}
if(dealer> 17){
//reload
document.querySelector('.dl').textContent = dealer
}else{
console.log('good')
document.querySelector('.dl').textContent = dealer
}
}
function sum(random){
let data = coloda[random].split('')[0]
if(data == 'A'){
dealer = dealer 11
}
else if(data == 'J' || data == 'K' || data =='Q'){
dealer = dealer 10
}else{
dealer = dealer Number(data)
}
}
start()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.card{
width: 100px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div >
<h1 ></h1>
</div>
<script src="script.js"></script>
</body>
</html>
I tried to solve it by reloading the page, but I don't think it's the best solution.
CodePudding user response:
One thing you could do is check the value of the dealer every X seconds and proceed if it is above 17 like this (X should be a small number to make it act like a while loop)
function check() {
if (dealer > 17) {
return true
} else {
return false
}
}
setInterval(function() {
let valid = check();
if (valid) {
// Insert code here
} else {
console.log('Dealer is not above 17')
}
}, X * 1000)
Hope this helps