Example #1
0
def main():
	
	pygame.init()

	size = width, height = [640,480+16]
	renderer.init(size)
	pygame.display.set_caption("snake")
	menu.init()
	
	
	# number of player, game type, lives, mapname
	while 1:	
		gametype = menu.choose ("",																			\
		[{ "label" : "Single Player", "value": "1p"}, 									\
		 { "label" : "Multi Players Game", "value": "multi"},						\
		 { "label" : "Join a Network Game", "value" : "join"},					\
		 { "label" : "QUIT", "value": None}])	

		if gametype == None : 
			break
		
		if game.init (gametype):
			game.mainloop ()

	pygame.display.quit()
Example #2
0
class TestMenu(unittest.TestCase):
    def test_choose(self):
        def test_func():
            pass

    menu = Menu([
        MenuItem(1, 'Test', test_func)
    ])
    output = menu.choose(1)
    self.assertEqual(output, 'kacsa')
Example #3
0
def _switch_voc(tstate: TraineeState) -> str:
    '''Let user choose from all found .voc files

    tstate    - trainer state object

    When a valid file name has been chosen the tstate is updated
    with that info.

    Return true if the vocabulary changed.
    '''

    old_voc_file = tstate.voc_file

    i = 1
    menuopts = []
    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    for f in files:
        if f.endswith('_voc.txt'):
            menuopts.append((str(i), f, f'The vocfile {f}'))
            i += 1

    # If no _voc.txt file was found
    if not menuopts:
        print("\033[93mWARNING:"
              " No _voc.txt file was found. Exit program and "
              "change file name to end with '_voc.txt'.\033[0m")

    # Add the option to not choose file
    menuopts.append(('q', 'go back without choosing file'))

    choice, vocfile = menu.choose(
        '[Select Vocabulary Menu]'
        ' Please choose a vocabulary to train.', menuopts)

    if choice != 'q':
        tstate.voc_file = vocfile

    return tstate.voc_file != old_voc_file
Example #4
0
def _modify_translation(engword: str, answer: str, translations: set,
                        vstate: VocState):
    '''Let user choose how a rejected translation should be handled.

    engword      - The english word to potentially modify translation for
    answer       - The user's translation that might actually be correct
    translations - The current set of valid translations
    vstate       - The VocState object containing any modifications to
                   the default translation of the engword

    '''

    # Menu options always available
    menuopts = [('0', '[Default] Do nothing. My translation was wrong.'),
                ('a', f"Add '{answer}' to translations"),
                ('r', f"Reset to original translation of '{engword}'")]

    # Add menu options for replacing a word. We associate the replacement
    # word with the option as the 2nd arg in the option tuple. See menu.choose.
    for n, word in enumerate(translations, start=1):
        menuopts.append((str(n), word, f"Replace '{word}' with '{answer}'"))

    opt, replaceword = menu.choose(
        '[Add/Modify Translation] What would you like to do?', menuopts, '0')

    if opt == '0':
        print('Ok. Continuing.\n')
    elif opt == 'a':
        print(f"Ok. Adding '{answer}' as a valid translation\n")
        vstate.change_translation(engword, add={answer})
    elif opt == 'r':
        print(f"Ok. Clearing all changes to translations of '{engword}'\n")
        vstate.reset_modifications(engword)
    else:  # Request replacing a word ( = value part of menu option)
        print(f"Ok. Replacing '{replaceword}' with '{answer}'\n")
        vstate.change_translation(engword, add={answer}, remove={replaceword})
Example #5
0
def init(gametype):
	global players, items, remplayers
	global ucolors, udevs, devs, colors
	global numbersend, lives, netgame
	global blue, pink, green, red, orange,cyan
	global nlpr, cont

	blue = (0,0,255)
	pink = (255,20,147)
	green =(0,128,0)
	red = (255,0,0)
	orange = (255,165,0)
	cyan= (0,255,255)
	

	if gametype != "join" :
		list = os.listdir("maps")
		list.sort()
		mapname = menu.choose ("Select the map:",\
					[{ "label" : file, "value" : file} for file in list])
		if mapname == None :
			return False

		board.init ("maps/"+ mapname)
		items = {}
	
	# Get Game options
	boolean = [ { "label" : "On", "value": True }, 
							{ "label" : "Off", "value": False } 
						]
	multioptions = [																								\
			{ "description" : "NLPR: ", 																\
				"name" : "nlpr", 																					\
				"options" : boolean,																			\
				"default" : False,																				\
			}, 																													\
			{	"description" : "Continue: ",															\
				"name" : "cont", 																					\
				"options" : boolean,																			\
				"default" : False,																				\
			},																													\
			{ "description" : "End with numbers: ",											\
				"name" : "numbersend",																		\
				"options" : boolean,																			\
				"default" : True,																					\
			},																													\
			{	"description" : "Players: ",															\
				"name" : "nplayers",																			\
				"default" : 2,																						\
				"options" : [ { "label" : str(x), "value" : x} 						\
												for x in range(1,5)												\
										]																							\
			}]

	if gametype == "1p":
		multioptions = []

	options = menu.select ("Select Game Options",										\
			multioptions + 																							\
			[{	"description" : "Lives: ", 															\
					"name" : "lives", 																			\
					"default" : 5,																					\
					"options" : [ { "label" : str(x), "value" : x }					\
						for x in [1, 2, 3, 4, 5, 10, 20, 50, 64, 100, 256]]} 	\
			])
	if options == None:
		return False
	if gametype == "1p":
		nlpr = False
		cont = False
		nplayers = 1
		numbersend = True
	else:
		nlpr = options["nlpr"]["value"]
		cont = options["cont"]["value"]
		nplayers = options["nplayers"]["value"]
		numbersend = options["numbersend"]["value"]
	lives = options["lives"]["value"]

	# Get Players
	ucolors = set()
	udevs = set()
	colors = [blue, pink, green, red, orange, cyan]
	devs = [("Keypad", "keypad"),												\
					("Computer", "ai"), 												\
					("Keyboard (wasd)", "keyboard"),						\
					("Vim Keys (hjkl)", "vim"), 								\
					("Netwrok", "net")													\
					]

	players = []
	netgame = False
	for i in range(nplayers):
		player = getplayer(str(i+1))
		if player == None:
			return None
		players.append(player)

	if netgame:
#		network.startserver()
		for player in players:
			if player.dev == "net":
				if network.waitfor(player) == None:
					network.sendinfo (player, board.dim, board.obstacles)
					return None
			
	renderer.updateboard()
	remplayers = nplayers
	return True
Example #6
0
def run_session(tstate: TraineeState):
    '''Main menu logic.

    tstate - The state that got read from file

    This functions run until the user selects the 'q' option (quit).
    From here one can select different vocabularies, train and do an
    exam when one has qualified.
    '''

    # If vocabulary configured in the state we load it.
    if tstate.voc_file:
        voctable = _read_voc(tstate)
    else:
        voctable = None

    remain_running = True

    while remain_running:

        print('-' * 60)

        # These menu options are always there
        menuopts = [('c', 'Change or set vocabulary file'),
                    ('l', 'Show levels for vocabularies')]

        # Some menu options are added conditionally below

        if not voctable:
            print("\033[93mNo vocabulary file selected. "
                  "Please select! (option 'c')\033[0m")
        else:
            print(f'  Current vocabulary: {tstate.voc_file}')
            level = tstate.current_voc_state.level
            print(f'  Level: {level}')

            if level == _MAXLEVEL:
                qualstr = '(you are max level - no more exams to do)'
            else:
                menuopts.append(('t', 'Start training sub session'))
                if tstate.current_voc_state.qualified:
                    qualstr = 'Yes!'
                    menuopts.append(('e', 'Take exam'))
                else:
                    qualstr = 'No'
            print(f'  Qualified for exam: {qualstr}')

        # Nice to have the quit option furthest down
        menuopts.append(('q', 'Quit and save'))

        choice, _ = menu.choose('\n[Main Menu]: Pick an operation!', menuopts)
        print()

        if choice == 'c':
            if (_switch_voc(tstate)):
                voctable = _read_voc(tstate)
        elif choice == 'q':
            print('Ok. See you soon!')
            remain_running = False
        elif choice == 't':
            _train(tstate.current_voc_state, voctable)
        elif choice == 'e':
            _take_exam(tstate.current_voc_state, voctable)
        elif choice == 'l':
            tstate.print_all_stats(_MAXLEVEL)
            print()
Example #7
0
def _train(vstate: VocState, voctable: VocTable):
    '''Run a training session

    vstate      - trainee state for given (=current) vocabulary
    voctable    - full table (= all levels) of vocabulary
    '''

    vocdict = _setup_test(vstate, voctable)

    _print_banner(f'Level {vstate.level} training session', 40)

    def get_translations(engword):
        return vstate.get_modified_translations(engword, vocdict[engword])

    keepon = True

    while keepon:
        # Randomize the order of remaining words
        testwords = list(vocdict.keys())
        numwords = len(testwords)
        random.shuffle(testwords)

        print(f'Starting test round of {len(testwords)} words.\n')

        for num, engword in enumerate(testwords):
            translations = get_translations(engword)
            print(f'{num + 1}: How do you say \'{engword}\'? ', end='')
            answer = input().lower()
            if answer not in translations:
                # Ok - wrong answer. Give the user a chance to add the
                # word to the vocabulary
                correct = " or ".join(f"'{w}'" for w in translations)
                print(f'Not correct. It should be {correct}.')
                _modify_translation(engword, answer, translations, vstate)
            else:
                print('  Correct!')
                del vocdict[engword]  # Remove it from the rest of the session.

        if not vocdict:  # If all words been translated correctly at least once
            print('\nYou seem to know all the words!')
            if not vstate.qualified:
                if vstate.level < _MAXLEVEL:
                    print('You are now qualfied to take the exam!')
                vstate.qualified = True
            keepon = False

        else:  # There are still words we've not translated correctly
            print('\nDone. You got '
                  f'{numwords - len(vocdict)}/{numwords} correct!\n')
            print('Difficult words:')
            print('----------------')
            for engword in vocdict.keys():
                translations = get_translations(engword)
                print(f'  {engword} -> {", ".join(translations)}')

            # At this point the user can exit the training if they like

            menutext = "[Training Menu] Would you like to continue training?"
            menuopts = [('c', 'Continue with difficult words?'),
                        ('x', 'Exit to main menu')]
            if menu.choose(menutext, menuopts)[0] == 'x':
                keepon = False
            else:
                _clear_screen()