Thursday, 14 August 2014

Browser Based Dice Thrower Using Java

I wanted to use Java to create a simple dice simulator, which I could run in a browser, so I wrote the following program and compiled it. It generates a random integer between 1 and 6, converts it into a string then displays it:

andrew@UBUNTU:~/Java$ cat Dice.java
import java.awt.Graphics;
public class Dice
extends java.applet.Applet
{
public void paint(Graphics g)
  {
  int int1 = (int) (Math.random() * 6 + 1);
  String string1 = String.valueOf(int1);
  g.drawString(string1,20,40);
  }
}
andrew@UBUNTU:~/Java$ javac Dice.java
andrew@UBUNTU:~/Java$

Then I wrote a few lines of HTML:

andrew@UBUNTU:~/Java$ cat Dice.html
<html>
<head>
<title>Dice Thrower</title>
</head>
<body>
<applet name="Dice Thrower"
 code="Dice.class"
 width = 400 height = 200>
</applet>
</body>
</html>
andrew@UBUNTU:~/Java$ 

... so I could run it like this. Each time I reloaded the page, the program created a new number. As usual, click on the image to enlarge it and bring it into focus:


Finally, I loaded it on the free web space which comes with my home Internet connection. If you would like to try it yourself, click on the link below (it should look like the screen above):