我正在用 HTML、CSS 和 JavaScript 制作二十一点游戏,这就是我目前所拥有的,它应该做的是让玩家和计算机初始手并将其打印到屏幕上。但是手的价值总是返回为 0,我不知道为什么......任何帮助将不胜感激,这是一个小提琴:http: //jsfiddle.net/KR9jJ/
//当窗口加载时,将画布垂直和水平定位到屏幕中心
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * 0.8;
var canvasHeight = canvasWidth / 2;
canvas.style.position = "absolute";
canvas.setAttribute("width", canvasWidth);
canvas.setAttribute("height", canvasHeight);
canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
};
//随机数生成器1-13的函数
function random() {
var number = (Math.random()*13)+1;
return number;
}
function rank() {
var randomCard = random();
var output = "randomCard";
switch (randomCard) {
case 1:
output = "Ace";
break;
case 2:
output = "Two";
break;
case 3:
output = "Three";
break;
case 4:
output = "Four";
break;
case 5:
output = "Five";
break;
case 6:
output = "Six";
break;
case 7:
output = "Seven";
break;
case 8:
output = "Eight";
break;
case 9:
output = "Nine";
break;
case 10:
output = "Ten";
break;
case 11:
output = "Jack";
break;
case 12:
output = "Queen";
break;
case 13:
output = "King";
break;
}
return output;
}
//根据随机结果返回卡片值的函数
function value(randomCard) {
var output = 0;
if (randomCard === ("Ace")) {
output = 11;
}
if (randomCard === ("Two")) {
output = 2;
}
if (randomCard === ("Three")) {
output = 3;
}
if (randomCard === ("Four")) {
output = 4;
}
if (randomCard === ("Five")) {
output = 5;
}
if (randomCard === ("Six")) {
output = 6;
}
if (randomCard === ("Seven")) {
output = 7;
}
if (randomCard === ("Eight")) {
output = 8;
}
if (randomCard === ("Nine")) {
output = 9;
}
if (randomCard === ("Ten")) {
output = 10;
}
if (randomCard === ("Jack")) {
output = 10;
}
if (randomCard === ("Queen")) {
output = 10;
}
if (randomCard === ("King")) {
output = 10;
}
return output;
}
//指定玩家和电脑默认手
var playerHand = 0;
var compHand = 0;
//为电脑和玩家发初始手牌
var playerFirstCard = rank();
var playerCardOne = value(playerFirstCard);
var compFirstCard = rank();
var compCardOne = value(compFirstCard);
var playerSecondCard = rank();
var playerCardTwo = value(playerSecondCard);
playerHand = playerHand + (playerCardOne+playerCardTwo);
var compSecondCard = rank();
var compCardTwo = value(compSecondCard);
compHand = compHand + (compCardOne+compCardTwo);
//显示球员和比赛的手
document.getElementById('p').innerHTML = playerHand;
document.getElementById('c').innerHTML = compHand;
请注意:请不要 jQuery 建议。