Beispiel #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')
Beispiel #2
0
def startGame(gid):
    rvalue = {"errmsg":"", "pclist":[]}

    # find request.user.id created game id
    if gid <1:
        rvalue["errmsg"]="Game does not exist!"
        return rvalue

    # set game statue
    try:
        game = GameInfo.objects.get(pk=gid)
        
        if game.statue ==1:
            game.statue = 2
            allpc=PC.objects.filter(gameStatue=gid)
            pc_num = len(allpc)

            if pc_num<2:
                rvalue["errmsg"] = "not enough players!"
                return rvalue
            if pc_num>6:
                rvalue["errmsg"] = "too many players! please remove %d player(s)."%(len(pclist)-6)
                return rvalue

            # set players statue
            rvalue["pclist"] = ""
            tmpC = 0
            
            for pc in allpc:
                if tmpC ==0:
                    firstCaster = pc.player_id
                pc.sanity = 3

                #pc sequence

                #提醒:PClist部分作为投骰顺序数组保存,勿删除!
                #游戏信息使用get GIRNDByUid()获取
                
                tstr = str(pc.player_id)
                tmpC = tmpC + 1
                rvalue["pclist"] = rvalue["pclist"] + tstr
                if tmpC < pc_num:   #6:
                    rvalue["pclist"] = rvalue["pclist"] + ","

            createNewRound(firstCaster,gid)
            game.pclist = rvalue["pclist"]
            game.save(update_fields=['statue','pclist'])
    except Exception,data:
        debugLog("startGame():"+str(Exception)+":"+str(data))
        rvalue["errmsg"] = "cannot start the game!"
Beispiel #3
0
def eye_choose(uid, dice, turnFlg):
    r = {"errmsg":""}
    diceIndex = {"Cthulhu":0,"Yellow":1,"Tentacle":2,"Elder":8}
    
    if dice not in diceIndex:
        r["errmsg"]="no such dice"
        return r

    attFlag = turnFlg["RollTurnInfo"]["grStatue"]
    gid = turnFlg["gid"]
    
    try:
        rnd_list = Round.objects.filter(gameID=gid).order_by('-id')[:1]
    except Exception,data:
        debugLog("eye_choose() query Round fail: "+str(Exception)+":"+str(data))
        r["errmsg"]="query round error"
        return r
Beispiel #4
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
Beispiel #5
0
def roll(request, target, gid, cRound, turnFlg):
    debugLog("roll() begin aaa")
    uid = request.user.id
    
    attFlag = turnFlg["RollTurnInfo"]["grStatue"]
    
    r = {"errmsg":""}
    targetStatue = ifMad(target)
    
    if targetStatue["errmsg"]=="":
        mad = targetStatue["mad"]
    else:
        r["errmsg"] = targetStatue["errmsg"]
        return r
    if mad and attFlag==0:
	r["errmsg"] = "target mad" #u"目标已疯,不能进行此操作。"
        return r
    else:
        # 生成骰数
	num = random.randint(0,11)
	#num = 9
	
        # 根据骰数决定对应操作
        diceIndex =["Cthulhu","Yellow","Tentacle","Tentacle","Yellow","Yellow","Yellow","Yellow","Elder","Eye","Tentacle","Tentacle"]

        debugLog("roll()  randint: diceNum="+str(num)+" dice="+str(diceIndex[num]) )
        debugLog("roll() *** attFlag="+str(attFlag))

        #设置攻击及受害者
        if attFlag==0:
            caster = uid
            victim = target
        elif attFlag == 1:
            lastRnd = getLastRound(gid)
            caster = lastRnd.victim
            victim = lastRnd.caster
        else:
            r["errmsg"] = "unknow"
            return r
        
        r["target"] = victim
        
        if not turnFlg["PCTURN"]:
            ot = True
        else:
            ot = False
            
        # 进行相应操作:扣除被伤害者相应神智/...等
        va = {"dice":diceIndex[num],
              "gid":gid,
              "caster":caster,
              "victim":victim,
              "flag":attFlag,
              "overtime":ot
              }
        rvalue = switch(va)
        
        if len(rvalue)==0:
            return r
        rvalue["rid"] = cRound

	rnd_list = Round.objects.filter(gameID=gid).order_by('-id')[:1]
	t_rnd = rnd_list[0]
        
        rvalue["rollFlag"] = attFlag

        #更新
        if attFlag==0:
	    if diceIndex[num]!="Eye":
	        rvalue["pTurn"] = target
	    else:
	        rvalue["pTurn"] = caster
            t_rnd.casterDice = num
            t_rnd.fbTimeBegin = datetime.datetime.now()
            t_rnd.victim = target
            t_rnd.save(update_fields=['casterDice','victim','fbTimeBegin'])
        elif attFlag == 1:
            t_rnd.victimDice = num
            t_rnd.save(update_fields=['victimDice'])

            # 若本轮结束则更新本轮;
            if diceIndex[num]!="Eye":
	        # 游戏结束:sanity<1的人有5个;查找是否有获胜者;返回数据格式:
	        gameover = ifGameOver(gid)
	        if gameover>=0:
		    rvalue["gameover"]=1
		    rvalue["winner"]=gameover
		    game = GameInfo.objects.get(pk=gid)
		    game.statue = 0
		    game.winner = gameover
		    game.save(update_fields=['statue','winner'])
		else:
		    rvalue["gameover"]=0
		    
		    #查找下一个玩家,开启下一回合(轮)
		    nextCaster = findNextCaster(gid)
		    newrid = createNewRound(nextCaster,gid)
		    
		    rvalue["crntRid"] = newrid
		    rvalue["pTurn"] = nextCaster
		    rvalue["rtime"] = datetime.datetime.now()
		    rvalue["rFlag"] = 1
            else:
	        rvalue["pTurn"] = uid
	        rvalue["rollFlag"] = attFlag+3
        else:
            pass
	    
        r["info"] = rvalue

    return r
Beispiel #6
0
        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')
            except Exception,data:
		debugLog("STRT error:"+str(Exception)+":"+str(data))
        return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #................................................................
    if cmd == "QRRD":   # query game round
        return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

    #................................................................
    if cmd == "ROLL":   # roll dice ( with target )
        # 获取发送者及游戏状态,决定是否可投骰,产生投骰结果,修改游戏及玩家状态,插入消息并返回
        
        #是否以自己为目标
        if target == uid:
	    return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

        iValue = ifPCInGame(uid)
Beispiel #7
0
def checkPCTurn(uid):
    try:
        gid = ifPCInGame(uid)
    except Exception, data:
        es = str(Exception) + ":" + str(data)
        debugLog("   check PCTurn() ifPCInGame:" + es)
Beispiel #8
0
        gid = ifPCInGame(uid)
    except Exception, data:
        es = str(Exception) + ":" + str(data)
        debugLog("   check PCTurn() ifPCInGame:" + es)

    r = {"PCTURN": False, "RollToken": False, "rndID": -1, "gid": gid}

    if gid <= 0:
        return r

    try:
        tmpDicePC = getCrntDicePC(gid)
        r["RollTurnInfo"] = tmpDicePC
    except Exception, data:
        es = str(Exception) + ":" + str(data)
        debugLog("check PCTurn () line 38:" + es)
        return r

    # 无论是否超时,只要当前是该玩家投骰则返回True
    if r["RollTurnInfo"]["crntPC"] == uid:
        r["PCTURN"] = True
        r["RollToken"] = True
        return r
    elif r["RollTurnInfo"]["overtime"] == True:

        # 非uid投骰,且当前超时:
        #  检查下一个投骰者是否uid
        nextpc = isNextCaster(uid, gid)

        #    若是则设置当前轮状态,生成新轮,并返回新生成的轮信息
        ##if uid == nextpc:
Beispiel #9
0
# -*-coding:utf-8 -*-
from cthulhudice.models import Chat,PC,Counter,GameInfo,Round


from debugLog import debugLog

def ifPCInGame(uid):
    inGameFlag = False

    try:
        pcstatue = PC.objects.get(player_id=uid)
        
        if pcstatue.gameStatue > 0:
            inGameFlag = True
        else:
            return 0
    except Exception,data:
        return -2

    if inGameFlag:
        try:
            ginfo = GameInfo.objects.get(pk = pcstatue.gameStatue)
            if ginfo.statue >0:
                return ginfo.id
        except Exception,data:
            es = str(Exception)+":"+str(data)
            debugLog("ifPCInGame() get gameinfo: "+str(Exception)+":"+str(data))
            return -3
    return 0