📄 riskgame.java
字号:
// Yura Mamyrin, Group D
package risk.engine.core;
import java.util.*;
import java.io.*;
import java.awt.Color;
import java.net.URL;
//import java.beans.XMLEncoder;
//import java.beans.XMLDecoder;
/**
* <p> Risk Game Main Class </p>
* @author Yura Mamyrin
*/
public class RiskGame implements Serializable { // transient
private static final long serialVersionUID = 6L;
public final static String SAVE_VERSION = String.valueOf(serialVersionUID);
public final static int MAX_PLAYERS = 6;
public final static Continent ANY_CONTINENT = new Continent("any","any", 0, null);
public final static int STATE_NEW_GAME = 0;
public final static int STATE_TRADE_CARDS = 1;
public final static int STATE_PLACE_ARMIES = 2;
public final static int STATE_ATTACKING = 3;
public final static int STATE_ROLLING = 4;
public final static int STATE_BATTLE_WON = 5;
public final static int STATE_FORTIFYING = 6;
public final static int STATE_END_TURN = 7;
public final static int STATE_GAME_OVER = 8;
public final static int STATE_SELECT_CAPITAL = 9;
public final static int STATE_DEFEND_YOURSELF = 10;
public final static int MODE_DOMINATION = 0;
public final static int MODE_CAPITAL = 2;
public final static int MODE_SECRET_MISSION = 3;
public final static int CARD_INCREASING_SET = 0;
public final static int CARD_FIXED_SET = 1;
/*
// public final static int MODE_DOMINATION_2 = 1;
gameState:
nogame (-1 in gui) (current possible commands are: newgame, loadgame, closegame, savegame)
9 - select capital (current possible commands are: capital)
10 - defend yourself! (current possible commands are: roll)
0 - new game just created (current possible commands are: newplayer, delplayer, startgame)
1 - trade cards (current possible commands are: showcards, trade, notrade)
2 - placing new armies (current possible commands are: placearmies, autoplace)
3 - attacking (current possible commands are: attack endattack)
4 - rolling (current possible commands are: roll retreat)
5 - you have won! (current possible commands are: move)
6 - fortifying (current possible commands are: movearmy nomove)
7 - endturn (current possible commands are: endgo)
8 - game is over (current possible commands are: continue)
gameMode:
0 - WORLD DOMINATION RISK - 3 to 6 players
//1 - WORLD DOMINATION RISK - 2 player
2 - CAPITAL RISK - 3 to 6 players
3 - SECRET MISSION RISK - 3 to 6 players
playerType:
0 - human
1 - AI (Easy)
2 - AI (Hard)
3 - AI (Crap)
transient - A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.
*/
private static String defaultMap;
private static String defaultCards;
// ---------------------------------------
// THIS IS THE GAME INFO FOR Serialization
// ---------------------------------------
private Random r; // mmm, not sure where this should go, may stop cheeting when its here
// cant use URL as that stores full URL to the map file on the disk,
// and if the risk install dir changes the saves dont work
private String mapfile;
private String cardsfile;
private int setup;
private Vector Players;
private Country[] Countries;
private Continent[] Continents;
private Vector Cards;
private Vector Missions;
private Player currentPlayer;
private int gameState;
private int cardState;
private int mustmove;
private boolean capturedCountry;
private boolean tradeCap;
private int gameMode;
private Country attacker;
private Country defender;
private int attackerDice;
private int defenderDice;
private String ImagePic;
private String ImageMap;
private String previewPic;
private String mapName;
private Vector replayCommands;
private boolean simone;
private int cardMode;
private boolean runmaptest=false;
private boolean recycleCards=false;
/**
* Creates a new RiskGame
*/
public RiskGame() throws Exception {
//try {
setMapfile("default");
setCardsfile("default");
//}
//catch (Exception e) {
// e.printStackTrace();
//}
setup=0; // when setup reaches the number of players it goes into normal mode
Players = new Vector();
currentPlayer=null;
gameState=STATE_NEW_GAME;
cardState=0;
replayCommands = new Vector();
//System.out.print("New Game created\n"); // testing
simone=false;
r = new Random();
}
public void addCommand(String a) {
replayCommands.add(a);
}
public Vector getCommands() {
return replayCommands;
}
public boolean getSimone() {
return simone;
}
/**
* This adds a player to the game
* @param type Type of game (i.e World Domination, Secret Mission, Capital)
* @param name Name of player
* @param color Color of player
* @return boolean Returns true if the player is added, returns false if the player can't be added.
*/
public boolean addPlayer(int type, String name, Color color, String a) {
if (gameState==STATE_NEW_GAME ) { // && !name.equals("neutral") && !(color==Color.gray)
for (int c=0; c< Players.size() ; c++) {
if (( name.equals(((Player)Players.elementAt(c)).getName() )) || (color == ((Player)Players.elementAt(c)).getColor() )) return false;
}
//System.out.print("Player added. Type: " +type+ "\n"); // testing
Player player = new Player(type, name, color , a);
Players.add(player);
return true;
}
else return false;
}
/**
* This deletes a player in the game
* @param name Name of the player
* @return boolean Returns true if the player is deleted, returns false if the player cannot be deleted
*/
public boolean delPlayer(String name) {
if (gameState==STATE_NEW_GAME) {
int n=-1;
for (int c=0; c< Players.size() ; c++) {
if (name.equals( ((Player)Players.elementAt(c)).getName() )) n=c;
}
if (n==-1) {
//System.out.print("Error: No player found\n"); // testing
return false;
}
else {
Players.removeElementAt(n);
Players.trimToSize();
//System.out.print("Player removed\n"); // testing
return true;
}
}
else return false;
}
/**
* Starts the game Risk
* @param mode This represents the moce of the game: normal, 2 player, capital or mission
*/
public void startGame(int mode, int card, boolean recycle) throws Exception {
if (gameState==STATE_NEW_GAME) { // && ((mapfile !=null && cardsfile !=null) || () )
gameMode=mode;
cardMode=card;
recycleCards = recycle;
// 2 player human crap
//if ( gameMode==1 && ( !(((Player)Players.elementAt(0)).getType()==0) || !(((Player)Players.elementAt(1)).getType()==0) ) ) { return; }
// check if things need to be loaded, maybe already loaded, then these will be null
if (mapfile!=null && cardsfile!=null) {
//try {
loadMap(mapfile);
//}
//catch (Exception e) {
// e.printStackTrace();
// return;
//}
try {
loadCards(cardsfile);
}
catch (Exception e) {
if (runmaptest) {
//System.out.println("LOAD FILE ERROR: " + e.getMessage() + "\n(This normally means you have selected the wrong set of cards for this map)"); // testing
//e.printStackTrace();
throw new Exception("LOAD FILE ERROR: " + e.getMessage() + "\n(This normally means you have selected the wrong set of cards for this map)",e);
}
return;
}
if (runmaptest) {
//try {
testMap(); // testing maps
//}
//catch (Exception e) {
// e.printStackTrace();
// return;
//}
}
}
if (Countries==null) { return; }
if (gameMode==MODE_SECRET_MISSION && Missions.size() < Players.size() ) { return; }
int armies = ( 10 - Players.size() ) * Math.round( Countries.length * 0.12f );
// System.out.print("armies="+ armies +"\n");
//
//if (gameMode==1) { // 2 player mode
// Player player = new Player(3, "neutral", Color.gray , "all" );
// Players.add(player);
//}
//
//System.out.print("Game Started\n"); // testing
for (int c=0; c< Players.size() ; c++) {
((Player)Players.elementAt(c)).addArmies(armies);
}
gameState=STATE_PLACE_ARMIES;
capturedCountry=false;
tradeCap=false;
}
}
/**
* this code is used to check if the borders in the map file are ok
*/
public void testMap() throws Exception {
//System.out.print("Starting map test...\n");
for (int c=0; c< Countries.length ; c++) {
Country c1 = Countries[c];
Vector c1neighbours = (Vector)c1.getNeighbours();
if (c1neighbours.contains(c1)) { throw new Exception("Error: "+c1.getName()+" neighbours with itself"); }
for (int a=0; a< c1neighbours.size() ; a++) {
Country c2 = (Country)c1neighbours.elementAt(a);
Vector c2neighbours = (Vector)c2.getNeighbours();
boolean ok=false;
for (int b=0; b< c2neighbours.size() ; b++) {
Country c3 = (Country)c2neighbours.elementAt(b);
if ( c1 == c3 ) { ok=true; }
}
if (ok==false) {
throw new Exception("Borders error with: " + Countries[c].getName() + " ("+Countries[c].getColor()+") and " + ((Country)c1neighbours.elementAt(a)).getName() +" ("+((Country)c1neighbours.elementAt(a)).getColor()+")" ); // Display
}
}
}
//System.out.print("End map test.\n");
}
/**
* Sets the current player in the game
* @param name The name of the current player
* @return Player Returns the current player in the game
*/
public Player setCurrentPlayer(String name) {
for (int c=0; c< Players.size() ; c++) {
if ( ((Player)Players.elementAt( c )).getName().equals(name) ) { currentPlayer=((Player)Players.elementAt( c )) ; }
}
return currentPlayer;
}
/**
* Gets the current player in the game
* @return String Returns the name of a randomly picked player from the set of players
*/
public String getRandomPlayer() {
return ((Player)Players.elementAt( r.nextInt( Players.size() ) )).getName();
}
/**
* Checks whether the player deserves a card during at the end of their go
* @return String Returns the name of the card if deserves a card, else else returns empty speech-marks
*/
public String getDesrvedCard() {
//check to see if the player deserves a new risk card
if (capturedCountry==true && Cards.size() > 0) {
Card c = (Card)Cards.elementAt( r.nextInt(Cards.size()) );
if (c.getCountry() == null) return Card.WILDCARD;
else return ( (Country)c.getCountry() ).getColor()+"";
}
else {
return "";
}
}
/**
* Ends a player's go
* @return Player Returns the next player
*/
public Player endGo() {
if (gameState==STATE_END_TURN) {
//System.out.print("go ended\n"); // testing
// work out who is the next player
while (true) {
for (int c=0; c< Players.size() ; c++) {
if ( currentPlayer==((Player)Players.elementAt(c)) && Players.size()==(c+1) ) {
currentPlayer=(Player)Players.elementAt(0);
c=Players.size();
}
else if ( currentPlayer==((Player)Players.elementAt(c)) && Players.size() !=(c+1) ) {
currentPlayer=(Player)Players.elementAt(c+1);
c=Players.size();
}
}
if ((setup != Players.size()) ) { break; }
// && (currentPlayer.getType() != 3)
else if ( currentPlayer.getNoTerritoriesOwned() > 0 ) {break; }
}
//System.out.print("Curent Player: " + currentPlayer.getName() + "\n"); // testing
if ( setup == Players.size() && !(gameMode==2 && currentPlayer.getCapital() == null) ) { // ie the initial setup has been compleated
workOutEndGoStats( currentPlayer );
currentPlayer.nextTurn();
// add new armies for the Territories Owned
if ( currentPlayer.getNoTerritoriesOwned() < 9 ) {
currentPlayer.addArmies(3);
}
else {
currentPlayer.addArmies( currentPlayer.getNoTerritoriesOwned() / 3 );
}
// add new armies for the Continents Owned
for (int c=0; c< Continents.length ; c++) {
if ( Continents[c].isOwned(currentPlayer) ) {
currentPlayer.addArmies( Continents[c].getArmyValue() );
}
}
}
if (setup == Players.size() && gameMode==2 && currentPlayer.getCapital() == null) { // capital risk setup not finished
gameState=STATE_SELECT_CAPITAL;
}
else if ( canTrade()==false ) { // ie the initial setup has not been compleated or there are no cards that can be traded
gameState=STATE_PLACE_ARMIES;
}
else { // there are cards that can be traded
gameState=STATE_TRADE_CARDS;
}
capturedCountry=false;
tradeCap=false;
return currentPlayer;
}
else {
//System.out.println("lala "+gameState);
return null;
}
}
/**
* Trades a set of cards
* @param card1 First card to trade
* @param card2 Second card to trade
* @param card3 Third card to trade
* @return int Returns the number of armies gained from the trade, returning 0 if the trade is unsuccessful
*/
public int trade(Card card1, Card card2, Card card3) {
if (gameState==STATE_TRADE_CARDS) {
// now check if they CAN be traded or not
if ( checkTrade(card1, card2, card3) ) {
// NOW TRADE THE CARDS
currentPlayer.tradeInCards(card1, card2, card3);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -