java - 建造纸牌游戏需要相同的牌来匹配价值
问题描述
我正在为一项任务构建一个战争纸牌游戏,我已经构建了游戏并且它正在工作,但我遇到了这样的问题,例如卡片 10 黑桃 J 的价值低于卡片 23 红心 J。寻找有关能够比较卡片以查看它们是否相等的最佳方法的建议。
以下是我到目前为止的代码:
import java.util.Random;
import java.util.Scanner;
public class WarGame {
public static void main(String a[]) {
DeckOfCards d = new DeckOfCards();
int input = 0;
int computer = 0;
int you = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
while (input != 2) {
if (input == 1) {
System.out.print("\n\nEnter the value of the card:");
int card = sc.nextInt();
if (card >= 0 && card <= 51) {
int systemCard = d.computerTurn(card);
System.out.println("Your card - " + d.inputCard(card));
System.out.println("Computer card - " + d.inputCard(systemCard));
if(systemCard > card)
++computer;
else
++you;
System.out.println("The winner is " + (systemCard > card ? "Computer" : "You"));
} else {
System.out.println("Invalid card");
}
}
else {
System.out.println("That is an invalid selection please choose 1 or 2.");
}
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
}
System.out.println("Total Wins by Computer: "+ computer);
System.out.println("Total Wins by You: "+ you);
if (computer > you)
System.out.println("Computer is the champion");
else if (computer == you)
System.out.println("Its a Tie");
else
System.out.println("You are the champion");
}
}
class DeckOfCards {
String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
Random ran = new Random();
int systemWin = 0;
int playerWin = 0;
String inputCard(int card) {
int suit = card / 13; //assigning suit to your card
int rank = card % 13; //Assigning rank to your card
String out = "";
switch (rank) { //Setting up face cards for the cases
case 0:
out = "Ace of " + suits[suit];
break;
case 10:
out = "Jack of " + suits[suit];
break;
case 11:
out = "Queen of " + suits[suit];
break;
case 12:
out = "King of " + suits[suit];
break;
default:
out = rank + 1 + " of " + suits[suit]; //Adding one to remainder so it will go from 2-10 instead of 1-9
break;
}
return out;
}
int computerTurn(int playerRank) { //Keeping track of the wins for computer and player
int systemRank = this.ran.nextInt(51);
if (systemRank > playerRank)
systemWin++;
else
playerWin++;
return systemRank;
}
}
解决方案
我认为您是在将索引与您的套牌进行比较,而不是卡片本身的价值。如果我理解,您想将 d.inputCard(card) 与 d.inputCard(systemCard) 进行比较,而不是将 card 与 systemCard 进行比较。但当然,这是一个字符串。很难遵循代码:-)。
推荐阅读
- python-3.x - Elasticsearch 按数组中的出现或顺序搜索/过滤
- django - 如何在 Django 的模型清理方法中验证多个字段
- python - 如何处理静态类型语言(或一般类型)中的各种错误
- django - 创建超级用户后,Django 无法访问管理员登录页面
- c# - Unity:如何修复错误 CS0201?新对象表达式不能用作语句
- spring-boot - 使用 Apple ID 登录的 Oauth2 会返回没有 CSRF 令牌的请求
- html - div 在另一个 div 下面,每个 div 都有 100% 的屏幕宽度和高度
- excel - VBA根据单元格引用设置打印区域
- javascript - 在mattable中给每一行一个随机颜色
- excel - 如何计算定量x变量对y变量的影响