Romantic Developer : )

(Javascript) 자바스크립트 기초실습 (2) 본문

Romantic Developer/JavaScript

(Javascript) 자바스크립트 기초실습 (2)

Romantic_Developer 2018. 7. 2. 12:00

안녕하세요~ 영감을 주는 개발자 방민방민입니다.


오늘은 지난 javascript 기초 문법에 이어 이를 활용한 간단한 반응형 웹을 만들어 보고자 합니다.


이 포스팅은 저번과 마찬가지로 코드카데미의 javascript 과정에서 "Code your own adventure" 과정을 토대로 작성되었습니다.

(참조 : https://www.codecademy.com/en/tracks/javascript)


그럼 시작합니다!



1. confirm


앞선 자바스크립트 기초(1) 이서 배웠던 confirm 기능을 활용하여 사용자의 준비를 확인합니다.

confirm("are you ready?");



2. Old enough to play?


사용자가 충분한 연령대의 사용자인지를 확인하기 위하여 사용자로부터 나이를 입력받고, 이를 특정 나이와 비교하여 메시지를 출력하도록 합니다. 이때, age 변수에 사용자 입력을 저장하고, if~else 문을 활용하여 검증한 뒤 알맞은 메시지를 출력합니다.

var age = prompt("what is your age?");

confirm("are you ready?");

var age = prompt("what is your age?");

if(age<= 13)
{
    console.log(" you are not allowed to take this")
}
else
{
    console.log(" let's get started");
}


위와같이 입력하면 사용자로부터 입력 받은 age 를 13과 비교하여 이 반응형 웹을 사용할수 있는지 아닌지를 확인합니다.


3. 스토리 추가와 사용자 입력


웹에서 반응할수 있는 사용자의 입력을 받기 위해 스토리를 추가하고 이에 따른 입력을 받아 변수 userAnswer 에 저장합니다. 코드는 아래와 같습니다.

confirm("are you ready?");

var age = prompt("what is your age?");

if(age<= 13)
{
    console.log(" you are not allowed to take this")
}
else
{
    console.log(" let's get started");
}

console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");

console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'");

var userAnswer = prompt("Do you want to race Bieber on stage?");


4. 사용자에 입력에 따른 출력


이후 사용자로부터 게임에 대한 점수를 feedback 이라는 변수에 입력받아 피드백이 8보다 클때와 작을때를 나누어 메시지를 출력하도록 조정합니다.


// Check if the user is ready to play!

confirm("are you ready?");

var age = prompt("what is your age?");

if(age<= 13)
{
    console.log(" you are not allowed to take this")
}
else
{
    console.log(" let's get started");
}

console.log("You are at a Justin Bieber concert, and you hear this lyric 'Lace my shoes off, start racing.'");

console.log("Suddenly, Bieber stops and says, 'Who wants to race me?'");

var userAnswer = prompt("Do you want to race Bieber on stage?");

if(userAnswer ==="yes")
{
    console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!");
}
else 
{
    console.log("Oh no! Bieber shakes his head and sings 'I set a pace, so I can race without pacing.'");
}

var feedback = prompt("grade the game out of 10");

if(feedback >=8)
{
    console.log("Thank you! We should race at the next concert!")
    
}
else
{
    console.log("I'll keep practicing coding and racing.");
}

위 코드를 따라 입력하면 아래와같은 실행화면이 나타납니다.



앞에서 배운 정말 간단한 코드를 활용하여, javascript를 이용한 반응형 콘솔을 확인해 보았습니다. 


아주 작은 첫걸음이지만 위대한 시작이 될 것입니다.


그럼 지금까지 영감을 주는 개발자 방민방민이었습니다.


감사합니다.