www.webdeveloper.com
Results 1 to 6 of 6

Thread: Help on tortoise and hare.

Hybrid View

  1. #1
    Join Date
    Oct 2012
    Posts
    3

    Help on tortoise and hare.

    I honestly do not even know where to start with this. I am completely lost and confused except that I know I need to use math.random() and some cases or if-else statements.

    Instructions are as follows: <In this problem, you will recreate one of the truly great moments in history, namely the classic race of the tortoise and the hare. You will use random number generation to develop a simulation of this memorable event. Our contenders begin the race at square 1 of 70 squares. Each square represents a possible position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground. There is a clock that ticks once per second. With each tick of the clock, your script should adjust the position of the animals according to the following rules: Animal Move type Percentage of the time Actual move Tortoise Fast plod 50% 3 squares to the right Slip 20% 6 squares to the left Slow plod 30% 1 square to the right Hare Sleep 20% No move at all Big hop 20% 9 squares to the right Big slip 10% 12 squares to the left Small hop 30% 1 square to the right Small slip 20% 2 squares to the left Use variables to keep track of the positions of the animals (i.e. position numbers are 1 – 70). Start each animal at poisiton 1 (i.e. the “starting gate”). If an animal slips left before square 1, move the animal back to square 1. Generate the percentages in the preceding table by producing a random integer I in the range 1<= I <= 10. For the tortoise, perform a “fast plod” when 1<=i<= 5, a “slip” when 6 <= I <= 7 and a “slow plod” when 8<=I <=10. Use a similar technique to move the hare. Begin the race by printing: “Bang!!! and they’re off!!!" Then, for each tick of the clock (i.e. each repetition of a loop), print a 70 position line showing the letter T in the position of the tortoise and the letter H in the position of the hare. Occasionally, the contenders will land on the same square. In this case, the tortoise bites the hare, and your script should print “OUCH!!!” beginning at that position. All print positions other than the T, the H or the “OUCH!!!” (in case of a tie) should be blank. After each line is printed, test whether either animal has reached or passed square 70. If so, print the winner, and terminate the simulation. If the tortoise wins, print “Tortoise wins!!! YAY!!!” If the hare wins, print “Hare wins. Yuck!” If both animals win on the same tick of the clock, print “It’s a tie”. If neither animal wins, perform the loop again to simulate the next tick of the clock.

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    Start off by having a function execute once every second. Then make the animals move every time it executes. I think that's a good start.

    Well, good luck!

    (Free pro tip: use more line breaks when posting... Big walls of text are very hard to read.)

  3. #3
    Join Date
    Oct 2012
    Posts
    3

    Thanks

    Thanks I appreciate it and I will try and put more breaks in next time.

  4. #4
    Join Date
    Oct 2012
    Posts
    3

    Still not working

    This is what I have so far. It does not do anything when I open it in a browser right now and I really don't know where to go from here.

    <?xml version = "1.0" encoding = "utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns = "http://www.w3.org/1999/xhtml">
    <title>Tortoise and hare</title>
    <body>
    <script type = "text/javascript">
    function moveT()//tortoise movement function
    {
    var tmp = Math.floor((Math.random()*10)+1);

    if (tmp < 5)
    return 3;
    if (tmp < 7)
    return -6;
    return 1;
    }

    function moveH()//Hare movement function
    {
    var tmp = Math.floor((Math.random()*10)+1);

    if (tmp < 2)
    return 0;
    if (tmp < 4)
    return 9;
    if (tmp < 5)
    return -12;
    if (tmp < 8)
    return 1;
    return -2;
    }


    function win()
    {
    if ( tortoise >= 69 )
    {
    document.writeln( "TORTOISE WINS!!! YAY!!!" );
    winner = true;
    }
    else if ( hare >= 69 )
    {
    document.writeln( "Hare wins. Yuck!" );
    winner = true;
    }
    else if ( (tortoise >= 69) && (hare >= 69) )
    {
    document.writeln( "It's a tie." );
    }
    }

    function draw()
    {
    for (var i = 0; i < 80; i++)
    {
    if ( (i == tortoise) && (i == hare) )
    {
    document.write( "OUCH!!!" );
    i += 6;
    }

    else if ( i == tortoise )
    {
    document.write( "T" );
    }
    else if ( i == hare )
    {
    document.write( "H" );
    }
    else if ( (i == tortoise) && (i == 69) )
    {
    document.write( "T" );
    }
    else if ( (i == hare) && (i == 69) )
    {
    document.write( "H" );
    }
    else if ( i == 69 )
    {
    document.write( "|" );
    }
    else if ( (i > 69) && (i != tortoise) && (i != hare) )
    {
    document.write( " " );
    }
    }
    }

    </script>
    </body>
    </html>

  5. #5
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    Nothing happens because you never call any of the functions at any point. Use the window.setInterval() function to execute a function at specific intervals. You'll need to add something like this:

    Code:
    function intervalFunc(){
        tortoise += moveT();
        hare += moveH();
    
        draw();
    
    
        if ( (tortoise >= 69) || (hare >= 69) )
            win();
    }
    
    setInterval(intervalFunc, 1000);
    And I don't recommend using document.write() when adding stuff to the page in this case. This is a better way if you want to replace everything on the page with something new:

    Code:
    document.body.innerHTML = "Hare wins!";

  6. #6
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    Quote Originally Posted by meme2324 View Post
    In this problem, you will recreate one of the truly great moments in history, namely the classic race of the tortoise and the hare.
    You're not the first to post this assignment. This is my interpretation, which won't do you any good but you might like to run it for inspiration:
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Tortoise and Hare</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type='text/css'>
    a,a:link,a:visited{padding:0.2em;}
    a:hover,a:active{padding:0.2em;text-decoration:none}
    body{ background-color:#0f0 }
    </style>
    </head>
    <body id="theBody">
    <div id='raceText' style='color:#000;font-weight:bold;position:fixed;top:5px;left:50%'></div>
    
    <input type='button' value='Reload' onclick='location.reload(true)' style='position:fixed; right:5px'>
    
    <script type='text/javascript'>
    
    function TAndH( containerID, cLength, resultBoxID )
    {
      var obj = this;
      
      this.delay = 997;
      this.cLength = cLength;
      this.squares = [];
      this.lastTPos = 1;
      this.lastHPos = 1;
      this.commentBox = document.getElementById( resultBoxID );
      
      this.actions = 
      { 
        "T" : [ { min : 1, max : 5, dist : 3 }, { min : 6, max : 7, dist : -6 }, { min : 8, max : 10, dist : 1 } ],
     
        "H" : [ { min : 1, max : 2, dist : 0 }, { min : 3, max : 4, dist : 9 }, { min : 5, max : 5, dist : -12 }, 
                { min : 6, max : 8, dist : 1 }, { min : 9, max : 10, dist : -2} ]
      }
      
      this.say = function( str, del )
      { 
        var inst = this;
        this.commentBox.innerHTML = str; 
        if( del )
          setTimeout( function(){ inst.commentBox.innerHTML=""; }, 2000 );
      }
      
      this.ouch = function( action )
      {
        var str = "OUCH!",
            inst = this,
            offset;
        
        this.collPos = this.lastHPos;
        
        offset = Math.max( 0,  str.length + this.collPos - this.cLength );
        
        for( var i = 0; i < str.length; i++ )
          this.squares[ this.collPos-1 + i - offset ].innerHTML = !action ? str.charAt( i ) : "";
        
        if( action )
          this.squares[ this.collPos-1 ].innerHTML = "TH";
        else     
          setTimeout( function(){ inst.ouch( true ); }, this.delay * 0.6 );     
      }
      
      this.buildCourse = function( /*2843294C6F67696320416C69*/ )
      {
        var container = document.getElementById( containerID ),
            place;
       
        for( var i = 0, sqLeft = 10, y = 100; i < this.cLength; i++, sqLeft += 16 )
        {
          place = document.createElement( 'div' );
     
          with( place.style )
          {
            position = 'absolute';
            left = sqLeft + 'px';
            top = (y = (y-5 + (Math.random()*10)) )+ 'px';
            
            width = '1.5em';
            height = '1.5em';
            padding = '2px';
            fontSize = '.6em';
            color = '#fff';
            backgroundColor = '#840';
            borderBottom = '2px solid #420';
          }    
          this.squares.push( container.appendChild( place ) );
        }     
        
        this.squares[ 0 ].innerHTML = "TH";
      }
      
      this.move = function( animal, pc )
      {
        var data = this.actions[ animal ],
            len = data.length,
            lastPos = this[ 'last' + animal + 'Pos' ],
            pos;
        
        for( var i = 0, found = false; i < len && !found; i++ )
          if( pc >= data[ i ].min && pc <= data[ i ].max )
          {
            found = true;
            pos = Math.min( this.cLength, Math.max( lastPos + data[ i ].dist, 1 ) );
            this.squares[ lastPos-1 ].innerHTML = this.squares[ lastPos-1 ].innerHTML.replace( animal, "" ); 
            this.squares[ pos-1 ].innerHTML += animal;
            this[ 'last' + animal + 'Pos' ] = pos;
          }    
      }
      
      this.run = function()
      {
        var i = 1 + Math.floor( Math.random() * 10 ),
            inst = this;
            
        this.move( "T" , i );   
        this.move( "H" , i );      
        
        if( this.lastTPos == this.lastHPos && this.lastTPos != this.cLength )
          setTimeout( function(){ inst.ouch( 0 ); }, 200 );
     
        if( this.lastTPos != this.cLength && this.lastHPos != this.cLength )
          setTimeout( function(){inst.run()}, this.delay );
        else
          this.say( this.lastHPos == this.cLength ? ( this.lastTPos == this.cLength ? "It's a tie!" : "Hare wins - yuck"): "Tortoise wins 'Yay!'", false );      
      }
      
      this.buildCourse();
      
      setTimeout( function(){ obj.say( "They're off!", true ); obj.run() }, 1000 );
    }
    
    new TAndH( 'theBody', 70, 'raceText' );
    
    </script>
    </body>
    </html>
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles