JS tool problem(play yourself) - reduced black jack
JS tool problem 2 about Markov decision process.
by Tinytsunami
HTML
<div id="demo">
<pre></pre>
<button>Draw</button>
<button>Pass</button>
</div>
CSS
body {
color: #ffffff;
background: #20262e;
font-family: monospace, sans-serif;
}
#demo input {
width: 120px;
color: #ffffff;
background: #20262e;
border: none;
border-bottom: solid 1px #ffffff;
outline: none;
}
#demo input {
margin-right: 5px;
}
#demo button {
cursor: pointer;
color: #ffffff;
background: #20262e;
border: 1px solid #ffffff;
outline: none;
}
#demo button:hover {
color: #20262e;
background: #ffffff;
}
JavaScript
(function() {
/* HTML DOM */
let demo = document.getElementById("demo");
let message = demo.getElementsByTagName("pre")[0];
let draw = demo.getElementsByTagName("button")[0];
let pass = demo.getElementsByTagName("button")[1];
/* constants */
let ACTOR = {
PLAYER: 0,
COMPUTER: 1
};
let turn = ACTOR.PLAYER;
/* variables */
let player_card = [];
let computer_card = [];
let player_pass = false;
let game_endding = false;
/* card sum */
let sum = function(cards) {
return cards.length > 0 ? cards.reduce((p, c) => p + c) : 0;
};
/* game initialize */
let initialize = function() {
player_card = [];
computer_card = [];
player_pass = false;
game_endding = false;
};
/* check winner */
let check = function(a, b) {
if (a > 10 && b > 10) {
return 2;
} else if (a > 10 && b <= 10) {
return ACTOR.COMPUTER;
} else if (a <= 10 && b > 10) {
return ACTOR.PLAYER;
} else {
if (player_pass) {
if (a < b) {
return ACTOR.COMPUTER;
} else if (a > b) {
return ACTOR.PLAYER;
} else if (a == b) {
return 2;
}
}
}
return -1; //not endding
};
/* game main-loop */
let next_turn = function() {
let a = sum(player_card);
let b = sum(computer_card);
message.innerHTML = `玩家的牌面是:`;
player_card.forEach((card, index) => {
message.innerHTML += `${card}${index != player_card.length - 1 ? "," : ""}`;
});
message.innerHTML += ` (${a})`;
message.innerHTML += `\n電腦的牌面是:`;
computer_card.forEach((card, index) => {
message.innerHTML += `${card}${index != computer_card.length - 1 ? "," : ""}`;
});
message.innerHTML += ` (${b})`;
let winner = check(a, b);
switch (winner) {
case ACTOR.PLAYER:
message.innerHTML += `\n玩家贏了,按 Draw 重新開始`;
break;
case ACTOR.COMPUTER:
message.innerHTML += `\n電腦贏了,按 Draw 重新開始`;
break;
...