今天参考书里的例子,动手写了一个Craps的小程序。就是掷骰子游戏。投掷两个骰子,计算点数和。如果第一次掷出了7和11,则赢了。如果第一次掷出2,3,12,则输了。第一次掷出了其他的点数,则该点数将做为接下来需要投掷的目标点数。接下来可以不停地投掷,直到投到了目标点数则赢,如果接下来任何一次投到了7,则输了。
具体代码如下:
//Craps
import java.applet.Applet;
import java.awt.Button;
import java.awt.Event;
import java.awt.Label;
import java.awt.TextField;
public class Craps extends Applet{
// constant variables for status of game
final int WON = 0, LOST = 1, CONTINUE = 2;
// other variables
Label label_dice1, label_dice2, label_sum, label_point;
TextField text_dice1, text_dice2, text_sum, text_point;
Button buttonRoll;
int dice1, dice2, sum, point;
boolean firstRoll;
int gameStatus;
// setup the graphical user interface components
// and initialize the variables
public void init()
{
label_dice1 = new Label( "Dice 1" );
label_dice2 = new Label( "Dice 2" );
label_sum = new Label( "Sum is" );
label_point = new Label( "Point is" );
text_dice1 = new TextField( 10 );
text_dice2 = new TextField( 10 );
text_sum = new TextField( 10 );
text_point = new TextField( 10 );
text_dice1.setEditable( false );
text_dice2.setEditable( false );
text_sum.setEditable( false );
text_point.setEditable( false );
buttonRoll = new Button ( "Roll Dice" );
add( label_dice1 );
add( text_dice1 );
add( label_dice2 );
add( text_dice2 );
add( label_sum );
add( text_sum );
add( label_point );
add( text_point );
add( buttonRoll );
firstRoll = true;
sum = point = 0;
}
// process one roll
public void play()
{
if ( firstRoll ) {
sum = rollDice();
switch ( sum ) {
case 7: case 11:
gameStatus = WON;
text_point.setText( "" );
firstRoll = true;
break;
case 2: case 3: case 12:
gameStatus = LOST;
text_point.setText( "" );
firstRoll = true;
break;
default:
gameStatus = CONTINUE;
text_point.setText( Integer.toString( sum ) );
firstRoll = false;
break;
}
}
else {
point = Integer.parseInt( text_point.getText() );
sum = rollDice();
if ( sum == point ) {
gameStatus = WON;
text_point.setText( "" );
firstRoll = true;
}
else if ( sum == 7 ) {
gameStatus = LOST;
text_point.setText( "" );
firstRoll = true;
}
}
// display the game status
if ( gameStatus == WON )
showStatus( "You win." );
else if ( gameStatus == LOST )
showStatus( "You lost." );
else if ( gameStatus == CONTINUE )
showStatus( "Roll again" );
}
// rollDice method definition
public int rollDice()
{
dice1 = 1 + ( int ) ( Math.random() * 6 );
dice2 = 1 + ( int ) ( Math.random() * 6 );
text_dice1.setText( Integer.toString( dice1 ) );
text_dice2.setText( Integer.toString( dice2 ) );
sum = dice1 + dice2;
text_sum.setText( Integer.toString( sum ) );
return sum;
}
// process button action
public boolean action ( Event e, Object o )
{
play();
return true;
}
}
在这个小程序中,接触到了常量的定义。定义了常量后,那个被定义的数字的修改变的容易了,如果在代码中多次出现,也不会产生输入错误。
同时第一次使用了button这个组件,不过只是稍微提及了下,后面还要好好深入学习下。
尽管这个小游戏很简单,但是自己写出来还是觉得很有意思,慢慢建立起一种程序思维。而且通过参照书本中给出的程序,可以发现自己的想法中的不足。