All pastes #739752 Raw Edit

TextFighter.java

public java v1 · immutable
#739752 ·published 2007-10-17 13:21 UTC
rendered paste body
/**  Main class for Text Fighter  - 20070928, Cheung Ho Yin */import java.util.Scanner;import java.util.Random;public class TextFighter {  private static Scanner input = new Scanner( System.in );  private static Player [] p     = { new Player(), new Player("Florence"),      new Player("Janice"), new Player("Justin") };  private static Random r = new Random();  // Methods  public static boolean gameOver() {    if(p[0].isDead()) return true;    int dead=0;    for(int i=0; i<p.length; i++){      if(p[i].isDead()) dead++;    }    return (dead>=p.length-1)?true:false;  }  // Action taken by a human player  public static void humanAction( Player player ) {    System.out.printf( "\n%s's command > ", player.getName());    int command = input.nextInt();    if( command < 0 || command >= p.length ){      System.out.println("--> Invalid option!");      return;    }    player.attack( p[command] );  }  // Action taken by a computer player  public static void computerAction( Player player ) {    if(player.isDead()) return; // do nothing if already dead    int command = r.nextInt()%2+1;    System.out.println();    System.out.printf( "%s's command > Thinking... /\r", player.getName() ); sleep();    System.out.printf( "%s's command > Thinking... -\r", player.getName() ); sleep();    System.out.printf( "%s's command > Thinking... \\\r", player.getName() ); sleep();    System.out.printf( "%s's command > Thinking... |\r", player.getName() ); sleep();    System.out.printf( "%s's command > Thinking... /\r", player.getName() ); sleep();    System.out.printf( "%s's command >              \r", player.getName() );    System.out.printf( "%s's command > %d\n", player.getName(), command );    player.attack( p[command] );  }  private static void sleep() {    try {      Thread.sleep(300);    } catch (InterruptedException e) {      e.printStackTrace();    }  }  public static void printStatus() {    for(int i=0; i<p.length; i++){      if(!p[i].isDead()) System.out.printf("[%d] %s (%d)\n", i, p[i].getName(), p[i].getPower() );    }  }  // Main program  public static void main( String [] args ){    int counter=0;    System.out.print("Java Text Fighter! v20070928\n\n");    System.out.print("Enter your name: ");    Scanner input = new Scanner(System.in);    p[0].setName( input.nextLine() );    do {      // Print heading information      System.out.println("\n== Round " + (++counter) + " ==");      printStatus();      // Human player      humanAction(p[0]);      // Computer players      for(int i=1; i<p.length; i++) { computerAction(p[i]); }      System.out.println();    } while(!gameOver());    System.out.println("Game over! The survivor(s):");    printStatus();  }}