[vue]가위바위보 게임 만들기[2]

박망키·2022년 2월 14일
0
post-thumbnail

1에서 가위바위보가 연속적으로 바뀌어 나오게 하는건 만들었다. 이제 버튼을 눌러서 비교하는걸 만들어야한다..!

2. 버튼을 만들고 누르면 가위바위보가 멈추게 하자.

이미 돌고 있는 change()를 멈추게 하기위해 변수를 만들어 if/else로 한번 더 감싸서 멈출수 있게 만들었다.멈추었을때 현재 화면에 나오는거랑 내가 누른것을 확인하기위해 콘솔을 찍어보고 일단 무승부까지 출력할수 있게 만들어봤다

<template>
  <Layout :isFooter="false">
    <div class="c-inner">
      <p class="rival">{{ list[moveindex] }}</p>
      <button v-for="item in list" :key="item.i" @click="choice(item)">{{item}}</button>
    </div>
  </Layout>
</template>

<script>
export default {
  data() {
    return {
      list: ["✌️", "✊", "🖐"],
      index: 0,
      myChoice:'',
    };
  },
  
  methods: {
    change() {
      if(this.myChoice==''){//버튼을 누르기 전
        this.index++;
        console.log(this.index);
        if(this.index<this.list.length-1){
          setTimeout(()=>{this.change()},100)
          
        }
        else{
          this.index=-1
          setTimeout(()=>{this.change()},100)
        }
      }
      else{//버튼이 누른 후
        console.log('현재화면에 보이는 list의 index : '+this.index)
        console.log('화면에 보이는거'+this.list[this.index])
        console.log('내가누른거'+this.myChoice)
        
        if(this.list[this.index]==this.myChoice){//무승부
          console.log('무승부입니다')
        }
      }
      
    },
    choice(value){
      this.myChoice=value;
    }
  },
  mounted() {
      this.change();
    
  },
  computed:{
    moveindex(){
      if(this.index==0){
        return 0
      }
      else if(this.index==1){
        return 1
      }
      else{
        return 2
      }
    }
  }
};
</script>

결과화면

오 그럴싸 하다 잘찍히는것 같다 ..! 라고 생각했지만

??? ㅎ????
change()함수에 else{} 가 this.index=-1까지 실행되고 setTimeout()이 실행되기전 그 1초 사이에 누르면 저렇게 인덱스가 -1로 떠버리는 것이다 ㅎ...ㅎ....이러면 비교를 할수가 없따
setTimeout을 없애고 그냥 실행하면 될까 했더니 ㅎㅎ...보자기가 안나온다
그래서 이렇게 if/else밖에 묶었더니 보이기엔 괜찮은데 계속 눌러보니 빛의속도로 -1이 찍힌다
그래서 -1도 대응을 해야했다..(인덱스로 비교하기위해 choice()에 인자를 바꿨다.

*매개변수(parameter)와 전달인자(argument)
종종 매개변수(parameter)와 전달인자(argument)는 적당히 섞어서 쓰이기도 하는데, 이 경우 문맥에 따라 의미를 달리해서 해석되기도 한다. 하지만 엄밀히 말해서 매개변수는 함수의 정의부분에 나열되어 있는 변수들을 의미하며, 전달인자는 함수를 호출할때 전달되는 실제 값을 의미한다. 이같은 의미를 명확히 하기 위해 매개변수는 변수(variable)로, 전달인자는 값(value)으로 보는 것이 일반적이다.

들어가는 실제 값을 바꾼거니까 인자 맞겠지?
data(){return{}}에 결과를 보여줄 result도 생성했다.
다 잘되는데 this.index가 0일때 콘솔엔 찍히는데 change()함수가 else로 넘어가질 않길래 myChoice 초기값을 null로 하고 if/else를 걸었더니 작동한다
this.index가 0일때 왜 else로 넘어가지 않았을까

<template>
  <Layout :isFooter="false">
    <div class="c-inner">
      <p class="rival">{{ list[moveindex] }}</p>
      <button
        v-for="(item, index) in list"
        :key="item.i"
        @click="choice(index)"
        class="btn"
      >
        {{ item }}
      </button>
      <p>{{ result }}</p>
    </div>
  </Layout>
</template>

<script>
export default {
  data() {
    return {
      list: ["✌️", "✊", "🖐"],
      index: 0,
      myChoice: null,
      result: ""
    };
  },

  methods: {
    change() {
      if (this.myChoice == null) {
        //버튼을 누르기 전
        this.index++;
        setTimeout(() => {
          if (this.index < this.list.length - 1) {
            this.change();
          } else {
            this.index = -1;
            this.change();
          }
        }, 100);
      } else {
        //버튼을누른 후
        if (this.index == 0) {
          if (this.myChoice == 0) {
            this.result = "비겼다";
          } else if (this.myChoice == 1) {
            this.result = "이겼다";
          } else {
            this.result = "졌다";
          }
        } else if (this.index == 1) {
          if (this.myChoice == 0) {
            this.result = "졌다";
          } else if (this.myChoice == 1) {
            this.result = "비겼다";
          } else {
            this.result = "이겼다";
          }
        } else if (this.index == 2) {
          if (this.myChoice == 0) {
            this.result = "이겼다";
          } else if (this.myChoice == 1) {
            this.result = "졌다";
          } else {
            this.result = "비겼다";
          }
        } else {
          //-1일때
          if (this.myChoice == 0) {
            this.result = "이겼다";
          } else if (this.myChoice == 1) {
            this.result = "졌다";
          } else {
            this.result = "비겼다";
          }
        }
      }
    },
    choice(index) {
      this.myChoice = index;
    }
  },
  mounted() {
    this.change();
  },
  computed: {
    moveindex() {
      if (this.index == 0) {
        return 0;
      } else if (this.index == 1) {
        return 1;
      } else {
        return 2;
      }
    }
  }
};
</script>

결과
구현하긴했지만 index=-1가 찝찝하다 . 영 깔끔하지 않아서 change()를 더 깔끔하게 바꿀방법을 고민해 봐야겠다.

profile
무럭무럭 자라는 망키

0개의 댓글