let funds = 50; //시작조건 while(funds>1 && funds <100) funds = funds +2; //while 루프 바디 funds = funds -1; //while 루프 끝난 후 실행
4.1.4 보조 함수
1 2 3 4 5 6 7 8 9
//m 이상 n 이하의 무작위 정수를 반환한다. functionrand(m,n){ return m + Math.floor((n - m +1) * Math.random()); } //크라운 앤 랭커 게임의 여섯 가지 도형 중 하나를 무작위로 반환한다. functionrandFace(){ return ["crown","anchor","heart","spade","Club","diamond"][rand(0,5)]; }
4.1.5 if else 문
1 2 3 4 5 6 7 8 9
const bets = {crown:0, anchor:0, heart:0, spade:0, club:0, diamond:0}; //토마스가 베팅할 카드 목록 {카드:얼마} let totalBet = rand(1,funds); if(totalBet===7){ //만약 돈을 7펜스를 뽑으면 totalBet = funds; //남은 돈을 다 건다. bets.heart = totalBet; //하트에 건다. }else{ //그 판에 걸 돈을 분배 } funds = funds - totalBet; // 남은돈 = 기존판에 남은돈 - 건 돈의 총액
4.1.6 do while 루프
while과 다르게 시작하면서 조건을 검사하지 않고 마지막에 검사한다. 루프바디를 최소 한 번은 실행하려 할 때 사용
1 2 3 4 5 6 7
let remaining = totalBet; //남은돈 = 걸 돈 총액; do{ let bet = rand(1,remaining); let face = randFace(); bets[face] = bets[face] + bet; remaining = remaining - bet; }while(remaining>0);
4.1.7 for 루프
어떤 일을 정해진 숫자만큼 반복할 때
1 2 3 4
const hand =[]; for(let roll=0; roll <3; roll++){ hand.push(randFace()); }
4.1.8 if문
1 2 3 4 5 6
let winnings = 0; for(let die=0; die<hand.length; die++){//hand.length ==3 (주사위를 세 번 굴린다.) let face = hand[die]; if(bets[face] > 0) winnings = winnings + bets[face]; } funds = funds +winnings;
/* [규칙] 1. 크라운, 앵커, 하트, 클럽, 스페이드, 다이아몬드 그림이 있고 선원이 무작위로 돈을 건다. 2. 6면체 주사위 세개를 굴린다. 3. 주사위가 사각형 번호에 일치하는 숫자에 멈추면 선원은 거기 건 만큼의 돈을 따게된다. 4. 예외 -> 토마스(선원)에게는 몇가지 규칙이 있다. 4-1) */
//m 이상 n 이하의 무작위 정수를 반환합니다. functionrand(m,n){ return m + Math.floor((n - m + 1) * Math.random()); } //rand(0,5) = > 0~5까지의 무작위 수를 반환.
//크라운 앤 앵커 게임의 여섯 그림 중 하나에 해당하는 문자열을 무작위로 반환합니다. functionrandFace(){ return ["crown","anchor","heart","spade","club","diamond"][rand(0,5)]; } // randFace() => "crown"
randFace();
let funds = 50; //선원이 가진 초기자본 = 50펜스 let round = 0; //게임 라운드
while(funds > 1 && funds < 100){ //선원 규칙 100펜스,0펜스가 되면 게임종료 즉 게임을 계속할때 round++; //게임 라운드가 1 올라가고 console.log('round ${round}:'); //돈을 건다. let bets = {crown :0 ,anchor:0,heart:0,spade:0,club:0,diamond:0}; let totalBet = rand(1,funds); //1~99까지의 무작위 금액을 거는 것에 대한 토탈 배팅 금액 console.log(totalBet);
//선원의 조건 if(totalBet ===7){ //뽑은 돈이 7펜스면 totalBet == funds; //남은 돈을 다 배팅 bets.heart = totalBet //현재는 0 인데 남은 돈 하트에 걸어버림 }else{ //판돈 나누기 let remaining = totalBet; do{ let bet = rand(1,remaining); //1~남은돈까지의 무작위 금액을 거는 것에 대한 배팅 금액 let face = randFace();// randFace() => "crown" bets[face] = bets[face] + bet; //0 = 0 + (1~남은돈까지의 무작위 금액을 거는 것에 대한 배팅 금액) remaining = remaining -bet //남은돈 = 남은돈 - (1~남은돈까지의 무작위 금액을 거는 것에 대한 배팅 금액) }while(remaining>0)//남은 돈이 0보다 클 때까지 do 구문을 계속 반복 } funds = funds - totalBet; //자본 = 자본 - 건돈 총액 //주사위 굴리기 contst hand =[]; for(let roll = 0; roll<3; roll++ ){ //3개의 주사위를 굴림 hand.push(randFace()); // hand 배열에 "crown" 넣음 }
//딴 돈을 가져옴 let winnings = 0; for(let die=0; die<hand.length; die++){ let face = hand[die]; if(bets[face] >0) winnings = winnings + bets[face]; } funds = funds + winnings; }
4.2 자바스크립트 제어문
조건문 if if else switch
반복문 while do while for
4.2.1 제어문의 예외
제어문의 실행 방식을 바꿈 break :루프 중간에 빠져나감 continue : 루프 다음 단계로 바로 건너뜀 return : 루프문 무시 함수 빠져나감 throw : 반드시 처리해야할 예외를 발생(제어문 밖에서도 작용)
//while : 컨디션이 참 같은 값이면 statement 를 실행한다. while(condition) statement //if else if(condition) //condition이 참 같은 값이면 statement1//statement1실행 [else//그렇지 않다면 statement2] //statement2 실행 //do while do statement //statement는 최소한 한 번 실행 while(condition); //condition이 참 같은 값일 동안 반복 실행 //for for([initialization];[condition];[final-expression]) statement /* 루프에 들어가기 전 initialization 실행 condition이 참인 동안 statement 실행 final-expression을 실행한 다음 condition 다시 체크 */
4.2.4 for 루프의 다른 패턴
> 쉼표 연산자를 쓰면 초기화와 마지막 표현식에 여러 문을 결합 할 수 있다.
루프의_다른_패턴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//피보나치 수열 => i,j 동시 선언, 세 변수 동시 조작 for(let temp, i=0, j=1; j<30; temp =i, i =j, j = i + temp) console.log(j); //for 루프에서 조건 생략시 항상 true로 평가되어 무한 루프 for(;;) console.log("i will repeat"); //특이한 for문들.. let s ='3'; //숫자가 들어있는 문자열 for(; s<s.length; s ='' + s); //문자열의 길이가 조건 for(let x = 0.2; x<3.0; x +=0.2) //제어변수가 정수가 아님 console.log(x); for(; !player.isBroke;) //조건에 객체 프로퍼티 사용 console.log('still playing');
4.2.5 switch 문
for 문이 두가지 중 하나를 선택하는 경우라면 switch는 조건 하나로 여러 가지 중 하나를 선택