Example #1
0
 def post(self, *args, **kwargs):
     userId = self.get_secure_cookie("userId").decode("utf-8")
     cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
     row = cursor.fetchone()
     tableId = row["table_id"]
     roomCache = GameRoomCache[tableId]
     anotherPlayerId = None
     for key in roomCache["playerState"].keys():
         if key != userId:
             anotherPlayerId = key
             break
     roomCache["playerState"][userId]["myTurn"] = False
     roomCache["playerState"][anotherPlayerId]["myTurn"] = False
     roomCache["totalGameTime"] += 1
     cursor.execute(
         "UPDATE user_info SET game_time=game_time+1,draw_time=draw_time+1 WHERE user_id=%s OR user_id=%s",
         (userId, anotherPlayerId))
     cursor.execute(
         "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
         tableId)
     # 将玩家状态改为在线,并通知其在线好友刷新friendList
     cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
     # 刷新相关好友列表
     refreshRelativeFriendList([userId, anotherPlayerId])
     # 提醒前端和棋
     for key in GameRoomSocketCache[tableId]:
         GameRoomSocketCache[tableId][key].gameDraw()
Example #2
0
    def post(self, *args, **kwargs):
        userId = self.get_secure_cookie("userId")
        if userId is None:
            returnJson = {"status": "00"}
            self.write(json.dumps(returnJson, ensure_ascii=False))
        else:
            userId = userId.decode("utf-8")
            cursor.execute(
                "UPDATE user SET login_state=0,state=0 WHERE user_id=%s",
                userId)
            # 查看是否关闭了GameRoom页面如果没有关闭则发送websocket关闭
            cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
            row = cursor.fetchone()
            tableId = row["table_id"]
            if tableId in GameRoomSocketCache.keys():
                if userId in GameRoomSocketCache[tableId].keys():
                    GameRoomSocketCache[tableId][userId].closeWindow()
                    del GameRoomSocketCache[tableId][userId]
                exitGameRoom(userId, tableId)
            else:
                if tableId is not None:
                    exitGameRoom(userId, tableId)
            # if tableId in GameRoomSocketCache.keys():
            #     if userId in GameRoomSocketCache[tableId].keys():
            #         GameRoomSocketCache[tableId][userId].closeWindow()
            #         exitGameRoom(userId, tableId)
            #         del GameRoomSocketCache[tableId][userId]

            # 刷新相关好友列表
            refreshRelativeFriendList([userId])
            self.clear_all_cookies()
            logging.info("cookie清除成功!")
            returnJson = {"status": "00"}
            self.write(json.dumps(returnJson, ensure_ascii=False))
Example #3
0
def exitGameRoom(userId,tableId):
    cursor.execute("UPDATE game_table_info SET left_player_id=NULL,left_ready_state=0 WHERE table_id=%s AND left_player_id=%s",
                   (tableId, userId))
    cursor.execute("UPDATE game_table_info SET right_player_id=NULL,right_ready_state=0 WHERE table_id=%s AND right_player_id=%s",
                   (tableId, userId))
    # 获取gameState
    cursor.execute("SELECT * FROM game_table_info WHERE table_id=%s", tableId)
    row = cursor.fetchone()
    gameState = row["game_state"]
    # 获取anotherPlayerId
    anotherPlayerId = None
    if gameState == 1:
        for key in GameRoomCache[tableId]["playerState"].keys():
            if key != userId:
                anotherPlayerId = key
                break
    escapeFlag = False
    if gameState == 1:
        # 玩家逃离对局,进行相应数据库操作
        escapeFlag = True
        cursor.execute(
            "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
            tableId)
        cursor.execute(
            "UPDATE user_info SET win_time=win_time+1,game_time=game_time+1 WHERE user_id=%s",
            anotherPlayerId)
        cursor.execute(
            "UPDATE user_info SET game_time=game_time+1 WHERE user_id=%s",
            userId)
        GameRoomSocketCache[tableId][anotherPlayerId].escapeGame()
        # 刷新相关好友列表
        refreshRelativeFriendList([userId, anotherPlayerId])
    # 判断tableId是否存在于GameRoomCache中
    if tableId in GameRoomCache.keys():
        # 删除缓存中的对局信息
        del GameRoomCache[tableId]
    if not escapeFlag:
        if tableId in GameRoomSocketCache.keys():
            for key in GameRoomSocketCache[tableId].keys():
                GameRoomSocketCache[tableId][key].refreshGameRoom()
    rowNumber = cursor.execute(
        "SELECT a.table_id,a.left_player_id,c.username AS left_username,b.avatar AS left_avatar,a.right_player_id,e.username AS right_username,d.avatar AS right_avatar,a.game_state FROM game_table_info AS a LEFT join user_info AS b ON a.left_player_id=b.user_id LEFT JOIN  user AS c ON b.user_id=c.user_id LEFT JOIN user_info AS d ON a.right_player_id=d.user_id LEFT JOIN user AS e ON e.user_id=d.user_id WHERE a.table_id=%s",
        tableId)
    refreshData = []
    for i in range(0, rowNumber):
        row = cursor.fetchone()
        temp = {"tableId": row["table_id"], "leftPlayerId": row["left_player_id"],
                "leftUsername": row["left_username"],
                "leftAvatar": row["left_avatar"], "rightPlayerId": row["right_player_id"],
                "rightUsername": row["right_username"], "rightAvatar": row["right_avatar"],
                "gameState": row["game_state"]}
        refreshData.append(temp)
    for key in HomeSocketCache:
        HomeSocketCache[key].refreshGameTableList(refreshData)
    cursor.execute("UPDATE user SET `table_id`=NULL WHERE user_id=%s", userId)
 def open(self, *args, **kwargs):
     userId = self.get_secure_cookie("userId").decode("utf-8")
     HomeSocketCache[userId] = self
     cursor.execute(
         "UPDATE user_info SET last_login_date =%s WHERE user_id=%s",
         (time.strftime('%Y-%m-%d', time.localtime()), str(userId)))
     cursor.execute(
         "UPDATE user SET login_state=1,state=1 WHERE user_id=%s",
         str(userId))
     logging.info(userId + "打开连接")
     #刷新相关好友列表
     refreshRelativeFriendList([userId])
Example #5
0
    def post(self, *args, **kwargs):
        self.set_header('Content-type', 'application/json')
        userId = self.get_secure_cookie("userId").decode("utf-8")
        cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
        row = cursor.fetchone()
        tableId = row["table_id"]
        roomCache = GameRoomCache[tableId]
        anotherPlayerId = None
        for key in roomCache["playerState"].keys():
            if key != userId:
                anotherPlayerId = key
                break
        # 对GameRoomCache进行更改
        roomCache["playerState"][userId]["myTurn"] = False
        roomCache["playerState"][userId]["overTimeCount"] += 1
        roomCache["playerState"][anotherPlayerId]["myTurn"] = True
        roomCache["playerState"][anotherPlayerId]["chessTime"] = time.time(
        ) * 1000
        returnData = {"status": "00"}
        self.write(json.dumps(returnData, ensure_ascii=False))
        # 通知前端调用交换棋权
        GameRoomSocketCache[tableId][anotherPlayerId].refreshGameView()
        if roomCache["playerState"][userId]["overTimeCount"] == 2:
            #当超时次数超过两次直接判输
            roomCache["playerState"][userId]["myTurn"] = False
            roomCache["playerState"][anotherPlayerId]["winTime"] += 1
            roomCache["playerState"][anotherPlayerId]["myTurn"] = False
            roomCache["totalGameTime"] += 1
            cursor.execute(
                "UPDATE user_info SET game_time=game_time+1 WHERE user_id=%s OR user_id=%s",
                (userId, anotherPlayerId))
            cursor.execute(
                "UPDATE user_info SET win_time=win_time+1 WHERE user_id=%s",
                anotherPlayerId)
            cursor.execute(
                "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
                tableId)
            # 将玩家状态改为在线,并通知其在线好友刷新friendList
            cursor.execute(
                "UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s",
                (userId, anotherPlayerId))
            # 刷新相关好友列表
            refreshRelativeFriendList([userId, anotherPlayerId])

            logging.info("玩家" + anotherPlayerId + "获胜")
            # 提醒前端胜负已分
            for key in GameRoomSocketCache[tableId]:
                GameRoomSocketCache[tableId][key].gameWin(anotherPlayerId)
    def on_message(self, message):
        data = json.loads(message)
        if data["type"] == "00":
            self.maintainConnection()
        if data["type"] == "01":
            userId = self.get_secure_cookie("userId").decode("utf-8")
            cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
            row = cursor.fetchone()
            tableId = row["table_id"]
            for key in GameRoomSocketCache[tableId].keys():
                if key != userId:
                    returnData = {}
                    returnData["type"] = "08"
                    returnData["data"] = data["message"]
                    GameRoomSocketCache[tableId][key].write_message(json.dumps(returnData, ensure_ascii=False))

        if data["type"] == "02":
            userId = self.get_secure_cookie("userId").decode("utf-8")
            cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
            row = cursor.fetchone()
            tableId = row["table_id"]
            roomCache = GameRoomCache[tableId]
            anotherPlayerId = None
            for key in roomCache["playerState"].keys():
                if key != userId:
                    anotherPlayerId = key
                    break
            if data["result"] == "agree":
                roomCache["playerState"][userId]["myTurn"] = False
                roomCache["playerState"][anotherPlayerId]["myTurn"] = False
                roomCache["totalGameTime"] += 1
                cursor.execute(
                    "UPDATE user_info SET game_time=game_time+1,draw_time=draw_time+1 WHERE user_id=%s OR user_id=%s",
                    (userId, anotherPlayerId))
                cursor.execute(
                    "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
                    tableId)
                cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
                # 将玩家状态改为在线,并通知其在线好友刷新friendList
                cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
                # 刷新相关好友列表
                refreshRelativeFriendList([userId, anotherPlayerId])
                # 提醒前端和棋
                for key in GameRoomSocketCache[tableId]:
                    GameRoomSocketCache[tableId][key].gameDraw()
            else:
                GameRoomSocketCache[tableId][anotherPlayerId].denyDraw()
Example #7
0
 def post(self):
     self.set_header('Content-type', 'application/json')
     userId = self.get_secure_cookie("userId").decode("utf-8")
     cursor.execute("SELECT * FROM user WHERE user_id=%s", userId)
     row = cursor.fetchone()
     tableId = row["table_id"]
     chessType = self.get_argument("chessType")
     x = self.get_argument("x")
     y = self.get_argument("y")
     logging.info("玩家" + userId + "下棋" + "index" + str([x, y]))
     roomCache = GameRoomCache[tableId]
     anotherPlayerId = None
     for key in roomCache["playerState"].keys():
         if key != userId:
             anotherPlayerId = key
             break
     # 对GameRoomCache进行更改
     roomCache["playerState"][userId]["myTurn"] = False
     roomCache["playerState"][anotherPlayerId]["myTurn"] = True
     roomCache["playerState"][anotherPlayerId]["chessTime"] = time.time()*1000
     roomCache["stepRecord"].append({"playerId": userId,
                                     "chessType": chessType,
                                     "point": [x, y]
                                     })
     # 对pointState进行更改
     pointState = roomCache["pointState"]
     if chessType == "black":
         pointState[int(x)][int(y)] = 1
     else:
         pointState[int(x)][int(y)] = 2
     # 判断输赢
     winFlag = False
     drawFlag = False
     if judgeWin(pointState, {"chessType": chessType, "chessPoint": [int(x), int(y)]}):
         winFlag = True
         roomCache["playerState"][userId]["myTurn"] = False
         roomCache["playerState"][userId]["winTime"] += 1
         roomCache["playerState"][anotherPlayerId]["myTurn"] = False
         roomCache["totalGameTime"] += 1
         cursor.execute("UPDATE user_info SET game_time=game_time+1 WHERE user_id=%s OR user_id=%s",
                        (userId, anotherPlayerId))
         cursor.execute("UPDATE user_info SET win_time=win_time+1 WHERE user_id=%s", userId)
         cursor.execute(
             "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
             tableId)
         # 将玩家状态改为在线,并通知其在线好友刷新friendList
         cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
         # 刷新相关好友列表
         refreshRelativeFriendList([userId, anotherPlayerId])
     # 和棋
     if len(roomCache["stepRecord"]) == 196:
         drawFlag = True
         roomCache["playerState"][userId]["myTurn"] = False
         roomCache["playerState"][anotherPlayerId]["myTurn"] = False
         roomCache["totalGameTime"] += 1
         cursor.execute(
             "UPDATE user_info SET game_time=game_time+1,draw_time=draw_time+1 WHERE user_id=%s OR user_id=%s",
             (userId, anotherPlayerId))
         cursor.execute(
             "UPDATE game_table_info SET left_ready_state=0,right_ready_state=0,game_state=0 WHERE table_id=%s",
             tableId)
         cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
         # 将玩家状态改为在线,并通知其在线好友刷新friendList
         cursor.execute("UPDATE user SET state=1 WHERE user_id=%s OR user_id=%s", (userId, anotherPlayerId))
         # 刷新相关好友列表
         refreshRelativeFriendList([userId, anotherPlayerId])
     returnData = {"status": "00"}
     self.write(json.dumps(returnData, ensure_ascii=False))
     # 通知前端调用交换棋权
     GameRoomSocketCache[tableId][anotherPlayerId].refreshGameView()
     if winFlag:
         logging.info("玩家" + userId + "获胜")
         # 提醒前端胜负已分
         for key in GameRoomSocketCache[tableId]:
             GameRoomSocketCache[tableId][key].gameWin(userId)
     if drawFlag:
         logging.info(tableId + "和局")
         # 提醒前端和棋
         for key in GameRoomSocketCache[tableId]:
             GameRoomSocketCache[tableId][key].gameDraw()
Example #8
0
def initGame(tableId):
    # 将数据库中gameState设置为1
    cursor.execute("UPDATE game_table_info SET game_state=1 WHERE table_id=%s",
                   tableId)
    # 获取此桌的玩家id
    cursor.execute("SELECT * FROM game_table_info WHERE table_id=%s", tableId)
    row = cursor.fetchone()
    leftUserId = str(row["left_player_id"])
    rightUserId = str(row["right_player_id"])
    # 将两个玩家的state改为2游戏中
    cursor.execute("UPDATE user SET state=2 WHERE user_id=%s OR user_id=%s",
                   (leftUserId, rightUserId))
    # 刷新相关好友列表
    refreshRelativeFriendList([leftUserId, rightUserId])
    # 准备刷新数据
    rowNumber = cursor.execute(
        "SELECT a.table_id,a.left_player_id,c.username AS left_username,b.avatar AS left_avatar,a.right_player_id,e.username AS right_username,d.avatar AS right_avatar,a.game_state FROM game_table_info AS a LEFT join user_info AS b ON a.left_player_id=b.user_id LEFT JOIN  user AS c ON b.user_id=c.user_id LEFT JOIN user_info AS d ON a.right_player_id=d.user_id LEFT JOIN user AS e ON e.user_id=d.user_id WHERE a.table_id=%s",
        tableId)
    refreshData = []
    for i in range(0, rowNumber):
        row = cursor.fetchone()
        temp = {
            "tableId": row["table_id"],
            "leftPlayerId": row["left_player_id"],
            "leftUsername": row["left_username"],
            "leftAvatar": row["left_avatar"],
            "rightPlayerId": row["right_player_id"],
            "rightUsername": row["right_username"],
            "rightAvatar": row["right_avatar"],
            "gameState": row["game_state"]
        }
        refreshData.append(temp)
    # 通知在线用户前端刷新数据
    for key in HomeSocketCache:
        HomeSocketCache[key].refreshGameTableList(refreshData)

    # 初始化pointState数组
    pointState = []
    for i in range(0, 15):
        temp = []
        for j in range(0, 15):
            temp.append(0)
        pointState.append(temp)

    # 初始化GameRoomCache
    if tableId in GameRoomCache.keys():
        GameRoomCache[tableId]["gameStartTime"] = time.time() * 1000
        GameRoomCache[tableId]["playerState"][leftUserId]["overTimeCount"] = 0
        GameRoomCache[tableId]["playerState"][rightUserId]["overTimeCount"] = 0
        if GameRoomCache[tableId]["totalGameTime"] % 2 == 0:
            GameRoomCache[tableId]["playerState"][leftUserId][
                "chessType"] = "black"
            GameRoomCache[tableId]["playerState"][leftUserId][
                "chessTime"] = time.time() * 1000
            GameRoomCache[tableId]["playerState"][leftUserId]["myTurn"] = True
            GameRoomCache[tableId]["playerState"][rightUserId][
                "chessType"] = "white"
            GameRoomCache[tableId]["playerState"][rightUserId][
                "myTurn"] = False
            GameRoomCache[tableId]["stepRecord"] = []
            GameRoomCache[tableId]["pointState"] = pointState
        else:
            GameRoomCache[tableId]["playerState"][leftUserId][
                "chessType"] = "white"
            GameRoomCache[tableId]["playerState"][leftUserId]["myTurn"] = False
            GameRoomCache[tableId]["playerState"][rightUserId][
                "chessType"] = "black"
            GameRoomCache[tableId]["playerState"][rightUserId][
                "chessTime"] = time.time() * 1000
            GameRoomCache[tableId]["playerState"][rightUserId]["myTurn"] = True
            GameRoomCache[tableId]["stepRecord"] = []
            GameRoomCache[tableId]["pointState"] = pointState
    else:
        GameRoomCache[tableId] = {
            "gameStartTime": time.time() * 1000,
            "totalGameTime": 0,
            "playerState": {
                leftUserId: {
                    "chessType": "black",
                    "overTimeCount": 0,
                    "winTime": 0,
                    "chessTime": time.time() * 1000,
                    "myTurn": True
                },
                rightUserId: {
                    "chessType": "white",
                    "overTimeCount": 0,
                    "winTime": 0,
                    "chessTime": "",
                    "myTurn": False
                }
            },
            "stepRecord": [],
            "pointState": pointState
        }
    # 通知前端对局开始
    GameRoomSocketCache[tableId][leftUserId].gameStart()
    GameRoomSocketCache[tableId][rightUserId].gameStart()