ผลต่างระหว่างรุ่นของ "01219245/javascript1/tutorial1"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
(01219245/javascript1/practice1 ถูกเปลี่ยนชื่อเป็น 01219245/javascript1/tutorial1)
แถว 22: แถว 22:
 
== Let's get started ==
 
== Let's get started ==
  
== First sketch ==
+
Before we dive in to code the game, it's best to think about the overall picture.  We code in small steps, but without the overall idea, it is very easy to get lost.
  
== Main loop ==
+
What are the steps, in the program, that we have to do? 
 +
 
 +
* Random the number
 +
* Read the guess
 +
* Check the guess and give hint
 +
* Repeat
 +
 
 +
=== First sketch ===
 +
 
 +
If we forget all the details, our JavaScript program would look like this:
 +
 
 +
<syntaxhighlight lang="javascript">
 +
var sol = randomSolution();
 +
do {
 +
    var guess = readGuess();
 +
    if ( guess == sol ) {
 +
        congratulate();
 +
    } else if ( guess < sol ) {
 +
        giveHint( 'Too Low' );
 +
    } else {
 +
        giveHint( 'Too High' );
 +
    }
 +
} while ( guess != sol );
 +
</syntaxhighlight>

รุ่นแก้ไขเมื่อ 18:59, 9 มกราคม 2557

This is part of 01219245

The best way to learn a language is to use it.

In this tutorial, we will write a simple number guessing game in JavaScript. Your goal is to guess a number between 1 - 100. If you guess incorrectly, a hint is given to you: if your guess is too high or too low. The game proceeds until you guess correctly.

An example of the interaction is given below:

Round 1, your guess?
40
Too low.
Round 2, your guess?
90
Too high.
Round 3, your guess?
75
Too high.
Round 4, your guess?
55
Great that's correct.

Let's get started

Before we dive in to code the game, it's best to think about the overall picture. We code in small steps, but without the overall idea, it is very easy to get lost.

What are the steps, in the program, that we have to do?

  • Random the number
  • Read the guess
  • Check the guess and give hint
  • Repeat

First sketch

If we forget all the details, our JavaScript program would look like this:

var sol = randomSolution();
do {
    var guess = readGuess();
    if ( guess == sol ) {
        congratulate();
    } else if ( guess < sol ) {
        giveHint( 'Too Low' );
    } else {
        giveHint( 'Too High' );
    }
} while ( guess != sol );