Esempio n. 1
0
def say(request):
    req =simplejson.loads(request.body)
    content = req['content']
    cmd = req['cmd']
    target = req['target']
    uid = request.user.id
    
    
    if not cmd:
        return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')

    chat = Chat()
    pattern1 = re.compile(r'<')
    content_t = re.sub(pattern1, '&lt;', content)

    pattern2 = re.compile(r'>')
    content_t = re.sub(pattern2, '&gt;', content_t)

    chat.username_id = request.user.id

    #................................................................
    if cmd == "chat":
        insertMsg(content_t,uid,datetime.datetime.now(),cmd,-1,'pub',ifPCInGame(uid))
	return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #..............................OK..................................
    if cmd == "GPCL":   #get pc list
	bValue = updateOnlineList(request)
	target_t = uid 
	content_t = getPcList(request)
	insertMsg( content_t, request.user.id, datetime.datetime.now(),"OLPC",uid,"pri",ifPCInGame(uid))
	return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #..............................OK..................................
    if cmd == "CRTG":   # create game
        bValue = updateOnlineList(request)
        
        g = createGame(uid, get_client_ip(request))

        debugLog("CRTG: createGame() return value="+str(g))
        
        if g["gid"]>0: 
            try:
                grinfo = getGIRNDByUid(uid, request.user.username)
                rCRTG = insertMsg( simplejson.dumps(grinfo),uid, datetime.datetime.now(), "CRTG", uid, "pri", g["gid"])
            except Exception,data:
                debugLog("CRTG error:"+str(Exception)+":"+str(data))
                
        else:
            rCRTG = insertMsg( g["errmsg"],uid, datetime.datetime.now(), "CRTG", uid, "pri", -1)
        
        return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
Esempio n. 2
0
def getPcList(request):
    uid = request.user.id
    found = False
    gameID = ifPCInGame(uid)
    if gameID == 0:
        return simplejson.dumps([])
    
    try:
        p = PC.objects.get(player_id=uid) 
        if p:
            found = True
    except:
        pass
    
    ip = get_client_ip(request)
    
    if not found: 
        ol = PC()
        
        ol.player_id = uid
        ol.ip = ip
        ol.sanity = 3
        ol.save()
    
    ols = PC.objects.filter( Q(gameStatue=gameID) )

    olplayers = []
    for player in ols:
        nick = User.objects.get(pk=player.player_id).username 
        olplayers.append({'id':player.player_id, 
                          'player':nick,
                          'sanity':player.sanity
                          })
    r = simplejson.dumps(olplayers)
    return r
Esempio n. 3
0
def createGame(uid, ip):
    r = {"errmsg":"","gid":0}
    
    # check items
    bValue1 = checkOblation(uid)
    iValue = ifPCInGame(uid)

    if bValue1 and iValue==0:
        gi = GameInfo()
        
        gi.cthulhuSanity = 0
        gi.pclist = str(uid)
        gi.winner = -1
        gi.statue = 1
        gi.createTime = datetime.datetime.now()
        gi.creator_id = uid
        gi.save()
        try:
            crntgame = GameInfo.objects.filter(creator_id=uid).order_by('-id')[:1]
            if len(crntgame)==0:
                r["errmsg"] = "create game fail."
                return r
            gid = crntgame[0]
            r["gid"] = gid.id
        except:
            r["errmsg"] = "create game fail."
            return r
        
        # modify creators' game statue
        try:
            ol = PC.objects.get(player_id = uid)
            ol.active_time = datetime.datetime.now()
            ol.ip = ip
            ol.gameStatue = gid.id
            ol.sanity = 3

            ol.save(update_fields=['ip','active_time','gameStatue','sanity'])
        except:
            ol = PC()
            ol.player_id = uid
            ol.active_time = datetime.datetime.now()
            ol.ip = ip
            ol.gameStatue = gid.id
            ol.sanity = 3
            ol.save()
        return r
    if iValue>0:
        r["errmsg"] = "already in a game!"
        r["gid"] = iValue
    if not bValue1:
        r["errmsg"] = "not enough oblation!"
    
    return r
Esempio n. 4
0
def chatAllLog(request):
    if 'record_offset' in request.session:
        record_offset = request.session.get('record_offset')
    else:
        record_offset = 0
        request.session['record_offset'] = 0
    uid = request.user.id

    gameID = ifPCInGame(uid)
    
    pcGstatue = PC.objects.get(player_id=uid)
    if gameID <= 0 and pcGstatue.gameStatue==0 :
        chatList = Chat.objects.filter( Q(cmdType="pub") |
                                          Q(cmdType="sys") |
                                          Q(cmdType="ano") |
                                          Q(cmdType="pri", target = uid),#target=request.user.username),
                                          Q(id__gt=record_offset) )
    else:
        chatList = Chat.objects.filter( Q(cmdType="pub") |
                                    Q(cmdType="sys") |
                                    Q(cmdType="ano") |
                                    Q(cmdType="gam", gid=gameID) |
                                    Q(cmdType="gam", gid=pcGstatue.gameStatue) |
                                    Q(cmdType="pri", target = uid ),#target=request.user.username),
                                    Q(id__gt=record_offset) )
    
    chatlist_dict = []
    request.session['record_offset'] = len(chatList) + record_offset
    for chat in chatList:
	nick = User.objects.get(pk=chat.username_id).username

        chatlist_dict.append({'id':chat.id,
			      'content':chat.content,
                              'username_id': nick,
                              'date':str(chat.date).split('.')[0],
			      'cmd':chat.cmd,
			      'cmdType': chat.cmdType,
			      'target': chat.target,
                              'gid': chat.gid
                              })
    if gameID <= 0 and pcGstatue.gameStatue>0 :
        pcGstatue.gameStatue = 0
        pcGstatue.save(update_fields=['gameStatue'])

    return HttpResponse(simplejson.dumps(chatlist_dict), mimetype = 'application/json')
Esempio n. 5
0
def joinGame(gid, uid, ip):
    errmsg = ''

    # check player's statue and if in a game - and jump to current game if there's any
    iValue = ifPCInGame(uid)
    if iValue>0:
        errmsg = "already in a game!"
        return errmsg

    g = ifGameAvailable(gid)
    
    if g["gameAvailable"]:
        if g["statue"] == 1:
            # check how many players in game
            num = PC.objects.filter(gameStatue=gid)#.count()

            if len(num) < 6:
                # modify creators' game statue
                try:
                    ol = PC.objects.get(player_id = uid)
                    ol.active_time = datetime.datetime.now()
                    ol.ip = ip
                    ol.gameStatue = gid
                    ol.sanity = 3
                    ol.save(update_fields=["ip","active_time","gameStatue","sanity"])
                except Exception,data:
                    ol = PC()
                    ol.player_id = uid
                    ol.active_time = datetime.datetime.now()
                    ol.ip = ip
                    ol.gameStatue = gid
                    ol.sanity = 3
                    ol.save()

                return errmsg
            else:
                errmsg = "You cannot join the game!"
        else:
            errmsg = "You cannnot join the game!"
Esempio n. 6
0
def getGIRNDByUid(uid, nick):
    r = {}

    # 获取PC状态,验证PC当前是否处于某个游戏中
    gid = ifPCInGame(uid)
    if gid > 0:
        try:
            pl = PC.objects.filter(gameStatue=gid)
            gs = GameInfo.objects.get(pk=gid)

            # if pl.statue == 2:
            if gs.statue == 2 or gs.statue == 1:
                pclist = []
                for p in pl:
                    nick = User.objects.get(pk=p.player_id).username
                    pclist.append({"id": p.player_id, "player": nick, "sanity": p.sanity})

            if gs.statue == 2:
                rnd = Round.objects.filter(gameID=gid).order_by("-id")[0]

                rnd_id = rnd.id
                rnd_caster = rnd.caster
                rnd_victim = rnd.victim
                rnd_attackTimeBegin = rnd.attackTimeBegin
                rnd_fbTimeBegin = rnd.fbTimeBegin
                rnd_casterDice = rnd.casterDice
                rnd_victimDice = rnd.victimDice
                rnd_roundStatue = rnd.roundStatue

                act = getCrntDicePC(gid)

                if act["crntPC"] > 0:
                    actor = act["crntPC"]
                else:
                    actor = -1

            else:
                rnd_id = 0
                rnd_caster = 0
                rnd_victim = 0
                rnd_attackTimeBegin = 0
                rnd_fbTimeBegin = 0
                rnd_casterDice = 0
                rnd_victimDice = 0
                rnd_roundStatue = 0
                actor = -1

            tempPL = simplejson.dumps(pclist)
            game = GameInfo.objects.get(pk=gid)

            d = game.createTime  #
            st = d.strftime("%Y-%m-%d %H:%M:%S")  #

            if rnd_fbTimeBegin:
                fbt = rnd_fbTimeBegin.strftime("%Y-%m-%d %H:%M:%S")
            else:
                fbt = "0"

            if rnd_attackTimeBegin:
                atime = rnd_attackTimeBegin.strftime("%Y-%m-%d %H:%M:%S")
            else:
                atime = 0

            r = {
                "nick": nick,
                "actor": actor,
                "gid": gid,
                "cs": game.cthulhuSanity,
                "statue": game.statue,
                "ctime": st,
                "creator": game.creator_id,
                "winner": game.winner,
                "ps": tempPL,
                "rid": rnd_id,
                "caster": rnd_caster,
                "victim": rnd_victim,
                "atime": atime,
                "fbtime": fbt,
                "cdice": rnd_casterDice,
                "vdice": rnd_victimDice,
                "rstatue": rnd_roundStatue,
            }
            debugLog("getGIRNDByUid() r = " + str(r))
        except Exception, data:
            debugLog("getGIRNDByUid()" + str(Exception) + ":" + str(data))
            return r
Esempio n. 7
0
    if cmd == "JOIN":   # join game
        jGid = req['gid']
        bValue = updateOnlineList(request)
        
        jg = joinGame(int(jGid), uid, get_client_ip(request))
        
        if jg =="":
	    grinfo = getGIRNDByUid(uid, request.user.username)
            insertMsg( simplejson.dumps(grinfo), uid, datetime.datetime.now(),"JOIN",0,"gam",jGid)
        else:
            insertMsg( "", uid, datetime.datetime.now(),"JOIN",uid,"pri",0)
        return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #.............................nearly.OK..................................
    if cmd == "STRT":   # start game
        crntGid = ifPCInGame(uid)
        
        if crntGid >0:
            sg = startGame(crntGid)
            
            if sg["errmsg"]:
                insertMsg( sg["errmsg"], uid, datetime.datetime.now(),"STRT",target_t,"pri",0)
                return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')

            grin = getGIRNDByUid(uid, request.user.username)
            
            try:
	        if len(grin)>0:
		    insertMsg(simplejson.dumps(grin), uid, datetime.datetime.now(), "STRT", 0, "gam",grin["gid"] )
		else:
		    return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')
Esempio n. 8
0
def checkPCTurn(uid):
    try:
        gid = ifPCInGame(uid)
    except Exception, data:
        es = str(Exception) + ":" + str(data)
        debugLog("   check PCTurn() ifPCInGame:" + es)