iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
Modern Web

初學者前端應用30天系列 第 27

[DAY27]前端井字遊戲實作(下)

  • 分享至 

  • xImage
  •  

我們繼續來實作井字遊戲(人對電腦)的先手問題、電腦對手和勝負判斷的功能。

電腦對手

因為我的寫code功力沒有很強,所以這次做的電腦對手是用亂數下的。
我們先要知道電腦下棋的時機,是要在玩家下棋完後電腦才要下,所以我們要在監聽區塊裡執行電腦下棋的function

    $("#div1").on( "click", function() {
        if ((that.selected.indexOf(1) == -1)) {
            $("#div1").text(localStorage.getItem("player"))//<--玩家下完
            that.selected.push(1)
            that.getRandom()//<--電腦下棋的function
        }
    });

接著來做亂數AI

當輪到電腦下棋時,我們用random找出要下的地方,再用while檢查陣列是否有重覆,找出沒被下過的地方,找到後檢查棋盤是否被下滿,若沒有則會在random出來的區塊中下電腦所屬的OX,並往陣列推值紀錄現在已經下過的地方。

    getRandom() {
        const that = this;
        var random = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        while (that.selected.indexOf(random) != -1) {
            random = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        }
        if (that.selected.length < 9) {
            switch (random) {
                case 1:
                    $("#div1").text(localStorage.getItem("ai"))
                    that.selected.push(1)
                    break;
                case 2:
                    $("#div2").text(localStorage.getItem("ai"))
                    that.selected.push(2)
                    break;
                case 3:
                    $("#div3").text(localStorage.getItem("ai"))
                    that.selected.push(3)
                    break;
                case 4:
                    $("#div4").text(localStorage.getItem("ai"))
                    that.selected.push(4)
                    break;
                case 5:
                    $("#div5").text(localStorage.getItem("ai"))
                    that.selected.push(5)
                    break;
                case 6:
                    $("#div6").text(localStorage.getItem("ai"))
                    that.selected.push(6)
                    break;
                case 7:
                    $("#div7").text(localStorage.getItem("ai"))
                    that.selected.push(7)
                    break;
                case 8:
                    $("#div8").text(localStorage.getItem("ai"))
                    that.selected.push(8)
                    break;
                case 9:
                    $("#div9").text(localStorage.getItem("ai"))
                    that.selected.push(9)
                    break;
                default:
                    break;
            }
        }
    },

先手問題

在遊戲開始前要先,判斷是玩家先下還是電腦先下,在選擇OX時就要決定誰先下,所以要在選擇OX的function做判斷。

    x() {
        $("#all").css('display','block');
        $("#select").css('display','none'); 
        $("#exit").css('display','block'); 
        localStorage.setItem("player", "x")
        localStorage.setItem("ai", "o")
        this.whofirst();//<--決定先手function
    },
    o() {
        $("#all").css('display','block');
        $("#select").css('display','none'); 
        $("#exit").css('display','block'); 
        localStorage.setItem("player", "o")
        localStorage.setItem("ai", "x")
        this.whofirst();//<--決定先手function
    },

判斷方法為,random一個1或2的結果,若等於2則電腦先手。

    whofirst(){
        var who = Math.floor(Math.random() * (2 - 1 + 1)) + 1;
        if (who == 2) {
            this.getRandom()
        }
    },

勝負判斷

我們要先找出判斷勝負的時機,在玩家下完和電腦下完都要做判斷。

玩家下棋的地方(9個監聽都要做):

    $("#div1").on( "click", function() {
        if ((that.selected.indexOf(1) == -1)) {
            $("#div1").text(localStorage.getItem("player"))
            that.selected.push(1)
            that.judgment()//<--勝負判斷
            that.getRandom()
        }
    });

電腦下棋的地方(9個case都要做):

        case 1:
            $("#div1").text(localStorage.getItem("ai"))
            that.selected.push(1)
            that.judgment()//<--勝負判斷
            break;

先在data裡新增兩個值名稱為xwin和owin,用來判斷是O還是X勝利

  data:()=>({
      selected:[],
      xwin:null,
      owin:null,
  }),

接著製作勝利條件,判斷區塊內的OX值,
勝利條件為
123區塊相連
456區塊相連
789區塊相連
147區塊相連
258區塊相連
369區塊相連
159區塊相連
357區塊相連
這8個勝利條件,若有任一條件達成,則會另owin或xwin為true。

    judgment() {
        const that = this;

        var xhaveone = (($("#div1").text()) == "x")
        var xhavetwo = (($("#div2").text()) == "x")
        var xhavethree = (($("#div3").text()) == "x")
        var xhavefour = (($("#div4").text()) == "x")
        var xhavefive = (($("#div5").text()) == "x")
        var xhavesix = (($("#div6").text()) == "x")
        var xhaveseven = (($("#div7").text()) == "x")
        var xhaveeight = (($("#div8").text()) == "x")
        var xhavenine = (($("#div9").text()) == "x")

        var ohaveone = (($("#div1").text()) == "o")
        var ohavetwo = (($("#div2").text()) == "o")
        var ohavethree = (($("#div3").text()) == "o")
        var ohavefour = (($("#div4").text()) == "o")
        var ohavefive = (($("#div5").text()) == "o")
        var ohavesix = (($("#div6").text()) == "o")
        var ohaveseven = (($("#div7").text()) == "o")
        var ohaveeight = (($("#div8").text()) == "o")
        var ohavenine = (($("#div9").text()) == "o")

        var xwin1 = (xhaveone && xhavetwo && xhavethree)
        var xwin2 = (xhavefour && xhavefive && xhavesix)
        var xwin3 = (xhaveseven && xhaveeight && xhavenine)
        var xwin4 = (xhaveone && xhavefour && xhaveseven)
        var xwin5 = (xhavetwo && xhavefive && xhaveeight)
        var xwin6 = (xhavethree && xhavesix && xhavenine)
        var xwin7 = (xhaveone && xhavefive && xhavenine)
        var xwin8 = (xhavethree && xhavefive && xhaveseven)

        var owin1 = (ohaveone && ohavetwo && ohavethree)
        var owin2 = (ohavefour && ohavefive && ohavesix)
        var owin3 = (ohaveseven && ohaveeight && ohavenine)
        var owin4 = (ohaveone && ohavefour && ohaveseven)
        var owin5 = (ohavetwo && ohavefive && ohaveeight)
        var owin6 = (ohavethree && ohavesix && ohavenine)
        var owin7 = (ohaveone && ohavefive && ohavenine)
        var owin8 = (ohavethree && ohavefive && ohaveseven)

        that.xwin = (xwin1 || xwin2 || xwin3 || xwin4 || xwin5 || xwin6 || xwin7 || xwin8)
        that.owin = (owin1 || owin2 || owin3 || owin4 || owin5 || owin6 || owin7 || owin8)
    }
  },

因為我們已經有用陣列記錄所下過的區塊,只需用watch監聽該陣列,並跳出勝利、輸了和平手的訊息。
先判斷是O還是X贏,在比對該符號是電腦還是玩家,就可以跳出勝負訊息。
平手則要在陣列長度為9也就是所有區塊都下滿,且任何一方都沒勝利的條件下,跳出平手訊息。

   selected:{
       immediate:false,
       handler(af,bf){
        const that = this;
        if (that.owin) {
            if (localStorage.getItem("ai") == "o") {
                console.log("aiwin")
                localStorage.clear()
                setTimeout(function() {
                    alert('你輸了');
                    window.location.reload()
                }, 100);
            } else {
                console.log("playerwin")
                localStorage.clear()
                setTimeout(function() {
                    alert('你贏了');
                    window.location.reload()
                }, 100);
            }
        } else if (that.xwin) {
                if (localStorage.getItem("ai") == "x") {
                    console.log("aiwin")
                    localStorage.clear()
                    setTimeout(function() {
                        alert('你輸了');
                        window.location.reload()
                    }, 100);
                } else {
                    console.log("playerwin")
                    localStorage.clear()
                    setTimeout(function() {
                        alert('你贏了');
                        window.location.reload()
                    }, 100);
                }
        }
        if ((that.selected.length == 9) && !(that.xwin) && !(that.owin)) {
            console.log("平手")
            localStorage.clear()
            setTimeout(function() {
                alert('平手了');
                window.location.reload()
            }, 100);
        }
       },
   }

還有一個地方要注意,要在玩家下棋的地方做勝負判斷,當勝負未定時才讓電腦下,不然會發現玩家勝利後電腦還會再下一子的問題。

    $("#div1").on( "click", function() {
        if ((that.selected.indexOf(1) == -1)) {
            $("#div1").text(localStorage.getItem("player"))
            that.selected.push(1)
            that.judgment()
            if(!(that.owin||that.xwin)){//<--新增判斷
                that.getRandom()
            }
        }
    });

以上就是簡單井字遊戲的流程。

附上全程式碼:

<template>
  <div id="base">
    <div id="all">
    </div>
    <div id="select">
        玩家選擇OX
        <br>
        <button id="o" @click="o">O</button>
        <button id="x" @click="x">X</button>
    </div>
    <button id="exit" @click="re">重新遊戲</button>
  </div>
</template>
<script>
// @ is an alias to /src
/*eslint-disable*/
export default {
  components: {
  },
  data:()=>({
      selected:[],
      xwin:null,
      owin:null,
  }),
  watch:{
   selected:{
       immediate:false,
       handler(af,bf){
        const that = this;
        if (that.owin) {
            if (localStorage.getItem("ai") == "o") {
                console.log("aiwin")
                localStorage.clear()
                setTimeout(function() {
                    alert('你輸了');
                    window.location.reload()
                }, 100);
            } else {
                console.log("playerwin")
                localStorage.clear()
                setTimeout(function() {
                    alert('你贏了');
                    window.location.reload()
                }, 100);
            }
        } else if (that.xwin) {
                if (localStorage.getItem("ai") == "x") {
                    console.log("aiwin")
                    localStorage.clear()
                    setTimeout(function() {
                        alert('你輸了');
                        window.location.reload()
                    }, 100);
                } else {
                    console.log("playerwin")
                    localStorage.clear()
                    setTimeout(function() {
                        alert('你贏了');
                        window.location.reload()
                    }, 100);
                }
        }
        if ((that.selected.length == 9) && !(that.xwin) && !(that.owin)) {
            console.log("平手")
            localStorage.clear()
            setTimeout(function() {
                alert('平手了');
                window.location.reload()
            }, 100);
        }
       },
   }
  },
  methods:{

    x() {
        $("#all").css('display','block');
        $("#select").css('display','none'); 
        $("#exit").css('display','block'); 
        localStorage.setItem("player", "x")
        localStorage.setItem("ai", "o")
        this.whofirst();
    },
    o() {
        $("#all").css('display','block');
        $("#select").css('display','none'); 
        $("#exit").css('display','block'); 
        localStorage.setItem("player", "o")
        localStorage.setItem("ai", "x")
        this.whofirst();
    },
    whofirst(){
        var who = Math.floor(Math.random() * (2 - 1 + 1)) + 1;
        if (who == 2) {
            this.getRandom()
        }
    },
    re() {
        localStorage.clear()
        window.location.reload()
    },

    getRandom() {
        const that = this;
        var random = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        while (that.selected.indexOf(random) != -1) {
            random = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
        }
        if (that.selected.length < 9) {
            switch (random) {
                case 1:
                    $("#div1").text(localStorage.getItem("ai"))
                    that.selected.push(1)
                    that.judgment()
                    break;
                case 2:
                    $("#div2").text(localStorage.getItem("ai"))
                    that.selected.push(2)
                    that.judgment()
                    break;
                case 3:
                    $("#div3").text(localStorage.getItem("ai"))
                    that.selected.push(3)
                    that.judgment()
                    break;
                case 4:
                    $("#div4").text(localStorage.getItem("ai"))
                    that.selected.push(4)
                    that.judgment()
                    break;
                case 5:
                    $("#div5").text(localStorage.getItem("ai"))
                    that.selected.push(5)
                    that.judgment()
                    break;
                case 6:
                    $("#div6").text(localStorage.getItem("ai"))
                    that.selected.push(6)
                    that.judgment()
                    break;
                case 7:
                    $("#div7").text(localStorage.getItem("ai"))
                    that.selected.push(7)
                    that.judgment()
                    break;
                case 8:
                    $("#div8").text(localStorage.getItem("ai"))
                    that.selected.push(8)
                    that.judgment()
                    break;
                case 9:
                    $("#div9").text(localStorage.getItem("ai"))
                    that.selected.push(9)
                    that.judgment()
                    break;
                default:
                    break;
            }
        }
    },

    judgment() {
        const that = this;

        var xhaveone = (($("#div1").text()) == "x")
        var xhavetwo = (($("#div2").text()) == "x")
        var xhavethree = (($("#div3").text()) == "x")
        var xhavefour = (($("#div4").text()) == "x")
        var xhavefive = (($("#div5").text()) == "x")
        var xhavesix = (($("#div6").text()) == "x")
        var xhaveseven = (($("#div7").text()) == "x")
        var xhaveeight = (($("#div8").text()) == "x")
        var xhavenine = (($("#div9").text()) == "x")

        var ohaveone = (($("#div1").text()) == "o")
        var ohavetwo = (($("#div2").text()) == "o")
        var ohavethree = (($("#div3").text()) == "o")
        var ohavefour = (($("#div4").text()) == "o")
        var ohavefive = (($("#div5").text()) == "o")
        var ohavesix = (($("#div6").text()) == "o")
        var ohaveseven = (($("#div7").text()) == "o")
        var ohaveeight = (($("#div8").text()) == "o")
        var ohavenine = (($("#div9").text()) == "o")

        var xwin1 = (xhaveone && xhavetwo && xhavethree)
        var xwin2 = (xhavefour && xhavefive && xhavesix)
        var xwin3 = (xhaveseven && xhaveeight && xhavenine)
        var xwin4 = (xhaveone && xhavefour && xhaveseven)
        var xwin5 = (xhavetwo && xhavefive && xhaveeight)
        var xwin6 = (xhavethree && xhavesix && xhavenine)
        var xwin7 = (xhaveone && xhavefive && xhavenine)
        var xwin8 = (xhavethree && xhavefive && xhaveseven)

        var owin1 = (ohaveone && ohavetwo && ohavethree)
        var owin2 = (ohavefour && ohavefive && ohavesix)
        var owin3 = (ohaveseven && ohaveeight && ohavenine)
        var owin4 = (ohaveone && ohavefour && ohaveseven)
        var owin5 = (ohavetwo && ohavefive && ohaveeight)
        var owin6 = (ohavethree && ohavesix && ohavenine)
        var owin7 = (ohaveone && ohavefive && ohavenine)
        var owin8 = (ohavethree && ohavefive && ohaveseven)

        that.xwin = (xwin1 || xwin2 || xwin3 || xwin4 || xwin5 || xwin6 || xwin7 || xwin8)
        that.owin = (owin1 || owin2 || owin3 || owin4 || owin5 || owin6 || owin7 || owin8)
    }
  },
  
  mounted(){
    for(var i = 0;i<9;i++){
        var div = document.createElement("div")
        $(div).attr('id','div'+(i+1));
        $(div).css({
            margin: '1px',
            position: 'relative',
            float: 'left',
            width: '150px',
            height: '150px',
            'background-color': 'rgb(71, 5, 255)',
            'font-size': '100px',
            'text-align': 'center',
            'line-height': '150px',
        });
        $("#all").append(div);
    }
    const that = this
    $("#all").css('display','none');
    $("#exit").css('display','none'); 

    $("#div1").on( "click", function() {
        if ((that.selected.indexOf(1) == -1)) {
            $("#div1").text(localStorage.getItem("player"))
            that.selected.push(1)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div2").on( "click", function() {
        if ((that.selected.indexOf(2) == -1)) {
            $("#div2").text(localStorage.getItem("player"))
            that.selected.push(2)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div3").on( "click", function() {
        if ((that.selected.indexOf(3) == -1)) {
            $("#div3").text(localStorage.getItem("player"))
            that.selected.push(3)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div4").on( "click", function() {
        if ((that.selected.indexOf(4) == -1)) {
            $("#div4").text(localStorage.getItem("player"))
            that.selected.push(4)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div5").on( "click", function() {
        if ((that.selected.indexOf(5) == -1)) {
            $("#div5").text(localStorage.getItem("player"))
            that.selected.push(5)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div6").on( "click", function() {
        if ((that.selected.indexOf(6) == -1)) {
            $("#div6").text(localStorage.getItem("player"))
            that.selected.push(6)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div7").on( "click", function() {
        if ((that.selected.indexOf(7) == -1)) {
            $("#div7").text(localStorage.getItem("player"))
            that.selected.push(7)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div8").on( "click", function() {
        if ((that.selected.indexOf(8) == -1)) {
            $("#div8").text(localStorage.getItem("player"))
            that.selected.push(8)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
    $("#div9").on( "click", function() {
        if ((that.selected.indexOf(9) == -1)) {
            $("#div9").text(localStorage.getItem("player"))
            that.selected.push(9)
            that.judgment()
            if(!(that.owin||that.xwin)){
                that.getRandom()
            }
        }
    });
  },
}
</script>
<style scoped>
    #exit{
        position: absolute;
        left: 30%;
        top:540px
    }
    #o {
        position: relative;
        top:50px;
        margin:5px;
        width: 36px;
        height: 36px;
        background-color: wheat
    }
    #x {
        position: relative;
        width: 36px;
        height: 36px;
        margin:5px;
        top:50px;
        background-color: wheat
    }
    #select {
        position: static; 
        height: 256px;
        background-color: cyan
    }
    #all {
        width: 456px;
        height: 456px;
        background-color: black;
        position: absolute;
        left: 30%;
    }
</style>

上一篇
[DAY26]前端井字遊戲實作(上)
下一篇
[DAY28]vue dr-vue-echarts 圖表套件(上)
系列文
初學者前端應用30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言