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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| <template> <div id="app"> <div id="res" v-if="win">游戏结束,获胜者是:{{ winner }}</div> <div class="row"> <cell @click="onclickCell(0, $event)" :n="n" /> <cell @click="onclickCell(1, $event)" :n="n" /> <cell @click="onclickCell(2, $event)" :n="n" /> </div> <div class="row"> <cell @click="onclickCell(3, $event)" :n="n" /> <cell @click="onclickCell(4, $event)" :n="n" /> <cell @click="onclickCell(5, $event)" :n="n" /> </div> <div class="row"> <cell @click="onclickCell(6, $event)" :n="n" /> <cell @click="onclickCell(7, $event)" :n="n" /> <cell @click="onclickCell(8, $event)" :n="n" /> </div> </div> </template>
<script> import cell from "./cell"; export default { data() { return { cells: [ [1, 1, 1], [1, 1, 1], [1, 1, 1], ], /* 写成如下没带逗号出现bug,影响到n的赋值,但是如下代码null批量替换成1后代码也可以运行 cells: [[null, null, null] [(null, null, null)]
[(null, null, null)]], */ n: 0, win: false, winner: null, }; }, components: { cell }, methods: { onclickCell(i, text) { console.log(`${i}号被点击,内容是${text}`); //插入变量是用反单引号括起来 this.cells[Math.floor(i / 3)][i % 3] = text; this.n = this.n + 1; this.tell(); if (this.win === true) { //此处误写掉括号,一直判定成true this.winner = text; console.log(`获胜者是${text}`); } else { console.log("胜负未定"); } }, tell() { const cells = this.cells; for (let i = 0; i < 2; i++) { if ( cells[i][0] === cells[i][1] && cells[i][0] === cells[i][2] && cells[i][0] !== 1 ) { this.win = true; } } for (let j = 0; j < 2; j++) { if ( cells[0][j] === cells[1][j] && cells[0][j] === cells[2][j] && cells[0][j] !== 1 ) { this.win = true; } } if ( cells[0][0] !== 1 && cells[2][2] == cells[0][0] && cells[1][1] === cells[2][2] ) { this.win = true; } if ( cells[0][2] !== 1 && cells[1][1] == cells[2][0] && cells[0][2] === cells[1][1] ) { this.win = true; } }, }, }; </script>
<style> .row { display: flex; justify-content: center; align-items: center; } #res { border: 1px solid red; background: lightblue; position: absolute; height: 374px; width: 100%; display: flex; justify-content: center; align-items: center; } </style>
|