Ejemplo n.º 1
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;
Ejemplo n.º 2
0
    response = conn1.requestKey();

    if(response != False):
        KEY = response[0];
        SID = response[2];
    else:
        Display.errorMsg('Connection was rejected (maybe to too many people playing for too long?)');
        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:");

                # The user wants to go back instead of registering
                if(u.lower() == 'back' or p.lower() == 'back'): break;

                # Tell the user that we're doing things
Ejemplo n.º 3
0
    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;
    
# Begin the main python code
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':
conn1 = NetworkInterface()
conn1.status()

ascii_uppercase = ascii_uppercase[::-1]

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 + "!")