Пример #1
0
def main_menu():

    print(MAIN_MENU_TEXT)
    answer = prompt('\n>> ', '1', '2', '3', '4', '5', '6', 'r', 'R', 'q', 'Q',
                    '')
    if answer is 'q' or answer is 'Q':
        exit(0)
    elif answer is '1':
        gameshop.display()
    elif answer is '2':
        inventory.inv.display_inventory(player)
    elif answer is '3':
        inventory.inv.display_equipment(player)
    elif answer is '4':
        player.display_stats()
    elif answer is '5':
        battle(player, random.choice(low_level_monsters))
    elif answer is '6':
        usersave.save_game()
    elif answer is 'r' or answer is 'R':
        print("Hey, i'm still working on that :/")
        print(
            "Reset your save manually by deleting 'inventory.ini' and 'user_stats.ini' and run the game again"
        )
        prompt()
    main_menu()
Пример #2
0
def check_cheating():
    if player.health > player.max_health:
        print("Hey, your stats looks kinda weird.")
        print("One would think you might have tampered with some .ini files.")
        print("*Wink wink* ;)")
        prompt()
        return True
    return False
Пример #3
0
    def death(self):
        clear_screen()
        print(f"""
--- Oh dear, {self.name} Died! ---

Restart the game to keep playing.
Your stats will keep going from the last point you saved.

---""")
        prompt("< Press Enter to exit. >")
        exit(0)
Пример #4
0
def run():
    try:
        outputs = get_xrandr()

        connected_mapped_outputs = {
            outputName: output
            for outputName, output in outputs.items()
            if output['isConnected'] and output['isMapped']
        }
        connected_unmapped_outputs = {
            outputName: output
            for outputName, output in outputs.items()
            if output['isConnected'] and not output['isMapped']
        }
        outputs_to_cleanup = {
            ('clean ' + outputName): output
            for outputName, output in outputs.items()
            if not output['isConnected'] and output['isMapped']
        }
        main_choices = sorted(
            chain.from_iterable([
                connected_unmapped_outputs,
                connected_mapped_outputs,
                outputs_to_cleanup,
            ]))

        selected_output_name = prompt(main_choices)

        if selected_output_name in connected_mapped_outputs:
            selected_output = connected_mapped_outputs[selected_output_name]

            if selected_output['isPrimary']:
                actions = ACTIONS_PRIMARY
            else:
                actions = ACTIONS_SEGONDARY
            action = prompt(actions, prompt=selected_output['name'])

            if action == MOVE:
                run_move(outputs, selected_output)
            elif action == MODE:
                run_mode(selected_output)
            elif action == SHUTDOWN:
                run_shutdown(selected_output)
        elif selected_output_name in connected_unmapped_outputs:
            selected_output = connected_unmapped_outputs[selected_output_name]

            run_move(outputs, selected_output, is_auto=True)
        elif selected_output_name in outputs_to_cleanup:
            selected_output = outputs_to_cleanup[selected_output_name]
            run_shutdown(selected_output)

    except InvalidValue:
        pass
Пример #5
0
    def display_stats(self):
        clear_screen()
        print(f"""
_________________________________________
||| Displaying stats of {self.name} |||
- Attack: {self.attack}
- Defence: {self.defence}
- Health: {self.health}/{self.max_health}
- Gold: {self.gold}
- Luck: {self.luck}

(Higher Luck = Increased chance of running
away from monsters and unique drops)
_________________________________________""")
        prompt()
Пример #6
0
def linkatom():
    targetdir = os.path.join( homedir, '.atom' )
    atomdir = os.path.join( sourcedir, 'atom' )

    if not os.path.isdir( targetdir ):
        print( "Atom directory doesn't exist! Please install atom on your system!")
        return

    for filename in os.listdir(atomdir):
        sourcepath = os.path.join( atomdir, filename )
        targetpath = os.path.join( targetdir, filename )

        if os.path.islink(targetpath):
            print( "Removing existing symbolic link", targetpath )
            print( "rm -rf " + targetpath )
            subprocess.call( ["rm","-rf",targetpath] )

        # Query if already exists as regular file
        elif os.path.exists( targetpath ):
            if prompt.prompt( "Warning! Target " + targetpath + " already exists! Remove the existing path?" ):
                print( "rm -rf "+targetpath )
                subprocess.call(["rm","-rf",targetpath] )
            else:
                print("Warning! Skipping over project:", sourcepath )

        # Linking source file:
        print( "Soft linking:", sourcepath, '->', targetpath )
        subprocess.call( ["ln","-s",sourcepath,targetpath] )
Пример #7
0
def tick():

    dispatcher.send(signals.BEFORE_TICK, tick)

    for clientId in disconnectedClients:
        client.clientDisconnectedFromServer(clientId)

    for clientId in newClients:
        client.clientConnectedToServer(clientId)

    for clientId in flushedClients:
        cmds.clientFlushedCmdQueue(clientId)

    for cmd in clientCmds:
        cmds.clientSentCmd(cmd.key(), cmd.data())

    cmds.handleNextCmdForAllClients()

    def keys(intStringMap):
        return map(lambda i: i.key(), intStringMap)

    map(
        lambda clientId: send.sendToClient(clientId,
                                           prompt.prompt(clientId, clientId)),
        list(set(keys(clientCmds)).union(keys(send.clientMsgs))))

    dispatcher.send(signals.AFTER_TICK, tick)
Пример #8
0
def run_move(outputs, selected_output, is_auto=False):
    direction = prompt(DIRECTIONS, prompt=selected_output['name'])

    remaining_outputs = [
        outputName for outputName, output in outputs.items()
        if output != selected_output and output['isConnected']
        and output['isMapped']
    ]

    reference = prompt(remaining_outputs,
                       prompt=(selected_output['name'] + ' ' + direction))

    set_position(selected_output['name'],
                 XRANDR_OPTIONS_MOVE[direction],
                 reference,
                 auto_mode=is_auto)
Пример #9
0
def softlink():
    """
    Soft link process except for special directories
    """
    print ("Soft linking files in {0} to {1}".format(sourcedir,homedir))

    for filename in os.listdir(sourcedir):
        # ignoring special files
        if filename in special     : continue
        # ignoring configuration file for this package
        if filename.startswith('.'): continue

        sourcepath = os.path.join(sourcedir,filename)
        targetpath = os.path.join(homedir,'.'+filename)
        print( sourcepath, '->', targetpath )

        # Clearing symbolic links
        if os.path.islink(targetpath):
            print( "Removing existing symbolic link", targetpath )
            print( "rm -rf " + targetpath )
            subprocess.call( ["rm","-rf",targetpath] )

        # Query if already exists as regular file
        elif os.path.exists( targetpath ):
            if prompt.prompt( "Warning! Target " + targetpath + " already exists! Remove the existing path?" ):
                subprocess.call(["rm","-rf",targetpath] )
            else:
                print("Warning! Skipping over project:", sourcepath )

        # Linking source file:
        print( "Soft linking:", sourcepath, '->', targetpath )
        subprocess.call( ["ln","-s",sourcepath,targetpath] )
Пример #10
0
def tick():

    dispatcher.send(signals.BEFORE_TICK, tick)

    for clientId in disconnectedClients:
        client.clientDisconnectedFromServer(clientId)

    for clientId in newClients:
        client.clientConnectedToServer(clientId)

    for clientId in flushedClients:
        cmds.clientFlushedCmdQueue(clientId)

    for cmd in clientCmds:
        cmds.clientSentCmd(cmd.key(), cmd.data())

    cmds.handleNextCmdForAllClients()

    def keys(intStringMap):
        return map(lambda i: i.key(), intStringMap)

    map(
        lambda clientId: send.sendToClient(clientId, prompt.prompt(clientId, clientId)),
        list(set(keys(clientCmds)).union(keys(send.clientMsgs))),
    )

    dispatcher.send(signals.AFTER_TICK, tick)
Пример #11
0
    def display_equipment(self, player):
        print(f"||| Equipment of {player.name} |||")
        if not self.equipment:
            print(f"{player.name} has no items equipped!")
            prompt()
            return
        for item in self.equipment.values():
            print("________________________________")
            if item.item_type is 'Weapon':
                print(f"[ Weapon: ] {item.name} (+{item.attack} Attack)")
            if item.item_type is 'Armour':
                print(f"[ Armour: ] {item.name} (+{item.armour} Armour)")
            print(f"Sell value: {item.sell_value} Gold")
        print("""
________________________
| [ 1 ] Unequip Weapon  |
| [ 2 ] Unequip Armour  |
|                       |
| [ Q ] Go back         |
|_______________________|""")
        answer = prompt("\n>> ", 'Q', 'q', '1', '2')
        if answer is 'q' or answer is 'Q':
            return
        if answer is '1':
            for item in self.equipment.values():
                if item.item_type is 'Weapon':
                    self.unequip_item(item)
                    prompt()
                    return
        elif answer is '2':
            for item in self.equipment.values():
                if item.item_type is 'Armour':
                    self.unequip_item(item)
                    prompt()
                    return
Пример #12
0
    def run(self, path, print_file=True):
        from functools import reduce
        import prompt

        if print_file and self.print_file:
            _print_file(path)

        util.info("description: " + self.description)

        if type(self.deduction) is int:
            choices = ["do not take this deduction",
                       "take this deduction (-{} points)".format(
                           self.deduction)]
            got = prompt.prompt(choices, '1')

            if got == [1]:
                return {'deduction': self.deduction,
                        'description': self.description}
            else:
                util.info("taking no points")
                return None

        elif type(self.deduction) is list:
            choices = ["{} (-{} {})".format(y, x, util.plural("point", x)) for
                       x, y in self.deduction]
            got = prompt.prompt(choices, self.deduction_mode)

            total_deducted = sum(map(lambda x: self.deduction[x][0], got))
            if total_deducted > 0:
                deductions = []

                for s in got:
                    if self.deduction[s][0] > 0:
                        d = {'deduction': self.deduction[s][0],
                             'description': self.deduction[s][1]}
                        deductions.append(d)

                return {'description': self.description + ':',
                        'subresults': deductions}
            else:
                util.info("taking no points")
                return None
Пример #13
0
    def run(self, path):
        import os
        from functools import reduce
        import prompt
        _print_file(path)

        sprint("reviewing '{}' (in directory '{}')".format(
               path, os.getcwd()))
        sprint("description: " + self.description)

        if type(self.deduction) is int:
            choices = ["do not take this deduction",
                       "take this deduction (-{} points)".format(
                           self.deduction)]
            got = prompt.prompt(choices, '1')

            if got == [1]:
                return {'deduction': self.deduction,
                        'description': self.description}
            else:
                sprint("taking no points")
                return None

        elif type(self.deduction) is list:
            choices = ["{} (-{} {})".format(y, x, plural("point", x)) for
                       x, y in self.deduction]
            got = prompt.prompt(choices, self.deduction_mode)

            if sum(map(lambda x: self.deduction[x][0], got)) > 0:
                deductions = []

                for s in got:
                    if self.deduction[s][0] > 0:
                        d = {'deduction': self.deduction[s][0],
                             'description': self.deduction[s][1]}
                        deductions.append(d)

                return deductions
            else:
                sprint("taking no points")
                return None
Пример #14
0
def display():
    shop_list = {}
    clear_screen()
    print("||| Shop |||")
    index = 0
    for item in shop_entries:
        index += 1
        shop_list[index] = item
        print("________________________________")
        if item.item_type is 'Armour':
            print(f"[ {index} ] {item.name} (+{item.armour} Armour)")
        if item.item_type is 'Weapon':
            print(f"[ {index} ] {item.name} (+{item.attack} Attack)")
        if item.item_type is 'Health_Potion':
            print(f"[ {index} ] {item.name} (+{item.heal_value} Health)")
        print(f"Cost: {item.buy_value}")
    print(f"""
Your Gold: [ {player.gold} ]

[ 1-{index} ] Buy Item
[ S ] Sell items
[ Q ] Go Back""")
    options = ('q', 'Q', 's', 'S')
    for item in range(index + 1):
        options += (str(item), )
    answer = prompt("\n>> ", *options)
    if answer is 'q' or answer is 'Q':
        return
    elif answer is 's' or answer is 'S':
        sell_inventory_items()
        display()
    else:
        try:
            buy_item(shop_list[int(answer)])
            prompt()
            display()
        except (IndexError, TypeError, KeyError, ValueError):
            print("Item not found.")
            prompt()
            display()
            return
Пример #15
0
def main():

    #this runs a series of questions in the structure of a short converstation, getting needed variables for a madlibs story
    import prompt 
    name,location,feeling,animalName,bestFriend,activity,relitive = prompt.prompt()

    #count down here?







    #stories

    story1 = "Once upon a time there was a elephant named "+name+" who was owned by a man named "+animalName+". In the city of "+location+" was the "+relitive+"'s zoo, it was here that "+name+" would spend each day "+activity+". Feeling "+feeling+" "+name+" decided to run off and chase his/her dreams of "+activity+". In sharing plans with "+bestFriend+" it became clear to "+name+" that it would be really hard to do this. So "+name+" decided to stay at the zoo. \n"   

    story2 = name+" was walking his pet named "+animalName+" through "+location+". When suddenly a wild "+relitive+" came out of nowhere! "+name+" reacted quickly by "+activity+", which made him/her feel "+feeling+" and they didnt want to be "+activity+" anymore. They called "+bestFriend+" who they showed up with a helicopter. So "+name+" lived to see another day \n"   

    #list of stories...

    stories = [story1, story2];

    storiesNum = len(stories)

    #print(storiesNum)

    def storyChoicePrompt():
        choice = eval(input('We have '+str(storiesNum)+' stories to choose from... pick one (enter a number 1-'+str(storiesNum)+')\n'))
        return choice


    def storyChoiceCheck():
        if (choice > storiesNum) or (choice < 0) or (choice==""):
            print("Errored input! Try again...")
            storyChoicePrompt()
            storyChoiceCheck()
        else:
            print ("\n",stories[choice-1])
            file = open("newfile.txt", "w")

            file.write(stories[choice-1])





                #actually have them pick the storie...

    choice = storyChoicePrompt()
    storyChoiceCheck()
Пример #16
0
def create_user_data():
    if settings_exist():
        user = read_save_status(file=STATUS_FILE)
        read_inventory_status()
        if user.health <= 0:
            create_save(user.name)
            user = read_save_status(file=STATUS_FILE)
            return user
        return user
    else:
        user_name = prompt("\n< How are you called? >\n\n>> ")
        create_save(user_name)
        user = read_save_status(file=STATUS_FILE)
    return user
Пример #17
0
def installvim():
    basedir   = os.path.join(homedir,".vim","bundle")
    vundledir = os.path.join(basedir,"Vundle.vim")

    if os.path.isdir( vundledir ):
        return ## Vundle install, skipping
    elif os.path.exists( vundledir ):
        if prompt.prompt('Warning! File '+ vundledir + ' already exists! Remove the existing path?'):
            subprocess.call(['rm','-rf',vundledir])
        else:
            print('Please manually install the vim package manager Vundle.')
    else:
        print('First installation of vim plugins! Installing fresh version of Vundle')
        subprocess.call(["mkdir","-p",basedir])
        subprocess.call(["git","clone","https://github.com/gmarik/Vundle.vim.git","~/.vim/bundle/Vundle.vim/"])
        print('Manually install defined plugins via the ":PluginUpdate" command in a vim session')
Пример #18
0
    def __should_fail(self, result):
        """Called before an eval test is about to be failed, but the criteria
        specifies that a human should confirm the failure before taking
        any points. If this method returns True, the points are ultimately
        taken.
        """
        import sys
        from grader import write_results
        from prompt import prompt

        util.warning("about to fail a test")

        write_results(sys.stdout, [result])

        points = result['deduction']
        s = util.plural("point", points)
        fail_msg = "fail this test (-{} {})".format(points, s)

        choices = [fail_msg, "do not fail this test"]
        return prompt(choices, '1') == [0]
Пример #19
0
def movement(directions):
    """Movement things!"""

    if type(directions) != str:
        print("Error: ment() was passed an invalid argument (not a str).")
        exit(0)

    north = ['North', 'north', 'Up', 'up', 'N', 'n', 'U', 'u']
    south = ['South', 'south', 'Down', 'down', 'S', 's', 'D', 'd']
    east = ['East', 'east', 'Right', 'right', 'E', 'e', 'R', 'r']
    west = ['West', 'west', 'Left', 'left', 'W', 'w', 'L', 'l']

    while True:

        answer = prompt('feedback')

        if 'n' in directions and answer in north:
            aim = 'n'
            break

        elif 's' in directions and answer in south:
            aim = 's'
            break

        elif 'e' in directions and answer in east:
            aim = 'e'
            break

        elif 'w' in directions and answer in west:
            aim = 'w'
            break

        else:
            print("\n\tYou can't go that way...\n")

    return aim
Пример #20
0
def sell_inventory_items():
    if not inventory.inv.items.values():
        print("You don't have any items to sell.")
        prompt()
        return
    inventory_list = {}
    index = 0
    for item in inventory.inv.items.values():
        index += 1
        inventory_list[index] = item
        print("________________________________")
        if item.item_type is 'Armour':
            print(f"[ {index} ] {item.name} (+{item.armour} Armour)")
            print(f"Sell Value: {item.sell_value}")
        if item.item_type is 'Weapon':
            print(f"[ {index} ] {item.name} (+{item.attack} Attack)")
            print(f"Sell Value: {item.sell_value}")
        if item.item_type is 'Health_Potion':
            print(f"[ {index} ] {item.name} (+{item.heal_value} Health)")
            print(f"Sell Value: {item.sell_value}")
    print(f"\nYour Gold: {player.gold}")
    print(f"\n[ 1-{index} ] Sell Item")
    print("[ Q ] Go back")
    answer = prompt("\n>> ")
    if answer is 'q' or answer is 'Q':
        display()
        return
    else:
        try:
            sell_item(inventory_list[int(answer)])
            prompt()
            sell_inventory_items()
        except (IndexError, TypeError, KeyError, ValueError):
            print("Item not found.")
            prompt()
            sell_inventory_items()
Пример #21
0
 def drink_potion(self, item, player, message=True):
     if item.name in self.items:
         if item.item_type is 'Health_Potion':
             start_health = player.health
             if player.health == player.max_health:
                 print(
                     f"You already have max health! ({player.max_health})")
                 prompt()
                 return
             player.health += item.heal_value
             if player.health > player.max_health:
                 player.health = player.max_health
             final_health = player.health
             if message is True:
                 print(
                     f"{player.name} drank {item.name} and gained {final_health-start_health} HP."
                 )
                 print(f"Current HP: {player.health}/{player.max_health}")
             self.remove_item(item)
             prompt()
     else:
         if message is True:
             print("You don't have that potion.")
             prompt()
Пример #22
0
def d(): 
	COUNT = 0.0
	E = 1.6e-19 
	EIONPR = 34.0e-6 
	IFIT = 1 
	NP = 1
	PI = 3.14159265358979 
	STDRHO = 2.689E+25
	TAU = 0.0
	I = 0
	while (I < 1025) :
		FIRST[I] = math.exp(–I)
		SECOND[I] = math.exp(-I / 1024.0)
		I += 1
	
	#DONPUT initializations
	GLS = [[0.201, 0.5132, 0.7515, 1.0, 1.266], [1.602, 2.027, 2.887, 4.110, 5.202], [0.0, 2.3, 5.2, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.3, 0.5, 1.0, 1.5]]
	GUS = [[0.5132, 0.7515, 1.0, 1.266, 1.602], [2.027, 2.887, 4.110, 5.202, 8.332], [2.3, 5.2, 9.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.5, 1.0, 1.5, 2.0]]
	FRACS = [[0.0358, 0.0641, 0.0728, 0.0934, 0.1170], [0.1343, 0.1814, 0.1288, 0.1209, 0.0515], [0.573, 0.388, 0.039, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.173, 0.362, 0.257, 0.208]]
	NS = [10, 3, 4]
	DNN = [[1.656e22, 7.694e21, 1.417e21, 1.064e22]]
	GLSN = [[4.0, 7.0, 9.0, 13.0]]
	GUSN = [[7.0, 10.0, 13.0, 14.0]]
	NSN = [4]
	
	#Test run initializations follow
	RADS = [[0.0, 2.536e25], [1.0e3, 2.302e25], [2.0e3, 2.0847e25], [3.0e3, 1.882e25], [4.0e3, 1.696e25], [5.0e3, 1.525e25], [6.0e3, 1.367e25], [7.0e3, 1.221e25], [8.0e3, 1.089e25], [9.0e3, 9.670e25], [1.0e3, 8.560e25], [1.5e4, 4.032e24], [2.0e4, 1.840e24], [2.5e4, 8.297e23], [3.0e4, 3.811e23]]
	DR = 50
	NDR = 250
	NT = 16
	HOB = 5000
	RSTART = 500
	if (RSTART + DR * NDR > HOB) :
		DR = (HOB - RSTART) / NDR
	IPROMPT = "YES"
	NGAMMA = "YES"
	ISOMER = "NO"
	
	#LOOP TO FILL THE TIME STEP ARRAYS
	I = 0
	while (I < 10) :
		DTS[I] = 1e-9
		NDTS[I] = 15
		I += 1
	
	NGS = 10
	IRAD = “STA”
	
	#60 branch
	I = 0
	while (I < 15) :
		RAD[0][I] = RADS[0][I]
		RAD[1][I] = RADS[1][I]
		I += 1
	
	#THESE STATEMENTS DETERMINE THE WEAPON PROMPT GAMMA CHARACTERISTICS
	CASEP = 2
	DT = 3e-8
	DTDR = DT / DR
	NMAX = 200
	TRIP = 5e-7
	NCAL = 1
	GCAL = 1e33
	SIZ = 10
	IFUN = 1
	ALPHA = 2e9
	BETA = 5e8
	TPEAK = 1e-7
	
	#THESE STATEMENTS DETERMINE THE PROMPT GAMMA ENERGY GROUPS
	I1 = 1 #Added to ensure prompt subroutine is run
	ISPEC = "SPE"
	NSPEC = 0
	SUMS = 0.0
	NGROUP = NS[NSPEC] #330 Branch
	I = 0
	while (I < NGROUP) :
		GRPLO[I] = GLS[I][NSPEC]
		GRPHI[I] = GUS[I][NSPEC]
		FRAC[I] = FRACS[I][NSPEC]
	curfit.curfit(GRPLO, GRPHI, eg, rg, ee, re, aa, bb, ff, NGROUP, PI, sigm)
	
	#THESE STATEMENTS SET UP THE NEUTRON-GAMMA SPECTRUM 
	I2 = 1
	CASEN = 1e30
	ISPECN = "SPE"
	NSPECN = 0
	NGRPN = NSN(NSPECN)
	I = 0
	while (I < NGRPN) :
		GRPLON[I] = GLSN[I][NSPECN]
		GRPHIN[I] = GUSN[I][NSPECN]
		DN[I] = DNN[I][NSPECN]
	
	convert.convert(cn, cnn, eg, g, g1, g2, GRPHI, GRPLO, H, hz, NGRPN)
	
	#GAMMA was not run in the Test Run data
	#gamma.gamma(ai, ciso, di, DN, DT, edep, edei, eden, engi, engp, engn, FRAC, fracis, gdoti, gdotn, GRPHI, grphii, GRPHIN, GRPLO, grploi, GRPLON, gdot, gtime, GCAL, hz, I1, IFUN, ndei, nden, NGROUP, ngrpi, NGRPN, ntrani, rdt, SIZ, sn, sor, totali, totaln, trani, peak)
	
	#End of test run initializations
	
	CINC = 3 * NDR * NT 
	CONJ = E / (4.0 * PI) 
	CONQ = 1.0 / (EIONPR * 4.0 * PI) 
	DNT = PI / NT
	DR2 = DR * 0.5 
	DTDR2 = DTDR * 0.5 
	NT2 = NT / 2 
	NTMI1 = NT - 1
	I = 0
	while (I < NDR) :
		R[I] = RSTART + I * DR
		R2[I] = R[I]**2
		if (NP != 2) :
			if (R[I] - 500.0 + DR2 >= 0) : #10
				NPR = I #20
				NP = 2
		I += 1 #30
	
	#PROMPT PARAMETERS
	if (I1 != 2) :
		K = 0
		while (K < NGROUP) : #40
			EERG[K] = (EE[K] * SIGM[K] + EG[K] * (1.0 – SIGM[K])) / RG[K] 
			FC[K] = 1.0 – FF[K] * 1.0e3 / RG[K]
			FREG[K] = FRAC[K] / EG[K]
			RERG[K] = RE[K] / RG[K] * SIGM[K]
			RGI[K] = 1.0 / RG[K]
			K += 1 #50
		N = 0
		while (N < NMAX) :
			TDR[N] = N * DTDR + DTDR2
			ROOT[N] = math.sqrt(TDR[N])
			N += 1 #60
		
	#N-GAMMA PARAMETERS
	if (I2 != 2) : #70
		M = 0
		while (M < NGRPN) : #80
			DN[M] =  DN[M] * CASEN
			M += 1 #90
		
	#ISOMERIC PARAMETERS - not running ISOMER per Colonel Fee
	#if (I3 != 2) : #100
	#	L = 0
	#	while (L < NISO) : #110
	#		ROOTKI[L] = math.sqrt(DI[L])
	#		DII[L] = 1.0 / DI[L]
	#		CONISO[L] = AI[L] * DI[L]
	#		L += 1 #120
		
	#DAWSON INTEGRAL VALUES - not running ISOMER (the only subroutine to use DAWSON) per Colonel Fee
	#A0 = 0.5
	#A1 = 0.241958349
	#A2 = 0.675059021
	#I = 0
	#while (I < 10) :
	#	BI = I
	#	if (I == 0) :
	#		FACTOR[I] = 1.0 #130
	#	else :
	#		FACTOR[I] = (2.0 * BI - 3.0) / ((2.0 * BI - 1.0) * (BI - 1.0)) #140
	#	I += 1 #150
	#K = 0
	#while (K < NGRPI) :
	#	EERGI[K] =  (EEISO[K] * SIGMI[K] + EGISO[K] * (1.0 - SIGMI[K])) / RGISO[K]
	#	FCISO[K] = 1.0 - FFISO[K] * 1e3 / RGISO[K]
	#	RERGI[K] = REISO[K] / RGISO[K] * SIGMI[K]
	#	FREGI[K] = FRANCIS[K] / EGISO[K]
	#	RGISCI[K] = 1.0 / RGISO[K]
	#	K += 1 #160
	
	#RELATIVE AIR DENSITY AND INTEGRAL OF RHO * DR CALCULATION
	reldens.reldens(NRAD, RAD, STDRHO, NTM1, DNT, R, HOB, DR2, RHO, DRRHO, DR, NDR, NT, RHOH, DRRHOH) #170
	
	#Open save file
	fh = open("D Code Output.txt", "w")
	fh.write("TIME\tRANGE\tCURRENT\tION-RATE(H)\tIONRATE\n")
	
	#Main loop - yes, everything previous was initialization!
	NS = 0
	while (NS < NGS) :
		#RESTART check at 180 removed - subroutine not needed in Python
		ITIME = 1 #190
		DT = DTS[NS] #200
		NDT = NDTS[NS]
		DT2 = DT * 0.5
		RDT = 2.0 / (RHO[0][NT2 - 1] * DT)
		#"SENSE SWITCH" code at 871 and 872 removed - we have much better ways of aborting programs now!
		if (COUNT - 3.5e6 < 0) : #if >= 0, program terminates
			COUNT = COUNT + CINC #210
			TAU = TAU + DT
			I = 0
			while (I < NDR) :
				J = 0
				while (j < NT) :
					FJH[I][J] = 0.0
					QH1[I][J] = QH[I][J] – QH1[I][J]
					QH[I][J] = 0.0
					J += 1 #220
				J = 0
				while (J < NTM1) :
					Q1[I][J] = Q[I][J] – Q1[I][J]
					Q[I][J] = 0.0
					J += 1 #230
				I += 1 #240
			
			#CALCULATE THE CURRENT AND IONIZATION RATE
			if (I1 != 2) :
				prompt.prompt(DECG, FREG, DECQ, DECJ, L, EXP, IFIT, DT, DT2, NMAX, TRIP, TDR, SOURCE, SOR, DTDR, TAU, TPEAK, R, CONJ, CONQ, RHOH, DRRHOH, FC, FF, RERG, EERG, EG, BB, AA, SN, NGROUP, FJH, QH, RHO, DRRHO, RGI, Q, NTM1, NDR, NT)
			if (I2 != 2) :
				ngamma.ngamma(TAU, TPEAK, R, CONJ, CONQ, RHOH, DRRHOH, FC, FF, RERG, EERG, EG, BB, AA, SN, NGROUP, FJH, QH, RHO, DRRHO, RGI, Q, NTM1, NDR, NT)
			#not running ISOMER per Colonel Fee
			#if (I3 != 2) :
			#	ISOMER(AAISO, CISO, CONJ, CONQ, CONISO, DII, DRRHO, DRRHOH, EERGI, EGISO, EXKI, FCISO, FFISO, FJH, FREGI, NISO, NGRPI, NDR, NT, NGROUP, Q, QH, RHO, RHOH, R, RERG, RGISOI, ROOTKI, SORISO, TAU)
			#CONTINUE at 300 removed, as well as the following PRINT statement
			I = 0
			while (I < NDR) :
				J = 0
				while (J < NTM1) :
					QH[I][J] = QH[I][J] + QH1[I][J]
					Q[I][J] = Q[I][J] + Q1[I][J]
					J += 1 #310
				J = NT
				QH[I][J - 1] = QH[I][J - 1] + QH1[I][J - 1]
				I += 1 #320
			
			#print to file
			fh.write(str(TAU)+'\t') #write time
			fh.write(str(R[0])+'\t') #write range
			fh.write(str(FJH[0][NT2 - 1])+'\t') #write current
			fh.write(str(QH[0][NT2 - 1])+'\t') #write ion rate(h)
			fh.write(str(Q[0][NT2 - 1])+'\n') #write ion rate
			fh.write()
	
	#Close file
	fh.close()
Пример #23
0
def cli(args=sys.argv[1:]):
    parser = optparse.OptionParser(usage='%prog [options]', description=__doc__)

    parser.add_option('-d', '--workdir', dest='workdir',
                      action='store', default=None,
                      help='Set up everything in this directory')
    for resource in valid_resources['cli'].difference(valid_resources['default']):
        cmdlet = resource.replace('_', '-')
        parser.add_option('--prepare-%s' % cmdlet, dest=resource,
                          action='store_true', default=False,
                          help='Do whatever it takes to set up %s' % resource)
    parser.add_option('-m', '--metadata', dest='metadata',
                      action='append', default=[],
                      help='Append a piece of metadata in the form <key>=<value>. '
                           'Attempt to use this metadata wherever it makes sense. '
                           'Store values of duplicate keys in a list. E.g --metadata '
                           'user=foo --metadata user=bar --metadata branch=mozilla-central')
    parser.add_option('--no-prompt', dest='prompt_disabled',
                      action='store_true', default=False,
                      help='Never prompt me for any additional '
                           'information, error out instead')
    parser.add_option('--only', dest='only',
                      action='store_true', default=False,
                      help='Only prepare resources I explicitly specify (either by '
                           'command line or prompt)')
    parser.add_option('--store', dest='store',
                      action='store_true', default=False,
                      help='Store any usernames and passwords I enter for this session for '
                           'later use. Note: passwords will not be encrypted')
    parser.add_option('-l', '--log-level', dest='log_level', action='store',
                      type='choice', default='INFO',
                      choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
                      help='Only print messages at this log level')
    options, args = parser.parse_args(args)
    log.setLevel(getattr(mozlog, options.log_level))
    prompt.prompt_disabled = options.prompt_disabled

    # parse the metadata
    metadata = {}
    metadata['workdir'] = options.workdir
    metadata['store'] = options.store
    for data in options.metadata:
        k, v = data.split('=', 1)
        if k in metadata:
            if not isinstance(metadata[k], list):
                metadata[k] = [metadata[k]]
            metadata[k].append(v)
        else:
            metadata[k] = v

    # make sure only one device was specified
    resources = [r for r in valid_resources['all'] if getattr(options, r, False)]
    device = set(resources).intersection(valid_resources['device'])
    if len(device) > 1:
        raise MultipleDeviceResourceException(*device)

    # add the default resources
    if not options.only:
        resources.extend(list(valid_resources['default']))

    # prompt for additional resources if needed
    resources = prompt.prompt_resources(valid_resources, resources)

    # recursively add resources that depend on the resources so far
    if not options.only:
        def add_dependencies(res):
            for r in valid_resources[res]:
                if r in resources:
                    continue
                if res in resources:
                    resources.append(r)
                if r in valid_resources:
                    add_dependencies(r)
        t_resources = resources[:]
        for res in t_resources:
            if res in valid_resources:
                add_dependencies(res)

    # set the working directory
    device = list(set(resources).intersection(valid_resources['device']))
    if len(device) > 1:
        raise MultipleDeviceResourceException(*device)
    elif not device:
        device = list(set(resources).intersection(valid_resources['cli']))
    device = device[0]

    if not metadata['workdir']:
        metadata['workdir'] = os.path.join(os.getcwd(), 'b2g-workdir', device)
        if os.path.isdir(metadata['workdir']):
            if prompt.prompt("Resource '%s' already exists in the working directory, do you want to overwrite it?" % device) == "y":
                log.info("removing '%s'" % metadata['workdir'])
                shutil.rmtree(metadata['workdir'])
            else:
                metadata['workdir'] = prompt.prompt("Enter the full path to a new working directory:", [])

    if not os.path.isdir(metadata['workdir']):
        os.makedirs(metadata['workdir'])

    # build and dispatch the request
    build_request(resources, metadata)
Пример #24
0
def grade(criteria, submissions, filename,
          assume_missing=False, late_check=True):
    found = []
    num_missing = 0
    total = criteria.total_points

    for f in criteria.files:
        crit_dir, crit_name = os.path.split(f.path)

        for s in submissions:
            sub_dir, sub_name = os.path.split(s)

            if crit_name == sub_name:
                found.append(f)
                break
        else:

            util.warning("could not find file '{}'".format(f.path))

            if len(submissions) < 1:
                continue

            if not assume_missing:
                # find the submission directory (it could be the
                # current working directory, but maybe not)
                submission_dir, _ = os.path.split(submissions[0])

                if not submission_dir:
                    submission_dir = os.path.abspath(os.curdir)

                choices = [f for f in os.listdir(submission_dir)
                           if os.path.isfile(os.path.join(submission_dir, f))]
                choices.append("skip grading this submission now")
                choices.append("mark the file as missing")

                util.info("this student may have named the file incorrectly")

                # we prompt the grader for zero or one choice
                got = prompt(choices, '1')
                got = got[0]

                if got == len(choices) - 1:
                    # declare the file missing
                    num_missing += 1
                    continue

                elif got == len(choices) - 2:
                    util.info("skipping this submission")
                    util.exit(util.EXIT_WITH_DEFER)

                else:
                    # get absolute path to the old and new files
                    sname = choices[got]

                    opath = os.path.join(submission_dir, sname)
                    npath = os.path.join(submission_dir, crit_name)

                    try:
                        os.rename(opath, npath)
                    except:
                        util.error("error renaming incorrectly named file")
                        util.print_traceback()
                        util.exit(util.ERR_GRADING_MISC)

                    found.append(f)

    out = io.StringIO()

    try:
        for f in criteria.files:
            out.write(util.heading("{} [{} points]".format(f, f.point_value),
                                   level=2))

            if f not in found:
                total -= f.point_value
                out.write("-{}\tnot submitted\n".format(f.point_value))
                out.write("\n\n")
                continue

            util.info("running tests for " + str(f))

            points_taken = 0
            points_taken += write_results(out, f.run_tests())

            if late_check:
                file_stat = os.stat(f.path)
                mtime = datetime.datetime.fromtimestamp(file_stat.st_mtime)

                mult = criteria.get_late_penalty(mtime)
                late_penalty = f.point_value * mult

                if late_penalty != 0:
                    util.warning("taking {}% late penalty".format(mult * 100))

                    adjusted = min(f.point_value - points_taken, late_penalty)
                    out.write("-{}\tsubmitted late\n".format(adjusted))
                    points_taken += adjusted

            total -= min(f.point_value, points_taken)

            out.write("\n")

        out.write("\nTotal: {}\n".format(total))

    except KeyboardInterrupt:
        out.close()

        util.warning("stopping (received interrupt)")
        util.exit(util.ERR_INTERRUPTED)

    except:
        out.close()

        util.exit(util.ERR_GRADING_MISC)

    with open(filename, 'w') as f:
        out.seek(0)
        f.write(out.read())

    return num_missing
Пример #25
0
    def display_inventory(self, player):
        print(f"||| Inventory of {player.name} |||")
        if not self.items:
            print(f"\nInventory of {player.name} is empty!")
            prompt()
            return
        for item in self.items.values():
            print("________________________________")

            if item.item_type is 'Weapon':
                print(
                    f"[ x{item.quantity} {item.name} ] (+{item.attack} Attack)"
                )
            if item.item_type is 'Armour':
                print(
                    f"[ x{item.quantity} {item.name} ] (+{item.armour} Armour)"
                )
            if item.item_type is 'Health_Potion':
                print(
                    f"[ x{item.quantity} {item.name} ] (+{item.heal_value} Health)"
                )
            print(f"Sell value: {item.sell_value} Gold")
        print("""
 _____________________
| [ 1 ] Equip Weapon  |
| [ 2 ] Equip Armour  |
| [ 3 ] Drink Potion  |
|                     |
| [ Q ] Go back       |
|_____________________|""")
        answer = prompt(">> ", 'q', 'Q', '1', '2', '3')
        if answer is 'q':
            return

        if answer is '1':
            clear_screen()
            weapons = []
            index = 1
            for item in self.items.values():
                if item.item_type is 'Weapon':
                    weapons.append(item)
            print("||| Weapons in Inventory |||")
            for item in weapons:
                print("________________________________")
                print(f"[ {index} ] {item.name} (+{item.attack} Attack)")
                index += 1
            equip_options = ('q', 'Q')
            for item_option in range(index):
                equip_options += (str(item_option), )
            print(f"\n[ 1-{index-1} ] Equip Weapon")
            print("[ Q ] Go back")
            answer = prompt("\n>> ", *equip_options)
            if answer is 'q' or answer is 'Q':
                return
            else:
                try:
                    pos = int(answer) - 1
                    self.equip_item(weapons[pos])
                except (IndexError, TypeError):
                    print("Item not found.")
                prompt()
                return

        if answer is '2':
            clear_screen()
            armours = []
            index = 1
            for item in self.items.values():
                if item.item_type is 'Armour':
                    armours.append(item)
            print("||| Armours in Inventory |||")
            for item in armours:
                print("________________________________")
                print(f"[ {index} ] {item.name} (+{item.armour} Armour)")
                index += 1
            equip_options = ('q', 'Q')
            for item_option in range(index):
                equip_options += (str(item_option), )
            print(f"\n[ 1-{index-1} ] Equip Armour")
            print("[ Q ] Go back")
            answer = prompt("\n>> ", *equip_options)
            if answer is 'q' or answer is 'Q':
                return
            else:
                try:
                    pos = int(answer) - 1
                    self.equip_item(armours[pos])
                except (IndexError, TypeError):
                    print("Item not found.")
                prompt()
                return
        if answer is '3':
            clear_screen()
            index = 1
            item_options = []
            print(
                f"||| Current Health: {player.health}/{player.max_health} |||\n"
            )
            for item in self.items.values():
                if item.item_type is 'Health_Potion':
                    item_options.append(item)
                    print("________________________________")
                    print(
                        f"[ {index} ] {item.name} (+{item.heal_value} Health)")
                    index += 1
            drink_options = ('q', 'Q')
            for item_option in range(index):
                drink_options += (str(item_option), )
            print(f"\n[ 1-{index-1} ] Drink Potion")
            print("[ Q ] Go back")
            answer = prompt("\n>> ", *drink_options)
            if answer is 'q' or answer is 'Q':
                return
            try:
                pos = int(answer) - 1
                self.drink_potion(item_options[pos], player)
            except (IndexError, TypeError):
                print("Item not found.")
                prompt()
                return
Пример #26
0
def battle(player, npc):
    """
    :param player: Monster
    :param npc: Player
    :return: None
    """
    for item in inventory.inv.equipment.values():
        if item.item_type == 'Weapon':
            weapon_attack = item.attack
            break
    else:
        weapon_attack = 0
    for item in inventory.inv.equipment.values():
        if item.item_type == 'Armour':
            armour_defence = item.armour
            break
    else:
        armour_defence = 0
    effective_player_defence = player.defence + armour_defence
    effective_player_attack = player.attack + weapon_attack
    npc.health = npc.max_health
    print(f"""
______ {player.name} Vs {npc.name} ______

- {player.name} HP: {player.health}/{player.max_health}
- {player.name} Attack: {player.attack} + {weapon_attack} from Weapon ({effective_player_attack})
- {player.name} Defence: {player.defence} + {armour_defence} from Armour ({effective_player_defence})
-----------------------------------------
- {npc.name} HP: {npc.health}/{npc.max_health}
- {npc.name} Attack: {npc.attack}
- {npc.name} Defence: {npc.defence}
__________________________________________
    """)
    prompt()

    while True:
        player_hit = random.randint(
            0, effective_player_attack) - random.randint(0, npc.defence)
        npc_hit = random.randint(0, npc.attack) - random.randint(
            0, effective_player_defence)
        if player_hit < 0:
            player_hit = 0
        if npc_hit < 0:
            npc_hit = 0
        player.health -= npc_hit
        npc.health -= player_hit

        print(f"""
______ {player.name} Vs {npc.name} ______
{player.name} hit {player_hit}.
{npc.name} hit {npc_hit}.
-----------------------------------------
- {player.name} HP: {player.health}/{player.max_health}
- {npc.name} HP: {npc.health}/{npc.max_health}
__________________________________________""")
        if player.health <= 0:
            player.death()
        if npc.health <= 0:
            break
        print(f"""
[ Enter ] Attack
[   1   ] Attack
[   2   ] Drink HP Potion
[   Q   ] Run Away!

Current Run chance: {player.luck} roll(s) at 1/5 Chance.""")
        answer = prompt("\n>> ", '', '1', '2', 'q', 'Q')
        if answer is '1':
            pass
        elif answer is '2':
            for item in inventory.inv.items.values():
                if item.item_type is 'Health_Potion':
                    inventory.inv.drink_potion(item, player)
            else:
                print("You don't have any Health Potions.")
                prompt()
        if answer is 'q' or answer is 'Q':
            for number in range(player.luck):
                if random.randint(0, 5) is 5:
                    clear_screen()
                    print("You ran away successfully. What a coward!")
                    prompt()
                    return
            clear_screen()
            print("You couldn't get away! Tough luck.")
            prompt()

    gold_reward = random.randint(0, npc.gold_drops)
    print(f"""
[ {player.name} beat {npc.name} successfully. ]

[ HP: {player.health}/{player.max_health} ]
________________________________________________
[      REWARDS      ]

[ Gold: {gold_reward} ]
    """)
    for number in range(player.luck):
        if random.randint(0, npc.extra_drop_rate) == npc.extra_drop_rate:
            try:
                print(f"[ Other: {npc.extra_drop.name} ]")
                inventory.inv.add_item(npc.extra_drop)
                break
            except AttributeError:
                pass
    else:
        print("[ Other: None ]")
    player.level_up(skill='attack', chance=7, increase=5)
    player.level_up(skill='defence', chance=25, increase=3)
    player.level_up(skill='health', chance=15, increase=5)
    player.level_up(skill='luck', chance=5, increase=2)

    player.gold += gold_reward
    prompt()
Пример #27
0
def main():
    check_cheating()
    print(START_TEXT)
    prompt()
Пример #28
0
def run_mode(selected_output):
    mode = prompt(selected_output['modes'], prompt=selected_output['name'])
    set_mode(selected_output['name'], mode)
Пример #29
0
def cli(args=sys.argv[1:]):
    parser = optparse.OptionParser(usage='%prog [options]',
                                   description=__doc__)

    parser.add_option('-d',
                      '--workdir',
                      dest='workdir',
                      action='store',
                      default=None,
                      help='Set up everything in this directory')
    for resource in valid_resources['cli'].difference(
            valid_resources['default']):
        cmdlet = resource.replace('_', '-')
        parser.add_option('--prepare-%s' % cmdlet,
                          dest=resource,
                          action='store_true',
                          default=False,
                          help='Do whatever it takes to set up %s' % resource)
    parser.add_option(
        '-m',
        '--metadata',
        dest='metadata',
        action='append',
        default=[],
        help='Append a piece of metadata in the form <key>=<value>. '
        'Attempt to use this metadata wherever it makes sense. '
        'Store values of duplicate keys in a list. E.g --metadata '
        'user=foo --metadata user=bar --metadata branch=mozilla-central')
    parser.add_option('--no-prompt',
                      dest='prompt_disabled',
                      action='store_true',
                      default=False,
                      help='Never prompt me for any additional '
                      'information, error out instead')
    parser.add_option(
        '--only',
        dest='only',
        action='store_true',
        default=False,
        help='Only prepare resources I explicitly specify (either by '
        'command line or prompt)')
    parser.add_option(
        '--store',
        dest='store',
        action='store_true',
        default=False,
        help='Store any usernames and passwords I enter for this session for '
        'later use. Note: passwords will not be encrypted')
    parser.add_option('-l',
                      '--log-level',
                      dest='log_level',
                      action='store',
                      type='choice',
                      default='INFO',
                      choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
                      help='Only print messages at this log level')
    options, args = parser.parse_args(args)
    log.setLevel(getattr(mozlog, options.log_level))
    prompt.prompt_disabled = options.prompt_disabled

    # parse the metadata
    metadata = {}
    metadata['workdir'] = options.workdir
    metadata['store'] = options.store
    for data in options.metadata:
        k, v = data.split('=', 1)
        if k in metadata:
            if not isinstance(metadata[k], list):
                metadata[k] = [metadata[k]]
            metadata[k].append(v)
        else:
            metadata[k] = v

    # make sure only one device was specified
    resources = [
        r for r in valid_resources['all'] if getattr(options, r, False)
    ]
    device = set(resources).intersection(valid_resources['device'])
    if len(device) > 1:
        raise MultipleDeviceResourceException(*device)

    # add the default resources
    if not options.only:
        resources.extend(list(valid_resources['default']))

    # prompt for additional resources if needed
    resources = prompt.prompt_resources(valid_resources, resources)

    # recursively add resources that depend on the resources so far
    if not options.only:

        def add_dependencies(res):
            for r in valid_resources[res]:
                if r in resources:
                    continue
                if res in resources:
                    resources.append(r)
                if r in valid_resources:
                    add_dependencies(r)

        t_resources = resources[:]
        for res in t_resources:
            if res in valid_resources:
                add_dependencies(res)

    # set the working directory
    device = list(set(resources).intersection(valid_resources['device']))
    if len(device) > 1:
        raise MultipleDeviceResourceException(*device)
    elif not device:
        device = list(set(resources).intersection(valid_resources['cli']))
    device = device[0]

    if not metadata['workdir']:
        metadata['workdir'] = os.path.join(os.getcwd(), 'b2g-workdir', device)
        if os.path.isdir(metadata['workdir']):
            if prompt.prompt(
                    "Resource '%s' already exists in the working directory, do you want to overwrite it?"
                    % device) == "y":
                log.info("removing '%s'" % metadata['workdir'])
                shutil.rmtree(metadata['workdir'])
            else:
                metadata['workdir'] = prompt.prompt(
                    "Enter the full path to a new working directory:", [])

    if not os.path.isdir(metadata['workdir']):
        os.makedirs(metadata['workdir'])

    # build and dispatch the request
    build_request(resources, metadata)
Пример #30
0
#Import modules:
import prompt
import encode
import decode

#Prompt the user to encode or decode:
prompt.prompt()

#Based on previous input, launch encode or decode function:
if prompt.prompt == 'e':
    encode.encode()
elif prompt.prompt == 'd':
    decode.decode()
Пример #31
0
def save_game():
    print("[[[ Saving game... ]]]")
    save_stats()
    save_inventory()
    print("[ Game Saved ]")
    prompt()
### End of functions. Main program flow starts here.

print "Guess-The-Number Game"
print "-----------------------------------"

### Initialize default variables then start the game loop.
low = 1
high = 10
new = True

while new == True:

    ### Custom settings configuration
    print "The current setting is between", low, "and", high
    print "Do you want to change this setting?"
    custom_settings = prompt.prompt("N")
    if custom_settings == True:
        low = int(raw_input('Set the low bound: '))
        high = int(raw_input('Set the high bound: '))

    ### Generate our random number for this game session
    number = random.randint(low,high)
    print "Number is between", low, "and", high
    #print "DEBUG- Number:", number
    new = False
    
    while True:
        ### Sub-loop for a 'game session' (retaining the same number between guesses)
                
        guess = int(raw_input('Guess the number: '))
        #print "DEBUG- Your guess was:",guess
Пример #33
0
def newGame():

    print("""

        THIS IS GOING TO BE A TITLE SCREEN

        """)

    string1 = """
    You find yourself at the entrance of an old home.
    The walls and windows are faded and dilapidated.

    A sign reads:
    """

    string2 = """
    \n
    \t‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡
    \t‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡
    \t‡‡‡‡                 ‡‡‡‡
    \t‡‡‡‡    F**k you.    ‡‡‡‡
    \t‡‡‡‡                 ‡‡‡‡
    \t‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡
    \t‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡
    \t          ‡‡‡‡‡
    \t          ‡‡‡‡‡
    \t          ‡‡‡‡‡
    \t          ‡‡‡‡‡
    \n
    """

    for i in range(0, len(string1)):
        print(string1[i], end='', flush=True)
        #sleep(.01)

    sleep(2)

    for i in range(0, len(string2)):
        print(string2[i], end='', flush=True)
        #sleep(.01)

    string3 = "Do you enter?\n\n"

    for i in range(0, len(string3)):
        print(string3[i], end='', flush=True)
        #sleep(.04)

    while True:
        answer = prompt('feedback')

        yes = [
            'Yeah', 'yeah', 'Yes', 'yes', 'Ye', 'ye', 'Yup', 'yup', 'Ya', 'ya',
            'Y', 'y'
        ]
        no = ['No', 'no', 'Nope', 'nope', 'Nah', 'nah', 'N', 'n']

        if answer in yes:
            six.enter()  #  Room D6
        elif answer in no:
            dead("\nYou run away like a little bitch.")
        else:
            print("\n    What?\n")
Пример #34
0
def grade(criteria, submissions, filename):
    found = []
    num_missing = 0
    total = criteria.total_points

    for f in criteria.files:
        crit_dir, crit_name = os.path.split(f.path)

        for s in submissions:
            sub_dir, sub_name = os.path.split(s)

            if crit_name == sub_name:
                found.append(f)
                break
        else:
            # in the case that the file is missing, we should prompt
            # the grader to pick the incorrect file name or declare
            # the file missing

            sprint(COLOR_YELLOW + "could not find "
                   "file '{}'".format(f.path) + COLOR_RESET)

            if len(submissions) < 1:
                continue

            # find the submission directory (it could be the
            # current working directory, but maybe not)
            submission_dir, _ = os.path.split(submissions[0])

            if not submission_dir:
                submission_dir = os.path.abspath(os.curdir)

            choices = [f for f in os.listdir(submission_dir)
                       if os.path.isfile(os.path.join(submission_dir, f))]
            choices.append("skip grading this submission now")
            choices.append("mark the file as missing")

            sprint("this student may have named the file incorrectly...")

            # we prompt the grader for zero or one choice
            got = prompt(choices, '1')
            got = got[0]

            if got == len(choices) - 1:
                # declare the file missing
                num_missing += 1
                continue

            elif got == len(choices) - 2:
                sprint("skipping this submission; no grade file written")
                sys.exit(EXIT_WITH_DEFER)

            else:
                # get absolute path to the old and new files
                sname = choices[got]

                opath = os.path.join(submission_dir, sname)
                npath = os.path.join(submission_dir, crit_name)

                try:
                    os.rename(opath, npath)
                except:
                    import traceback

                    sprint("error renaming incorrectly named file", error=True)
                    traceback.print_exc()
                    sys.exit(ERR_GRADING_MISC)

                found.append(f)

    out = io.StringIO()

    try:
        for f in criteria.files:
            out.write(heading("{} [{} points]".format(f, f.point_value),
                              level=2))

            if f not in found:
                total -= f.point_value
                out.write("-{}\tnot submitted\n".format(f.point_value))
                continue

            sprint("running tests for " + str(f))

            points_taken = 0
            points_taken += _write_results(out, f.run_tests())

            file_stat = os.stat(f.path)
            mtime = datetime.datetime.fromtimestamp(file_stat.st_mtime)

            if mtime > criteria.due:
                if mtime > criteria.due + datetime.timedelta(hours=24):
                    sprint(COLOR_YELLOW + "taking all points for >24-hour "
                           "late-submitted {}".format(f) + COLOR_RESET)

                    late_penalty = f.point_value
                    out.write("-{}\tsubmitted >24 hours "
                              "late\n".format(late_penalty))

                else:
                    sprint(COLOR_YELLOW + "taking 10% penalty for "
                           "late-submitted {}".format(f) + COLOR_RESET)

                    late_penalty = f.point_value * 0.10
                    out.write("-{}\tsubmitted late\n".format(late_penalty))

                points_taken += late_penalty

            total -= min(f.point_value, points_taken)

            out.write("\n")

        out.write("\nTotal: {}\n".format(total))

    except KeyboardInterrupt:
        sprint("\nstopping (received interrupt)")

        out.close()
        sys.exit(ERR_INTERRUPTED)

    except:
        import traceback

        err = sys.exc_info()
        sprint("encountered an error while "
               "grading: {}".format(err[0].__name__), error=True)
        traceback.print_exc()
        sprint("you might have to grade the old-fashioned "
               "way (sorry)")

        out.close()
        sys.exit(ERR_GRADING_MISC)


    with open(filename, 'w') as f:
        out.seek(0)
        f.write(out.read())

    sprint("grading completed")
    return num_missing