웹게임으로 배우는 vue 2

웹게임으로 배우는 vue 숫자야구

vue, webpack 설치

  1. npm init
  2. npm install vue
  3. npm install webpack webpack-cli -D
    • -D 대신 --save-dev 사용 가능
  4. webpack.config.js 파일 생성
    기본으로 들어가는 webpack.config.js 세팅
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    const path = require('path'); // node에서 도와주는 모듈. 절대경로 기재할 때 사용.

    module.exports = {
    mode: 'development',
    devtool: 'eval',
    entry: {
    app: path.join(__dirname, 'main.js'),// 하나로 합칠, 가장 대표가 되는 파일
    },
    resolve: {
    extensions: ['.js', '.vue'],
    },
    module: {
    rules: [{
    test: /\.vue$/,
    use: 'vue-loader',
    }],
    },
    plugins: [],
    output: {
    // filename: '[name].js' // 이렇게 해줘도 됨.
    filename: 'app.js', // 최종 결과물
    path: path.join(__dirname, 'dist') // 현재 경로 접근
    },
    }
    • mode: 개발할 때 development, 배포할 때 production
    • devtool: eval로 진행하면 속도가 더 빠르다. 배포할 때는 hidden-source-map
    • resolve: 확장자 처리할 때 사용. extensions에 넣어주면 import할 때 확장자 생략 가능하다.
  5. main.js 세팅
    1
    2
    3
    4
    import Vue from 'vue';
    import NumberBaseball from './NumberBaseball';

    new Vue(NumberBaseball).$mount('#root');
    1
    2
    3
    const app = new Vue({
    el: '#root',
    });
    동일한 코드.
  6. NumberBaseball.vue 세팅
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <templeate>
    <div></div>
    </templeate>

    <script>
    export default {};
    </script>
    <style>
    </style>

숫자야구

코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<template>
<div>
<h1>{{result}}</h1>
<form @submit.prevent="onSubmitForm">
<input ref="answer" minlength="4" maxlength="4" v-model="value" />
<button type="submit">입력</button>
</form>
<div>시도: {{tries.length}}</div>
<ul>
<li v-for="t in tries" :key="t.try">
<div>{{t.try}}</div>
<div>{{t.result}}</div>
</li>
</ul>
</div>
</template>

<script>
const getNumbers = () => {
const candidates = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const array = [];
for (let i = 0; i < 4; i += 1) {
const chosen = candidates.splice(Math.floor(Math.random() * (9 - i)), 1)[0];
array.push(chosen);
}
return array;
};

export default {
data() {
return {
answer: getNumbers(), // ex) [1,5,3,4]
tries: [], // 시도 수
value: '', // 입력
result: '', // 결과
}
},
methods: {
onSubmitForm() {
if (this.value === this.answer.join('')) { // 정답 맞췄으면
this.tries.push({
try: this.value,
result: '홈런',
});
this.result = '홈런';
alert('게임을 다시 실행합니다.');
this.value = '';
this.answer = getNumbers();
this.tries = [];
this.$refs.answer.focus();
} else { // 정답 틀렸을 때
if (this.tries.length >= 9) { // 10번째 시도
this.result = `10번 넘게 틀려서 실패! 답은 ${this.answer.join(',')}였습니다!`;
alert('게임을 다시 시작합니다.');
this.value = '';
this.answer = getNumbers();
this.tries = [];
this.$refs.answer.focus();
}
let strike = 0;
let ball = 0;
const answerArray = this.value.split('').map(v => parseInt(v));
for (let i = 0; i < 4; i += 1) {
if (answerArray[i] === this.answer[i]) { // 숫자 자릿수 모두 정답
strike++;
} else if (this.answer.includes(answerArray[i])) { // 숫자만 정답
ball++;
}
}
this.tries.push({
try: this.value,
result: `${strike} 스트라이크, ${ball} 볼입니다.`,
});
this.value = '';
this.$refs.answer.focus();
}
}
}
};
</script>

<style>
</style>
  • prevent.default@submit.prevent으로 바꿔 코드를 줄일 수 있다.
  • v-for: 지정한 뷰 데이터의 개수만큼 해당 HTML 태그를 반복 출력한다.

REFERENCE
인프런 온라인 강의 웹게임으로 배우는 vue _ 조현영 강사님

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer