wuheng 1 年之前
父節點
當前提交
00a6ec9179

+ 1 - 0
package.json

@@ -2,6 +2,7 @@
   "name": "gobang",
   "version": "0.1.0",
   "private": true,
+  "homepage": "./",
   "dependencies": {
     "@testing-library/jest-dom": "^5.16.5",
     "@testing-library/react": "^13.4.0",

+ 19 - 3
src/App.js

@@ -13,14 +13,26 @@ function App() {
   const [roomData, updateRoomData] = useState("")
   const [socket, setSocket] = useState(null)
   const [userName, setUsername] = useState("")
+
+  const [scrollWidth, setScrollWidth] = useState(document.body.scrollWidth)
+  const [scrollHeight, setScrollHeight] = useState(document.body.scrollHeight)
+
+  useEffect(()=>{
+    if ( scrollWidth > 1024 || scrollHeight > 1200 ) {
+      document.querySelector("html").style.fontSize = "24px";
+    } else {
+      document.querySelector("html").style.fontSize = (scrollWidth / 375) * 10 + "px"
+    }
+  }, [scrollWidth, scrollHeight])
+
   useEffect(()=>{
     if ( userName === "" ) return;
-    const socket = new WebSocket(`ws://127.0.0.1:8080/game/${userName}`) 
+    const socket = new WebSocket(`ws://39.105.160.25:11022/game/${userName}`) 
     socket.onopen = ()=>{
       socket.send(JSON.stringify( {instruct: HALL} ))
     }
     socket.onerror = ( error )=>{
-      console.log( error )
+      window.location.reload()
     }
     socket.onmessage = (msg)=>{
       const revMsg = JSON.parse(msg.data)
@@ -32,9 +44,13 @@ function App() {
       
     }
     socket.onclose = (e)=>{
-      console.log(e)
+      
     }
     setSocket(socket)
+    window.onresize = ()=>{
+      setScrollWidth(document.body.scrollWidth)
+      setScrollHeight(document.body.scrollHeight)
+    }
   }, [userName])
   
   return (

+ 2 - 1
src/Constant.js

@@ -2,4 +2,5 @@ const ROOM = "room"
 const HALL = "hall"
 const BEGIN = "begin"
 const POINT = "point"
-export  { ROOM, HALL, BEGIN, POINT }
+const WIN = "win"
+export  { ROOM, HALL, BEGIN, POINT, WIN }

+ 29 - 0
src/component/Dialog.css

@@ -0,0 +1,29 @@
+.dialog-container{
+    z-index: 1;
+    position: absolute;
+    transform: translate(-50%,-50%);
+    top: 50%;
+    left: 50%;
+    background: #e7e6e6;
+    width: 100%;
+    height: 50%;
+    border: 0.5rem solid #45920d;
+}
+.dialog-container .dialog-title{
+    padding: 2rem;
+}
+.dialog-container .dialog-body {
+    width: 100%;
+    height: 50%;
+}
+.dialog-container .dialog-body span {
+    display: inline-block;
+    padding: 3rem;
+}
+.dialog-container .dialog-body button {
+    position: absolute;
+    right: 3rem;
+    bottom: 2rem;
+    width: 6rem;
+    height: 2rem;
+}

+ 19 - 0
src/component/Dialog.js

@@ -0,0 +1,19 @@
+import "./Dialog.css"
+
+const Dialog = function({ show ,title, content, confirm}){
+    return (<>
+        <div style={{display: show ? "block" : "none"}} className="dialog-container">
+            <h3 className="dialog-title">{title}</h3>
+            <div className="dialog-body">
+                <span>{content}</span>
+                <button onClick={()=>{
+                    if ( confirm ) {
+                        confirm()
+                    }
+                }}>确认</button>
+            </div>
+        </div>
+    </>)
+}
+
+export default Dialog

+ 1 - 3
src/component/Navigation.css

@@ -23,9 +23,7 @@
     bottom: 2rem;
     border: 1px solid black;
 }
-/* .nav-item{
-    border: 0.01rem solid red;
-} */
+
 .beginGame{
     width: 8rem;
     margin: 0 auto;

+ 32 - 14
src/component/Navigation.js

@@ -30,33 +30,51 @@ const Navigation = function () {
                     <img className='avatar' alt='' src={require("../assets/left.png")} />
                     <div className='text-box'>
                         <span className='user-text'>{(() => {
-                            switch (room.status) {
-                                case 0: return '未开始'
-                                case 1: return '请黑方落子'
-                                case 2: return '请白方落子'
-                                default: return '未知!'
-                            }
+                            const localname = sessionStorage.getItem("username")
+                            if (localname === room.whiteUsername) return "对手"
+                            else return "黑棋"
                         })()}</span>
                         <span className='user-text'>{room.backUsername}</span>
                     </div>
                 </div>
                 <div className='nav-item'>
                     <button onClick={beginGame}
-                        disabled={room.status === 0 ? false : true}
+                        disabled={(()=>{
+                            const localname = sessionStorage.getItem("username")
+                            if ( room.status > 0 ) {
+                                return true;
+                            } else if ( room.backState === 2 && 
+                                localname === room.backUsername ) {
+                                return true      
+                            } else if ( room.whiteState === 2 && 
+                                localname === room.whiteUsername ) {
+                                return true      
+                            } else {
+                                return false
+                            }
+                        })()}
                         className='beginGame'>{(() => {
-                            return room.status === 0 ? '开始游戏' : '游戏进行中'
+                            if ( room.backState === 2 && room.whiteState !== 2 ) {
+                                return '等待白棋确认'
+                            } else if ( room.whiteState === 2 && room.backState !== 2 ) {
+                                return '等待黑棋确认'
+                            } else {
+                                switch (room.status) {
+                                    case 0: return '开始游戏'
+                                    case 1: return '请黑方落子'
+                                    case 2: return '请白方落子'
+                                    default: return '加油!'
+                                }
+                            } 
                         })()} </button>
                 </div>
                 <div className='nav-item'>
                     <img className='avatar right-avatar' alt='' src={require("../assets/right.png")} />
                     <div className='text-box'>
                         <span className='user-text'>{(() => {
-                            switch (room.status) {
-                                case 0: return '未开始'
-                                case 1: return '请黑方落子'
-                                case 2: return '请白方落子'
-                                default: return '未知情况'
-                            }
+                            const localname = sessionStorage.getItem("username")
+                            if (localname === room.backUsername) return "对手"
+                            else return "白棋"
                         })()}</span>
                         <span className='user-text'>{room.whiteUsername}</span>
                     </div>

+ 0 - 5
src/views/Checkerboard.css

@@ -1,11 +1,6 @@
 .checkerboard{
     position: relative;
 }
-@media screen and (max-width: 414px) {
-    html {
-        font-size: 10px;
-    }
-}
 .black{
     background-image: url('/src/assets/point.png');
     background-position: 0.08rem -1.5rem;

+ 123 - 114
src/views/Checkerboard.js

@@ -1,162 +1,171 @@
 import { useContext, useEffect, useState } from 'react'
 import './Checkerboard.css'
-import { POINT } from '../Constant';
+import { POINT, WIN } from '../Constant';
 import tableData from './CheckerboardData'
 import Navigation from '../component/Navigation'
 import RevRoomContext from '../provider/RevRoomContext';
 import GlobalSocketContext from '../provider/GlobalSocketContext';
+import Dialog from '../component/Dialog';
 const bgline = [
   ["x", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"],
   ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"]
 ];
-const constant = {a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10, k:11, l:12, m:13, n:14}
+const constantRev = {
+  0: "x",
+  1: "a",
+  2: "b",
+  3: "c",
+  4: "d",
+  5: "e",
+  6: "f",
+  7: "g",
+  8: "h",
+  9: "i",
+  10: "j",
+  11: "k",
+  12: "l",
+  13: "m",
+  14: "n"
+}
 const Checkerboard = function () {
+  const [dialogData, setDialog] = useState({
+    title: "游戏提示",
+    content: "xx获得游戏胜利!!",
+    show: false
+  })
   const { room, data } = useContext(RevRoomContext)
   const socket = useContext(GlobalSocketContext)
   const [table, updateTable] = useState(tableData)
-  const [userStatus, setGameStatus] = useState(0)
-  useEffect(()=>{
+  useEffect(() => {
     updateTable(data)
   }, [data])
   const goBangTouchEvent = function (x, y, value) {
-    if ( room.status === 0 ) {
-      console.log( "棋盘未开始呢!!" )
+    
+    //判断对方是否赢了
+    if ( room.winUsername !== "" ) {
+      dialogMsg( `${room.winUsername} 赢得了此轮竞技` )
+      return ;
+    }
+
+    if (room.status === 0) {
+      dialogMsg( "此轮对弈还未开始呢!" )
       return
     }
+
     if (value === 0) {
       data[x][y] = room.status
+      updateTable(data)
       socket.send(JSON.stringify({
-          instruct: POINT,
-          data:data
+        instruct: POINT,
+        data: data
       }))
-      if ( userStatus !== 0 ) {
-        win(x, y, table)
+      if (room.status !== 0) {
+        whoAreWin(data)
       }
     } else {
       console.log("此处已经落子了")
     }
   }
-  const win = function(x, y, table){
-    //横向
-    if( getXValue(x, y, table) ) {
-      console.log( userStatus === 1 ? "黑方赢了" : "白方赢了" )
-      setGameStatus(0)
-    }
-    //纵向
-    if( getYValue(x, y, table) ) {
-      console.log( userStatus === 1 ? "黑方赢了" : "白方赢了" )
-      setGameStatus(0)
-    }
-    //斜向
-    if ( getXyValue(x, y, table) ) {
-      console.log( userStatus === 1 ? "黑方赢了" : "白方赢了" )
-      setGameStatus(0)
-    }
-  }
-  const getXValue = function(x, y, table){
-    //向左遍历
-    let n = 0
-    for (let i = y; i < table[x].length; i++) {
-      if (table[x][i] === userStatus) {
-        n++;
-      } else if (table[x][i] === 0){
-        break
-      } else {
-        n=0
+  const whoAreWin = (table) => {
+    let blackWin = false
+    let whiteWin = false
+    //撇向
+    for (let x = 5; x < 14; x++) {
+      for (let y = 0; y <= 9; y++) {
+        let white = 0
+        let black = 0
+        let step = 0
+        while (step < 5) {
+          //console.log(`坐标: ${x - step} ${y + step}`)
+          if (table[constantRev[x - step]][y + step] !== 0) {
+            if (table[constantRev[x - step]][y + step] === 1) black++
+            if (table[constantRev[x - step]][y + step] === 2) white++
+          }
+          step++
+        }
+        if (black >= 5) blackWin = true
+        if (white >= 5) whiteWin = true
       }
     }
-    if ( n >= 5 ) return true
-    //向右遍历
-    n = 0
-    for (let i = y; i > 0; i--) {
-      if (table[x][i] === userStatus) {
-        n++;
-      } else if (table[x][i] === 0){
-        break
-      } else {
-        n=0
+    //捺向
+    for (let x = 10; x > 0; x--) {
+      for (let y = 0; y <= 9; y++) {
+        let white = 0
+        let black = 0
+        let step = 0
+        while (step < 5) {
+          //console.log( `坐标: ${x + step} ${y + step}` )
+          if (table[constantRev[x + step]][y + step] !== 0) {
+            if (table[constantRev[x + step]][y + step] === 1) black++
+            if (table[constantRev[x + step]][y + step] === 2) white++
+          }
+          step++
+        }
+        if (black >= 5) blackWin = true
+        if (white >= 5) whiteWin = true
       }
     }
-    if ( n >= 5 ) return true
-    return false
-  }
-  const getYValue = function(x, y, table){
-    //从点击点向上遍历
-    let n = 0
-    const rTable = Object.keys(table).reverse();
-    for (const key in rTable) {
-      if ( constant[rTable[key]] <=  constant[x] ) {
-        if ( table[rTable[key]][y] === userStatus ) {
-          n++
-        } else if ( table[rTable[key]][y] === 0 ) {
-          break
-        } else {
-          n=0
+    //纵向
+    for (let x = 1; x <= 14; x++) {
+      for (let y = 0; y <= 9; y++) {
+        let step = 0
+        let white = 0
+        let black = 0
+        while (step < 5) {
+          //console.log( `坐标: ${x} ${y + step}` )
+          if (table[constantRev[x]][y + step] !== 0) {
+            if (table[constantRev[x]][y + step] === 1) black++
+            if (table[constantRev[x]][y + step] === 2) white++
+          }
+          step++
         }
+        if (black >= 5) blackWin = true
+        if (white >= 5) whiteWin = true
       }
     }
-    if ( n >= 5 ) return true
-    //从点击点向下遍历
-    n=0
-    for (const key in table) {
-      if (Object.hasOwnProperty.call(table, key)) {
-        if ( constant[key] >=  constant[x] ) {
-          if ( table[key][y] === userStatus ) {
-            n++
-          } else if ( table[key][y] === 0 ) {
-            break
-          } else {
-            n=0
+    //横向
+    for (let y = 0; y <= 13; y++) {
+      for (let x = 1; x <= 10; x++) {
+        let step = 0
+        let white = 0
+        let black = 0
+        while (step < 5) {
+          //console.log( `坐标: ${y} ${x+step}` )
+          if (table[constantRev[x + step]][y] !== 0) {
+            if (table[constantRev[x + step]][y] === 1) black++
+            if (table[constantRev[x + step]][y] === 2) white++
           }
+          step++
         }
+        if (black >= 5) blackWin = true
+        if (white >= 5) whiteWin = true
       }
     }
-    if ( n >= 5 ) return true
-    return false
-  }
-  const getXyValue = function(x, y, table){
-    //向左上角遍历
-    let n = 0 , flag = false, k = y+1
-    const tableKey = Object.keys(table).reverse();
-    for (let i = 0; i < 14; i++) {
-      if ( tableKey[i] === x ) {
-        flag = true
-      }
-      if ( flag === false ) continue
-      k--
-      if ( table[tableKey[i]][k] === userStatus ) {
-        n++
-      } else if (table[tableKey[i]][k] === 0) {
-        break;
-      } else {
-        n=0
+    if (blackWin === true || whiteWin === true) {
+      const who = blackWin === true ? room.backUsername : room.whiteUsername
+      if ( who ) {
+        socket.send(JSON.stringify({
+          instruct: WIN,
+          winUser: who
+        }))
       }
+      dialogMsg( `${who} 赢得了此轮竞技!` )
     }
-    if ( n >= 5 ) return true
-    
-    //向左下角遍历
-    n = 0 ;  k = y-1; flag = false; 
-    const rTableKey = Object.keys(table)
-    for (let i = 0; i < table[x].length; i++ ) {
-      if ( rTableKey[i] === x ) {
-        flag = true
-      }
-      if ( flag === false ) continue
-      k++
-      if ( table[rTableKey[i]][k] === userStatus ) {
-        n++
-      } else if (table[rTableKey[i]][k] === 0) {
-        break;
-      } else {
-        n=0
+  }
+  const dialogMsg = (message) => {
+    setDialog({
+      ...dialogData,
+      content: message,
+      show: true,
+      confirm: () => {
+        setDialog({ ...dialogData, show: false })
       }
-    }
-    if ( n >= 5 ) return true
-    return false
+    })
   }
   return (
     <div className='body'>
-      <Navigation updateTable={updateTable} gameStatus={setGameStatus} status={userStatus} />
+      <Dialog {...dialogData} />
+      <Navigation />
       <div className='center'>
         <div className='checkerboard'>
           <div className='board' >

+ 1 - 0
src/views/Login.css

@@ -9,6 +9,7 @@
     width: 100%;
     margin-bottom: 1rem;
     height: 2rem;
+    padding-left: 1rem;
 }
 .login button {
     width: 100%;

+ 6 - 3
src/views/Login.js

@@ -1,15 +1,18 @@
 import { useState } from "react"
 import "./Login.css"
 const Login = function({setUsername}){
-    const [username, updateUsername] = useState("")
+    const [username, updateUsername] = useState(
+        sessionStorage.getItem("username") ? 
+        sessionStorage.getItem("username") : ""
+    )
     return (<>
         <div className="login">
             <img alt="gobang" src={require("../assets/point.png")} />
             <input onChange={(e)=>{
-                console.log(e.target.value)
                 updateUsername(e.target.value)
-            }} />
+            }} value={username} />
             <button onClick={()=>{
+                sessionStorage.setItem("username", username)
                 setUsername(username)
             }} >设置用户名</button>
         </div>

+ 8 - 13
src/views/RoomList.css

@@ -1,12 +1,17 @@
-
+.list-title{
+    margin-left: 2rem;
+}
+.grid-list{
+    display: flex;
+    flex-wrap: wrap;
+}
 .list{
     position: absolute;
     transform: translate(-50%,-50%);
     top: 50%;
     left: 50%;
     width: 30rem;
-    display: flex;
-    flex-wrap: wrap;
+    
 }
 .room-list{
     width: 9rem;
@@ -24,13 +29,3 @@
     padding-top: .8rem;
     padding-bottom: .5rem;
 }
-
-@media screen and (max-width:414px) and (min-width:375px)  {
-    .list{
-            width: 36rem;
-        }
-    .room-list{
-        width: 12rem;
-        margin-top: 1rem;
-    }
-}

+ 8 - 4
src/views/RoomList.js

@@ -20,13 +20,17 @@ const RoomList = function () {
     return (
         <>
             <div className='list'>
+            <h3 className='list-title'>在线博弈五子棋</h3>
+                <div className='grid-list'>
                 {(() => {
                     if ( roomList ) {
                         return roomList.data.map((item) => {
                             return (<div onClick={()=>{
                                 comeIn(item)
                             }} key={item.roomId} className='room-list'>
-                                <div className='room-list-item'>
+                                <div className='room-list-item' style={{
+                                        border: (item.backState === 2 && item.whiteState === 2) ? 
+                                        "3px solid green" : "1px solid black"}}>
                                     <span className='room-list-title'>黑方: {(()=>{
                                         if ( item.backState !== 0 ) {
                                             return item.backUsername
@@ -41,9 +45,9 @@ const RoomList = function () {
                                             return enuString[item.whiteState]
                                         }
                                     })()}</span>
-                                    <span className='room-list-title'>状态: {(()=>{
+                                    <span className='room-list-title' >状态: {(()=>{
                                         if ( item.backState === 2 && item.whiteState === 2 ) {
-                                            return "博弈中..."
+                                            return "博弈中"
                                         } else if (item.backState === 0 && item.whiteState === 0 ) {
                                             return "未开始"
                                         } else if (item.backState === 1 && item.whiteState === 1 ) {
@@ -62,10 +66,10 @@ const RoomList = function () {
                                     })()}</span>
                                 </div>
                             </div> )
-
                         })
                     }
                 })()}
+                </div>
             </div>
         </>
     )