// File: Dice.java
// T Balls Feb 1998
// Simulate the throwing of some dice
// and show the results graphically
import java.awt.*;
import java.util.Random;
public class Dice extends Frame
{ public Dice( int noOfDice )
{ dice = noOfDice;
setTitle( "Dice: " + dice );
setSize( 400, 300 );
results = new int[ 5*dice+1 ];
throwDice();
setVisible( true );
}
private int dice;
private int[] results;
Random roll = new Random();
// toss dice 1000 times
private void throwDice()
{ int loop;
for( loop = 0; loop < 1000; loop += 1 )
{ int score = 0;
for( int die = 0; die < dice; die += 1 )
{ int value = Math.abs(roll.nextInt()) % 6 + 1;
score += value;
}
results[ score-dice ] += 1;
}
}
public void paint( Graphics g )
{ Dimension d = getSize();
int left = 10;
int bottom = d.height - 20;
int width = d.width-20;
int height = d.height - 50;
int die;
int max=0;
for( die = 0; die < results.length; die += 1 )
{ if( max < results[die] )
{ max = results[die];
}
}
int vertUnit = height/max;
int horizUnit = width/(5*dice+1);
for( die = 0; die < results.length; die += 1 )
{ g.drawRect( left+die*horizUnit,
bottom-results[die]*vertUnit,
horizUnit,
results[die]*vertUnit );
}
}
}
class TwoDice
{ public static void main( String[] args )
{ new Dice( 2 );
}
}
class ThreeDice
{ public static void main( String[] args )
{ new Dice( 3 );
}
}
class FourDice
{ public static void main( String[] args )
{ new Dice( 4 );
}
}
class FiveDice
{ public static void main( String[] args )
{ new Dice( 5 );
}
}
class SixDice
{ public static void main( String[] args )
{ new Dice( 6 );
}
}
|