Java 21 点游戏:在线体验牌桌对决
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner;
public class BlackjackGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random();
System.out.println('游戏开始');
// 初始化牌堆
List<Integer> deck = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
for (int j = 0; j < 4; j++) {
deck.add(i);
}
}
// 发牌
int userTotal = 0;
int computerTotal = 0;
System.out.println('用户玩家发牌:' + dealCard(deck));
userTotal += dealCard(deck);
System.out.println('用户玩家点数:' + userTotal);
while (true) {
System.out.println('是否要牌:1要牌,2不要牌');
int choice = scanner.nextInt();
if (choice == 1) {
int card = dealCard(deck);
System.out.println('用户玩家发牌:' + card);
userTotal += card;
System.out.println('用户玩家点数:' + userTotal);
if (userTotal > 21) {
System.out.println('用户玩家爆了');
System.out.println('电脑玩家点数:' + computerTotal);
System.out.println('电脑玩家胜');
return;
}
} else if (choice == 2) {
System.out.println('用户玩家点数:' + userTotal);
break;
} else {
System.out.println('无效的输入,请重新输入');
}
}
// 电脑玩家要牌
System.out.println('电脑玩家发牌:' + dealCard(deck));
computerTotal += dealCard(deck);
System.out.println('电脑玩家点数:' + computerTotal);
while (computerTotal < 17) {
System.out.println('要牌');
int card = dealCard(deck);
System.out.println('电脑玩家发牌:' + card);
computerTotal += card;
System.out.println('电脑玩家点数:' + computerTotal);
}
if (computerTotal > 21) {
System.out.println('电脑玩家爆了');
System.out.println('用户玩家胜');
} else if (computerTotal > userTotal) {
System.out.println('电脑玩家胜');
} else if (computerTotal < userTotal) {
System.out.println('用户玩家胜');
} else {
System.out.println('平局');
}
}
private static int dealCard(List<Integer> deck) {
int index = random.nextInt(deck.size());
int card = deck.get(index);
deck.remove(index);
return card;
}
}
原文地址: https://www.cveoy.top/t/topic/kfFn 著作权归作者所有。请勿转载和采集!