SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    May 2001
    Location
    VA
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JavaScript assistance

    I am looking for help in creating a page that rolls six-sided dice. The user should be able to type the number of dice to roll and when he/she clicks a button, JavaScript will roll the dice and tell how many of each number (1 through 6) came up. Use a form to give this information to the user.

    Many thanks.

  2. #2
    JavaScript Guru (Big Ego) Arielladog's Avatar
    Join Date
    Jul 1999
    Location
    SC, USA
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    What you're basically doing is creating a random number from 1-6. To do this, you usually go:

    Math.floor(Math.random()*greatestValue)+lowestValue

    Math.random() produces a result 0-1. So, in your case, it should be:

    Math.floor(Math.random()*6)+1

    So, we can use this information to do what you want:

    Code:
    <script>
    function rollD(frm){
    x=parseInt(frm.input1.value);
    result=new Array(x);
    for(i=0;i<x;i++){
    result[i]=Math.floor(Math.random()*6)+1;
    }
    frm.res.value=result.join(", ");
    }
    </script>
    <form>
    Dice to roll: <input type="text" name="input1"> <input type="button" value="Roll!" onclick="rollD(this.form)">
    <br>Result of the dice: <input type="text" name="res">
    </form>
    aDog


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •