Beispiel #1
0
def finalEvaluation(data, opponent):
    # print data;
    if(data['userdata']['victory'] != -1):
        if(data['userdata']['victory'] == True):
            MessageBeep(beep); time.sleep(0.1); MessageBeep(beep); time.sleep(0.1); MessageBeep(beep);
            conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Win:'+data['username']};
            conn1.request();
            xp = str(int(floor(data['userdata']['remainingTurns'] / 4)));
            data2 = xp+',0,1';
            Display.playerMsg('Good job,', data['username']+'!');
            Display.gameMsg("You've defeated", opponent, 'in', (data['userdata']['maxTurns'] - data['userdata']['remainingTurns']), 'turns.');
            Display.gameMsg("You've earned", xp, 'SP point(s)!');
            
        elif(data['userdata']['victory'] == False):
            MessageBeep(MB_OK); time.sleep(0.1); MessageBeep(MB_OK); time.sleep(0.1); MessageBeep(MB_OK);
            conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Win:'+opponent};
            conn1.request();
            data2 = '1,1,0';
            Display.errorMsg("You failed", data['username']+".");
            Display.errorMsg("You've lost to", opponent+".");
            Display.errorMsg("The correct answer was " + data['userdata']['answer'] + ".");
            Display.gameMsg("You've received 1 SP point.");

        conn1.params = {"u":u, "p":p, "python":1, "type":"psh", "SID":SID, 'data':data2};
        response = conn1.request();
        if(response != False):
            if(response[0:7] == 'Leveled'): Display.gameMsg('-+-+-+-+ Congratulations! You are now level '+response[8:]+' +-+-+-+-');
            elif(response == 'Updated'): Display.gameMsg('Server updated successfully.');
            else: Display.errorMsg('Server update failed! ('+str(response)+')');
        else: Display.errorMsg('Server update failed! (could not establish connection)');
        Display.errorMsg('Game Over.');
Beispiel #2
0
def checkForCommands(response, actionQueue, opponent):
    global conn1;
    doBreak = False;
    
    if(response == '$Skipped:'+actionQueue['username']):
        conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$ClearGameData'};
        conn1.request();
        Display.errorMsg('Temporarily desynched from the server. Your actions were discarded.');
    elif(response == '$Skipped:'+opponent):
        Display.errorMsg('Your opponent has desynched from the server. You have been declared winner.');
        doBreak = True;
        actionQueue['userdata']['victory'] = True;
        finalEvaluation(actionQueue, opponent);
    elif(response == '$Updated'): Display.gameMsg("Synchronization complete.");
    elif(response == '$Win:'+opponent):
        actionQueue['userdata']['victory'] = False;
        finalEvaluation(actionQueue, opponent);
        doBreak = True;
    elif(response == '$Win:'+actionQueue['username']):
        actionQueue['userdata']['victory'] = True;
        finalEvaluation(actionQueue, opponent);
        doBreak = True;
    else:
        if(response == '$Alive:'+opponent or response == '$Yes' or response == '$Skipped:'+opponent):
            conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Die'};
            conn1.request();
            Display.errorMsg('Due to your opponent\'s excessive lag, the game has been canceled.');
            
        elif(response == '$Alive:'+actionQueue['username']):
            conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Die'};
            conn1.request();
            Display.errorMsg('Due to your excessive lag, the game has been canceled.');
            
        elif(response == '$Die'):
            Display.errorMsg('The game has been canceled unexpectedly. Probably due to lag.');
            
        else:
            Display.errorMsg('Bad response from server. Game Over.');
            Display.errorMsg('>>', response);
            
        actionQueue['userdata']['victory'] = -1;
        doBreak = True;
    return (actionQueue, doBreak);
Beispiel #3
0
def MAR_exit(status=0):
    if(status == 0): Display.gameMsg('Program Terminated.');
    else: Display.errorMsg('Program Terminated Unexpectedly ('+str(status)+')!');
    Display.evnMsg('(C) Copyright 2010 - Dark Gray. All Rights Reserved.');
    Display.pause();
    os._exit(status);
Beispiel #4
0
def MAR_battle(opponent, first):
    print '';
    global conn1, heartbeat, loggedIn, userdict, userpowers, ascii_uppercase;
    if(not conn1 or not loggedIn or not heartbeat or not userdict or not userpowers or not ascii_uppercase): MAR_exit(3);

    # Letters need re-reversing for some reason. Bad python scoping system is bad and horrible.
    # ascii_uppercase = ascii_uppercase[::-1];
    
    # Finish setting up our environment
    actionQueue = {'username':userdict['username'], 'specialdata':{},
                   'userdata':{
                       'guess':None,
                       'miniTurns':0,
                       'remainingTurns':27,
                       'maxTurns':28,
                       'letterNum':1,
                       'answer':None,
                       'answerStatus1':None,
                       'answerStatus2':None,
                       'skipped': False,
                       'victory': False
                   }};

    # Structure the user's powers into a workable menu object
    powerStructure = [('guess', -1), ('skip', -2)];
    for power in userpowers.keys(): powerStructure.insert(0, (str(power).lower(), str(power)));
    powerStructure = OrderedDict(powerStructure);

    # Begin the game
    while(actionQueue['userdata']['remainingTurns'] > 0 and not actionQueue['userdata']['victory']):
        if(actionQueue['userdata']['letterNum'] <= 4 and not actionQueue['userdata']['victory']):
            # We're up!
            if(first):
                if(not actionQueue['userdata']['skipped']):
                    # Set up our environment
                    if(actionQueue['userdata']['answer'] == None):
                        actionQueue['userdata']['answer'] = ascii_uppercase[randint(0, 25)];
                        Display.gameMsg('--> For you, this is letter '+str(actionQueue['userdata']['letterNum'])+' of 4.');
                    Display.gameMsg('[To use your specials, type the special\'s name and press "enter."]');
                    Display.gameMsg('[To guess, type "guess" followed by your letter guess.]');
                    Display.gameMsg('[To skip your turn, type "skip."]');
                    Display.gameMsg('[You have 60 seconds until your turn is automatically skipped]');
                    
                    # Prompt for selection of powers or guess (60 second time limit)
                    sleeptime = time.clock();
                    i = Display.menu(powerStructure, initMsg='Your move:', prefix='- ', time_limit=60, limit_phrase='skip');

                    # User wants to guess normally
                    if(i == -1):
                        if(actionQueue['userdata']['guess'] != None and actionQueue['userdata']['answerStatus2'] != ''): Display.gameMsg('-> You previous guess was:', actionQueue['userdata']['guess'], '('+actionQueue['userdata']['answerStatus2'][:-1].lower()+')');
                        actionQueue['userdata']['guess'] = Display.timed_input('> Guess a letter, '+actionQueue['username']+': ', 'skip', 60 - (time.clock() - sleeptime));
                        if(actionQueue['userdata']['guess'] == 'skip'): actionQueue['userdata']['skipped'] = True;
                        elif(actionQueue['userdata']['guess'] in ascii_letters):
                            if(actionQueue['userdata']['guess'].upper() == actionQueue['userdata']['answer']):
                                actionQueue['userdata']['miniTurns'] = actionQueue['userdata']['miniTurns'] + 1;
                                Display.gameMsg("You've guessed correctly! (Total", actionQueue['userdata']['miniTurns'], "turns)");
                                actionQueue['userdata']['letterNum'] = actionQueue['userdata']['letterNum'] + 1;
                                if(actionQueue['userdata']['letterNum'] <= 4 and not actionQueue['userdata']['victory']):
                                    MessageBeep(beep); time.sleep(0.1); MessageBeep(beep);
                                    actionQueue['userdata']['answerStatus1'] = actionQueue['username']+" guessed correctly and is onto the next letter! (Letter "+str(actionQueue['userdata']['letterNum'])+" of 4)";
                                    actionQueue['userdata']['answerStatus2'] = '';
                                    actionQueue['userdata']['miniTurns'] = 0;
                                    actionQueue['userdata']['answer'] = None;
                                else:
                                    actionQueue['userdata']['victory'] = True;
                                    finalEvaluation(actionQueue, opponent);
                                    break;
                            else:
                                dist = distanceAlgorithm(ascii_uppercase, actionQueue['userdata']['guess'].upper(), actionQueue['userdata']['answer'], 4.0, 40);
                                actionQueue['userdata']['answerStatus1'] = actionQueue['username']+' guessed incorrectly!';
                                actionQueue['userdata']['answerStatus2'] = "Guess was "+dist;
                                print Display.errorWrapper() + "Incorrect! Your guess was", dist;
                        else:
                            Display.errorMsg("That's not a letter,", actionQueue['username']+". You've lost two turns for that!");
                            actionQueue['userdata']['answerStatus1'] = actionQueue['username']+' entered an invalid response and was penalized!\n  What a fool!';
                            actionQueue['userdata']['answerStatus2'] = 'Guess was invalid.';
                            actionQueue['userdata']['remainingTurns'] = actionQueue['userdata']['remainingTurns'] - 2;
                            actionQueue['userdata']['miniTurns'] = actionQueue['userdata']['miniTurns'] + 1;
                    
                    # User wants to skip their turn
                    elif(i == -2):
                        actionQueue['userdata']['skipped'] = True;
                        actionQueue['userdata']['guess'] = actionQueue['userdata']['answerStatus1'] = None;
                        actionQueue['userdata']['answerStatus2'] = '';
                        actionQueue['userdata']['miniTurns'] = actionQueue['userdata']['miniTurns'] + 1;

                    # A power was chosen, attempt to add it to the specialdata array
                    else:
                        Display.errorMsg('Specials don\'t work yet. Sorry!');
                        actionQueue['userdata']['skipped'] = True;
                        actionQueue['userdata']['guess'] = actionQueue['userdata']['answerStatus1'] = None;
                        actionQueue['userdata']['answerStatus2'] = '';
                        actionQueue['userdata']['miniTurns'] = actionQueue['userdata']['miniTurns'] + 1;
                        # actionQueue['specialdata'] = activatePower(userpowers[i], actionQueue['specialdata']);

                # Evaluate specialdata array & victory conditions
                actionQueue = evaluateQueue(actionQueue);
                Display.gameMsg('Turn ended!');
                Display.gameMsg("You have", (actionQueue['userdata']['remainingTurns'] if actionQueue['userdata']['remainingTurns'] > 0 else 'no'), "turns remaining.");
                Display.gameMsg("Synchronizing with server...");
                conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':actionQueue};
                response = conn1.request();
                # print 'resp:', response

                if(response == '$UpdateFailed'): Display.errorMsg('Internal Error: server failed to update properly! Report this!');
                if(response == '$LookupError'): Display.errorMsg('Internal Error: server-user lookup error! Report this!');
                else:
                    actionQueue, doBreak = checkForCommands(response, actionQueue, opponent);
                    if(doBreak): break;
                
                actionQueue['userdata']['remainingTurns'] = actionQueue['userdata']['remainingTurns'] - 1;
                actionQueue['userdata']['miniTurns'] = actionQueue['userdata']['miniTurns'] + 1;
                actionQueue['userdata']['skipped'] = False;
                
            # They're up! (wait for 60[+10] seconds)
            else:
                Display.gameMsg('Waiting on', opponent+' (~60 seconds until timeout)...');
                response = block_on_challenge('$NoData', {"u":u, "p":p, "python":1, "type":"bat4", "SID":SID, 'opponent':opponent}, at_end=0, stall_time=70);
                
                if(is_JSON(response)):
                    if(response['userdata']['victory'] or response['userdata']['letterNum'] > 4):
                        print 'incorrect loss action:', response
                        actionQueue['userdata']['victory'] = False;
                        finalEvaluation(actionQueue, opponent);
                        break;
                    else:
                        if(response['userdata']['answerStatus1']):
                            if(response['userdata']['answerStatus1'].find('guessed correctly and is onto')+1): MessageBeep(MB_OK); time.sleep(0.1); MessageBeep(MB_OK);
                            Display.gameMsg('->', response['userdata']['answerStatus1']);
                        else: Display.gameMsg('->', opponent, 'skipped his turn?! Foolish!');
                        evaluateQueue(response, False);
                        Display.sysMsg('Opponent\'s turn ended. Your move!');
                elif(response == False):
                    # Send the "is alive ne?" packet
                    Display.gameMsg('No response from opponent, clearing victory conditions...');
                    conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Alive:'+opponent};
                    conn1.request();
                    response = block_on_challenge('$NoData', {"u":u, "p":p, "python":1, "type":"bat4", "SID":SID, 'opponent':opponent, "ignore":'$Alive:'+opponent}, at_end=0, stall_time=10, eval_response=False);
                    
                    if(response == '$Yes'):
                        Display.gameMsg('Opponent\'s turn was skipped.');
                        conn1.params = {"u":u, "p":p, "python":1, "type":"upd", "SID":SID, 'data':'$Skip:'+actionQueue['username']};
                        conn1.request();
                        time.sleep(3);

                    elif(response == False or response[0] == '{'):
                        Display.gameMsg('Opponent has disconnected from the server. You win by default.');
                        actionQueue['userdata']['victory'] = True;
                        finalEvaluation(actionQueue, opponent);
                        break;

                    else:   
                        actionQueue, doBreak = checkForCommands(response, actionQueue, opponent);
                        if(doBreak): break;
                else:   
                    actionQueue, doBreak = checkForCommands(response, actionQueue, opponent);
                    if(doBreak): break;

            #Change up the order
            first = not first;
            
        else:
            actionQueue['userdata']['victory'] = True;
            finalEvaluation(actionQueue, opponent);
            break;
    else:
        if(not actionQueue['userdata']['victory']): finalEvaluation(actionQueue, opponent);

    Display.sysMsg('Cleaning up room...');
    conn1.params = {"u":u, "p":p, "python":1, "type":"kil", "SID":SID};
    conn1.request();
    Display.sysMsg('Room cleaned successfully.');
    Display.gameMsg('Returning to main menu...');
    heartbeat.pauseFlag = False;
    conn1.makeNulls = False;
Beispiel #5
0
try:
    while(True):
        # Staying away from my complex menu object, since explaining it in a write up would be... well, complex.
        i = Display.menu(OrderedDict([('free play', 0), ('local play', 1), ('online play', 2), ('exit', 3)]), initMsg='Select Your Gameplay Mode:', prefix='# ');
        
        # Free play mode, which is basically the game as it was originally intended
        if(i == 0):
            gameNum = 0;
            state = 'y';
            name = Display.cooked_input("> What's your name? "); # Python doesn't even have a do-while?! Wow. Really? ... Really? What a waste of code.
            
            while not re.match('^[0-9a-zA-Z_]{4}[0-9a-zA-Z_]*$', name) and 4 <= name <= 25: # ^[0-9a-zA-Z_]{4,25}$ wasn't working for some odd reason >.<
                Display.errorMsg('Invalid name! Numbers/Letters only (between 4 and 25 chars).');
                name = Display.cooked_input("> What's your name? ");

            Display.gameMsg('Welcome to the Letter Guessing Game,', name+'!');
            
            while state == 'y':

                # Finish setting up our environment
                tries = 0;
                maxTries = 7;
                # ascii_uppercase = ascii_uppercase[::-1];
                answer = ascii_uppercase[randint(0, 25)];
                gameNum = gameNum + 1;
                Display.gameMsg('For you, this is game #'+str(gameNum)+'.');

                # Begin the game
                while tries < maxTries:
                    guess = Display.cooked_input('> Guess a letter, '+name+': ');
                    
Beispiel #6
0
        Display.errorMsg('Please try again later.');
        MAR_exit(1);
        
    while(True):
        zzz=lambda(zz):z==zz;
        while(not zzz(zz)): z = Display.cooked_input('> 暗証? ');
        if(not loggedIn):
            while(not login()): login();
        i = Display.menu(OrderedDict([('create', 0), ('moderate', 1), ('delete', 2), ('exit', 3)]), initMsg='Select Mode:', prefix='# ');
        
        # Creation mode, which allows for the creation of God accounts
        if(i == 0):
            response = None;
            while(response != "Approved"):
                # Ask the user for his/her information
                Display.gameMsg('Type "Back" at any time to go back to the previous menu.');
                Display.gameMsg('(This means "Back" cannot be your username/password!)');
                u = Display.cooked_input("> Desired Username: "******"> Desired Password:"******"Conversing with server...");

                # Package the new data
                conn1.params = {"u":u, "python":1, "type":"", "SID":SID};

                # Simple validation
                if(len(u) > 25 or len(p) > 100 or len(u) < 4 or len(p) < 4):
try:
    gameNum = 0
    i = 1
    state = "y"
    # No color support in this version, so the Display.*Msg distinctions are only code-deep
    Display.sysMsg("Bernard Dickens - Letter Guessing Game (Project II) - ", __author__)

    while i == 1:
        i = Display.menu(
            OrderedDict([("free play", False), ("load profile", 1), ("online play", True), ("exit", 2)]),
            initMsg="Please Select Your Gameplay Mode:",
            prefix="# ",
        )
        if i == 1:
            Display.gameMsg("This gameplay mode is not available yet.")

    if i != 2:
        name = Display.cooked_input("What's your name? ")
        while (
            not re.match("^[0-9a-zA-Z_]{4}[0-9a-zA-Z_]*$", name) and 4 <= name <= 25
        ):  # ^[0-9a-zA-Z_]{4,25}$ wasn't working for some odd reason >.<
            Display.errorMsg("Invalid name! Numbers/Letters only (between 4 and 25 chars).")
            name = Display.cooked_input("What's your name? ")

        Display.gameMsg("Welcome to the Letter Guessing Game,", name + "!")

        while state == "y":
            tries = 0
            maxTries = 7
            answer = ascii_uppercase[randint(0, 25)]