①第一个类Player至少包含两个成员变量. 1.name---姓名 2.goals---进球数(int 类型, 代表这个队员在这次世界杯的进球数量) ②第二个类Team至少包含三个成员变量 1.name---球队名字(String 类型,代表球队国家) 2.ranking---球队排名(int类型,只能取值1,2,3,4 , 并且数值的大小代表球队的水平) 3.2 players---2个球员(Player类型的, 球队的进球数会平均分给他们两个,若球队的进球数是单数,则随机分配给一个球员多一个进球,另外一个球员少一个进球) ③第三个类Game至少包含一个成员变量: TeamList: 一个ArrayList,元素为Team类型的对象。 还得包含至少三个成员方法: playGame: 模拟的是比赛的过程。通过分配一个随机数给两个球队。从而作为比赛的结果。分配的规则如下: 球队排名高的队伍产生的随机数范围是0到(5 + (一个位于0-2之间的随机数) ) 球队排名低的队伍产生的随机数范围是0 到 (5 - (一个位于0-2之间的随机数)) playPenaltyShootOut: 模拟点球大战 。每个队伍的两名球员,每个人有五次点球机会(进没进,有0,1随机数决定,0代表不进,1代表进球,随机数0出现的概率为20%,1出现的概率为80%。最后将这两名球员的进球数加在一起,进球数多的那一队胜利。
时间: 2023-12-10 15:39:28 浏览: 112
下面是代码实现:
```
import java.util.ArrayList;
import java.util.Random;
class Player {
String name;
int goals;
Player(String n, int g) {
name = n;
goals = g;
}
}
class Team {
String name;
int ranking;
Player player1;
Player player2;
Team(String n, int r, Player p1, Player p2) {
name = n;
ranking = r;
player1 = p1;
player2 = p2;
}
}
class Game {
ArrayList<Team> teamList;
Game(ArrayList<Team> list) {
teamList = list;
}
void playGame() {
Random rand = new Random();
int random1 = rand.nextInt(3);
int random2 = rand.nextInt(3);
for (Team t: teamList) {
int range = (t.ranking <= 2) ? 5 + random1 : 5 - random2;
int score = rand.nextInt(range + 1);
System.out.println(t.name + " scored " + score + " goals.");
if (score % 2 == 0) {
t.player1.goals += score / 2;
t.player2.goals += score / 2;
} else {
int extra = rand.nextInt(2);
if (extra == 0) {
t.player1.goals += score / 2;
t.player2.goals += score / 2 + 1;
} else {
t.player1.goals += score / 2 + 1;
t.player2.goals += score / 2;
}
}
}
}
void playPenaltyShootOut() {
Random rand = new Random();
for (Team t: teamList) {
int teamScore = 0;
for (int i = 0; i < 5; i++) {
int score1 = rand.nextInt(2);
int score2 = rand.nextInt(2);
teamScore += score1 + score2;
}
System.out.println(t.name + " scored " + teamScore + " penalty shoot-out goals.");
if (teamScore > teamList.get(1).player1.goals + teamList.get(1).player2.goals) {
System.out.println(t.name + " won the penalty shoot-out.");
} else {
System.out.println(teamList.get(1).name + " won the penalty shoot-out.");
}
}
}
}
public class Main {
public static void main(String[] args) {
Player p1 = new Player("Player1", 0);
Player p2 = new Player("Player2", 0);
Team t1 = new Team("Team1", 1, p1, p2);
Player p3 = new Player("Player3", 0);
Player p4 = new Player("Player4", 0);
Team t2 = new Team("Team2", 2, p3, p4);
ArrayList<Team> teamList = new ArrayList<>();
teamList.add(t1);
teamList.add(t2);
Game game = new Game(teamList);
game.playGame();
game.playPenaltyShootOut();
}
}
```
这个程序中,我们定义了三个类,分别是Player, Team, Game。Player 类表示球员,包含两个成员变量,姓名和进球数。Team 类表示球队,包含四个成员变量,球队名字,球队排名,和两名球员。Game 类表示比赛,包含一个成员变量,一个 ArrayList,元素为 Team 类型的对象。在 Game 类中,我们实现了两个方法,playGame 和 playPenaltyShootOut。playGame 方法模拟比赛的过程,通过分配随机数给两个球队,从而得出比赛结果。playPenaltyShootOut 方法模拟点球大战的过程,通过随机数来决定每个球员的进球情况,并将进球数加在一起,最终得出胜利的球队。
阅读全文