How to Code a Simple Random Virtual Dice

by Ramon771 in Circuits > Software

1261 Views, 4 Favorites, 0 Comments

How to Code a Simple Random Virtual Dice

Screenshot_20200512-232438.png

Hi everyone!!!!! This is my first instructable and i will be teaching you how to code a virtual dice on your PC or smartphone. I am using HTML,JavaScript and CSS , I hope you would all love it and don't forget to vote for me in the context below.

Supplies

1. A good text editor on your smart phone or PC

Get Your Text Editor

Here i am using my smartphone as a text editor here (AnWriter). You can use your PC's notepad too, or get a good text editor online

Download Die Faces

die_face_2.png
die_face_1.png
die_face_3.png
die_face_4.png
die_face_5.png
die_face_6.png

I downloaded some die faces from 1 to 6 which i attach to this step. So, you can download your preferred one or use mine( you are free).

I named mine according to the die faces. That is:

Die_face_1.png ,

Die_face_2.png ....and so on till 6 for better recognition

Start Coding

Save the code as .html file

Start by introducing the default die face you want by using the img src

<img src="die_face_6.png" id ="dice" >

Next we will need a button to roll the dice we do this by adding a button function

<button style="width:100px;height:100px;"onclick ="getRand()">
ROLL DICE
</button>

Use the Var and Math Function

Screenshot_20200512-214943.png
<img src="die_face_6.png" id ="dice" >
<button style="width:100px;height:100px;"onclick ="getRand()">
SHAKE DICE
</button>
<img src="die_face_6.png" id ="dicl" >
<script type="text/javascript">
function getRand(){
var vu=Math.floor(Math.random()*6)+1;
var vu2=Math.floor(Math.random()*6)+1;
var di =["die_face_1.png","die_face_2.png","die_face_3.png","die_face_4.png","die_face_5.png","die_face_6.png"];
document.getElementById("dice").src= di[vu-1];
document.getElementById("dicl").src= di[vu2-1];
}
</script> 

This is the full code, study it and test it and make sure you get the photo to get the effect

And if you need my help on this code mention it in the comment section

You could change the design if you don't like it but i prefer it for the purpose i want to use it for

Run

The dice test

run the code on your browser to get it working