def in_game_menu(): saved = 0 while True: os.system('clear') print('''{} 1. \033[38;2;255;255;100mC\033[38;2;255;255;255montinue 2. \033[38;2;255;255;100mS\033[38;2;255;255;255mave Game 3. \033[38;2;255;255;100mE\033[38;2;255;255;255mxit to Main Menu '''.format(color.white)) key = keyboard.getch() if key in ["c", "1"]: break elif key in ["s", "2"]: os.system('clear') save_game_menu() saved = 1 elif key in ["e", "3"]: if saved == 1: print("Ending game") else: print("\nDo you want save before quitting? [Y/N]") while True: key = keyboard.getch() if key == "n": globalLogic.stopGame(3) break elif key == "y": save_game_menu() globalLogic.stopGame(3) break print("Ending game") globalLogic.stopGame(3) break os.system('clear')
def input_name(self, screen, maxlen=10): """ Prompts the user to type in the name for entry in the high scores screen: the screen to show stuff on maxlen: the maximum number of characters allowed in the name (default 10) return: a string of the name as typed in by the user """ def update_display(): """ An inner helper function to refresh the screen display as the name is typed """ x = screen.width/2 - 7 screen.fill(' ') screen.write_text(x, 1, "New High Score!") x = screen.width/2 - (maxlen + 12)/2 screen.write_text(x,3, "Enter Name: " + name) screen.show() name = "" # start with a blank name ch = None # the character entered from the keyboard update_display() # show the display to begin while True: # go until Enter is pressed ch = keyboard.getch(10000) # get the next key board press if ch == '\n': break # we are done when Enter = \n is pressed if ch == keyboard.KEY_ESCAPE: return None # The user can skip annoying name entry by hitting Esc elif ch == keyboard.KEY_BACKSPACE: name = name[0:len(name)-1] # if we hit bakspace use all but the latest character elif ch not in [',', ' ', None] and len(ch) == 1 and len(name) < maxlen: name += ch # add the newest character unless it is whitespace, unprintable, or we go over our character limit update_display() # keep updating the display return name
def handle_new_score(self, score, screen): """ Takes in a new score and chacks if it ranks, and if so get the user's name and show the new list including the new user's name score: a number representing the score the user achieved screen: the screen to show stuff on """ if self.highscoresDB.ranking(score) < self.highscoresDB.N: # determine the ranking and if it should be entered name = self.input_name(screen) # get the name from the user if name != None: # Sometimes None is returned if the user presses Esc to skip adding their name self.highscoresDB.insert(name, score) # subit the name in the database... It bumps off the old bottom ranker self.highscoresDB.save() # re-save the scores in the database file self.scroll_on(screen, scroll_off = False) # scroll away the name input screen to show the scores screen.show() keyboard.getch(0) # clear key presses to abort scroll keyboard.getch(4) # wait for a key hit for 4 seconds
def motor_time(): global motor_step_n global user_input pyb.delay(100) angle = 90 speed = 5 default_user_input = ["0", "0", "0", "0"] default_value = "" for numb in default_user_input: default_value += numb last_pressed = "" angle_text = "A:" + str(angle) + " | S:" + str(speed) lcd_write(0, angle_text) lcd_write(1, "* exits") # functionality starts while True: angle_text = "A:" + str(angle) + " | S:" + str(speed) lcd_write(0, angle_text) lcd_write(1, "* exits") ch = keyboard.getch(i2c_lcd) if ch != "": # if '* pressed exit mode if ch == "*": break # set angle elif ch == "1": lcd_write(0, "Set angle") lcd_write(1, default_value) user_input = default_user_input while True: pyb.delay(100) key_input = read_keypad(last_pressed) last_pressed = key_input[0] mes = key_input[1] if mes != "": angle = int(mes) user_input = ["0","0","0","0"] break # set turning speed elif ch == "2": lcd_write(0, "set speed") lcd_write(1, default_value) user_input = default_user_input while True: pyb.delay(100) key_input = read_keypad(last_pressed, user_input) user_input = key_input[1] last_pressed = key_input[0] mes = key_input[2] if mes != "": speed = int(mes) user_input = ["0","0","0","0"] break # start rotation elif ch == "3": motor_step_n = motor.rotate_motor(angle, motor_step_n, speed) last_pressed = ch else: last_pressed = ""
def read_keypad(last): global user_input last = last # Keypad loop lcd_message = "" ch = keyboard.getch(i2c_lcd) log_message = "" # When key has been pressed if ch != "": # If Pressed key is * if ch == '*': # Reset array and screen user_input = ["0", "0", "0", "0"] log_message = "" lcd_message = "" lcd_write(1, "Waiting for key!") # If pressed key is # elif ch == '#': log_message = "" lcd_message = "" # If user_input has space if "" in user_input: # Write error message to user mes = "Invalid code:" for s in user_input: if s != "": mes += "" + s lcd_write(1, mes) else: for h in user_input: log_message += str(h) user_input = ["0", "0", "0", "0"] lcd_write(1, "Waiting for key!") # If pressed key is not same as last key pressed, * or # elif last != ch: # if user_input has space if "" in user_input: # Set pressed key to first empty space in user_input for i in range(0, 4): if user_input[i] == "": user_input[i] = ch break # If user_input has no space else: # Move all values one space down and add just pressed key to last space user_input[0] = user_input[1] user_input[1] = user_input[2] user_input[2] = user_input[3] user_input[3] = ch # After adjustment is done print info to user for i in range(0, 4): lcd_message += user_input[i] lcd_write(1, lcd_message) last = ch # When key is not pressed else: # Reset last key pressed last = "" return (last, log_message)
def scroll_on(self, screen, scroll_off = True): """ Scrolls the rankings on to the screen to reveal the top scores one at a time It scrolls until the last ranking appears at the bottom of the screen. If specified it will also. If it is interrupted with a keypress the slow scrolling high scores screen showing is aborted wait for 2 seconds and scroll back off the sreen revealing whatever was on the previous screen before showing the high scores screen scroll_off: boolean if true the high scores screen will wait 2 seconds and scroll back off (unless interrupted by a key hit) """ keyboard.getch(0) # clear all keys plate = character_map.CharacterMap( screen.width, max(screen.height, self.highscoresDB.N+2) ) prev = screen.clone() # store the previous screen to restore it when we are done text = "" # put the high score names and scores into text maxlen = 0 i = 0 for name, score in self.highscoresDB.data: # put each line in text i += 1 line = "%2d: %s ...... %d\n"%(i, name, score) text += line maxlen = max(maxlen, len(line)) x = plate.width / 2 - 9 plate.write_text(x, 0, "*** High Scores ***") # write the text into a high scores screen x = plate.width / 2 - maxlen / 2 plate.write_text(x, 2, text) for i in xrange(0, plate.height): # scroll the plate on one name at a time from the top screen.scroll_down() screen.draw(0, i-plate.height+1, plate) # draw the names plate in the gap you just scrolled off screen.show() if keyboard.getch(.07) != None: # tick at 1/.07 = 14.286 fps screen.draw(0, 0, plate) # show it quickly if you abort drawing return if not scroll_off: return if keyboard.getch(2) != None: return # wait 2 seconds for i in xrange(0, screen.height): screen.scroll_down() screen.draw(0, i-screen.height+1, prev) screen.show() if keyboard.getch(.07) != None: return
def run_until_key(self, stop_key, block): """ Execute `block` until `stop_key` is pressed """ from keyboard import getch info("Press %s to exit\n" % stop_key) while True: key = getch() if key == stop_key: self.close() return block(key)
def save_game_menu(): filename = input("Insert save game name (without extention): ") if os.path.isfile(sys.path[0] + SAVE_GAME_PATH + filename + ".sav"): print(filename + ".sav already exists. Do you wish to overwrite it? [Y/N]") while True: key = keyboard.getch() if key == "y": level.save_game(filename) break elif key == "n": print("Do you want to save it by another name? [Y/N]") while True: key = keyboard.getch() if key == "y": save_game_menu() break elif key == "n": break break else: level.save_game(filename)
def motor_flash(): global motor_step_n global user_input pyb.delay(100) default_user_input = ["0", "0", "0", "0"] user_input = default_user_input default_value = "" for numb in default_user_input: default_value += numb last_pressed = "" angle = 90 angle_text = "Angle:" + str(angle) lcd_write(0, angle_text) lcd_write(1, "* to exit") # start functionality loop while True: angle_text = "Angle:" + str(angle) lcd_write(0, angle_text) lcd_write(1, "* exits") ch = keyboard.getch(i2c_lcd) if ch != "": # Exit mode if ch == "*": break # Set turning angle elif ch == "1": user_input = default_user_input print (user_input) lcd_write(1, default_value) while True: pyb.delay(100) lcd_write(0, "Set angle") last_pressed = "" key_input = read_keypad(last_pressed) last_pressed = key_input[0] mes = key_input[1] if mes != "": angle = int(mes) user_input = default_user_input break # Start flash detection elif ch == "3": lcd_write(1, "Hold 0 to stop") lcd_write(0, "waiting flash") flash.flash_detection(i2c_lcd, motor_step_n, angle) else: last_pressed = ""
def main_menu(): while True: os.system('clear') common.printMainMenu() key = keyboard.getch() if key in ["n", "1"]: new_game_menu() break elif key in ["l", "2"]: load_game_menu() break elif key in ["e", "3"]: os.system('clear') common.printQuit() return 1 return 0
def main(): global stop, dev, keys, activeActor init() activeVar = None actionVar = None keysP1 = ('w', 's', 'a', 'd', 'f', 'e', '0', '\r') keysP2 = ('A', 'B', 'C', 'D', '-', 'e', '0', '\r') display(activeActor) while (1): # game logic turnVar = 0 while (turnVar < len(player.players)): # one round key = keyboard.getch() os.system('clear') if (activeActor == 0 or len(player.players) == 1) and key in keysP1: # player 1 turn actionVar = keys[key][0](*keys[key][1:]) if actionVar is not None or key == '\r': activeActor = 1 turnVar += 1 elif (activeActor == 1 or len(player.players) == 1) and key in keysP2: # Player 2 turn actionVar = keys[key][0](*keys[key][1:]) if actionVar is not None or key == '\r': activeActor = 0 turnVar += 1 display(activeActor, actionVar) if stop > 0: break if activeActor > len(player.players): break if actionVar is not None: enemy.enemyAction() if stop > 0: break os.system('clear') if stop == 1: common.printGameOver() print("\nPress enter to continue!") wait_for_enter() elif stop == 2: common.printGameWon() print("\nPress enter to continue!") wait_for_enter() level.level_clean_up() return 1
def load_game_menu(): os.system('clear') in_load_menu = True saves = sorted(level.get_save_files()) list_stage = 0 print_load_menu(saves, list_stage) while in_load_menu: key = keyboard.getch() if key == "A": if list_stage > 0: list_stage -= 1 os.system('clear') print_load_menu(saves, list_stage) elif key == "B": if list_stage < int((len(saves) - 1) / 9): list_stage += 1 os.system('clear') print_load_menu(saves, list_stage) elif key == "l": try: level_to_load = input("Insert filename without extension: ") level.load_level(sys.path[0] + SAVE_GAME_PATH + level_to_load + ".sav") error = globalLogic.main() except FileNotFoundError: print_load_menu(saves, list_stage) print("{}.sav does not exist".format(sys.path[0] + SAVE_GAME_PATH + level_to_load)) elif key in [str(i) for i in range(10)]: if int(key) == 0: in_load_menu = False if int(key) > 0: if int(key) <= len(saves) - list_stage * 9: os.system('clear') level.load_level(sys.path[0] + SAVE_GAME_PATH + saves[int(key) - 1 + 9 * list_stage]) error = globalLogic.main() in_load_menu = False
def new_game_menu(): os.system('clear') in_new_game_menu = True levels = sorted(level.get_level_files()) list_stage = 0 print_new_game_menu(levels, list_stage) while in_new_game_menu: key = keyboard.getch() if key == "A": if list_stage > 0: list_stage -= 1 os.system('clear') print_new_game_menu(levels, list_stage) elif key == "B": if list_stage < int((len(levels) - 1) / 9): list_stage += 1 os.system('clear') print_new_game_menu(levels, list_stage) elif key == "l": try: level_to_load = input("Insert filename without extension: ") start_new_game(level_to_load) except FileNotFoundError: print_new_game_menu(levels, list_stage) print("{}.inf does not exist".format(sys.path[0] + NEW_GAME_PATH + level_to_load)) elif key in [str(i) for i in range(10)]: if int(key) == 0: in_new_game_menu = False if int(key) > 0: if int(key) <= len(levels) - list_stage * 9: os.system('clear') start_new_game(sys.path[0] + SAVE_GAME_PATH + levels[int(key) - 1 + 9 * list_stage]) in_new_game_menu = False
menu = ["rotate/manual", "rotate/flash"] # main menu info menu2 = ["<=1 #select 3=>"] # initial menu position menu_item = 0 # Initial rotation motor.rotate_motor(9, motor_step_n, 10) # Main loop # 1 goes left, 3 goes right, # is select # rotates cycle if too far either direction while True: lcd_write(0, menu2[0]) lcd_write(1, menu[menu_item]) ch = keyboard.getch(i2c_lcd) if ch != "": if ch == "1": menu_item -= 1 elif ch == "3": menu_item += 1 if ch == '#': menu_do[menu_item]() if menu_item >= len(menu): menu_item = 0 if menu_item < 0: menu_item = len(menu) - 1 last = ch else: last = ""
def flash_detection(i2cLCD, motor_step_n, angle=90): global averages global av global middle_led global over_led global under_led global lights ave = 0 # If detected light is over average and average is not 0 startTime = time.time() while True: # if '*' pressed exit flash detection if time.time() - startTime >= 0.2: ch = keyboard.getch(i2cLCD) if ch == "0": break else: startTime = time.time() x1u = adc.read() if av != 0 and x1u > av + 50: motor_step_n = motor.rotate_motor(angle, motor_step_n) middle_led.on() over_led.on() under_led.on() pyb.delay(200) middle_led.off() over_led.off() under_led.off() av = 0 averages = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] continue # Adding light data to list if 0 in averages: if 0 in lights: for i in range(0, 50): if lights[i] == 0: lights[i] = x1u break else: sum = 0 for x in range(0, 50): sum += lights[x] a = sum/50 for x in range(0, 10): if averages[x] == 0: averages[x] = a lights= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] else: sum = 0 for x in range(0, 10): sum += averages[x] av = sum/10 for x in range(0, 9): averages[x] = averages[x+1] averages[9] = 0 print("av:" , av , " averages: " , averages)
def waitKey(): """ Blocking function to wait for Enter key (or Escape key) to be pressed """ kb.getch() print("CONTINUE KEY ACCEPTED")
if __name__ == "__main__": # start library thread # lib_output holds the retval from calls to 'library_thread.thread_call' # each call will always add 1 item to the queue # the output queue will get a "ready" on it when initilization is done lib_output = Queue.Queue() library_thread = librarythread.LibraryThread(Queue.Queue(), lib_output, Queue.Queue(), "config.xml") library_thread.start() # wait for librarythread to initialize try: print lib_output.get(timeout=1) print "" except Queue.Empty: print "failed to initialize in a timely fashion" library_thread.thread_call(library_thread.die) # try to connect quadruped actions.act_on_key('c', library_thread) # listen to keyboard while True: c = keyboard.getch() actions.act_on_key(c, library_thread) if c == 'q': break # at the end, kill the library thread library_thread.thread_call(library_thread.die)
def main(): global rows global columns global score global next_level game_player = gamePlayer('P', score, 7, rows-2) game_wall = gameWall('X', rows, columns) game_floor = gameFloor('X', rows, columns) game_ladder = gameLadder('H', game_floor.coordinates) game_coin = gameCoin('c', game_floor.coordinates, columns) game_donkey = gameBadGuy('D', game_floor.coordinates) game_fireball_list = [] game_princess = gameQueen('Q', game_floor.coordinates) game_matrix.update_walls_in_matrix(game_wall.coordinates, game_wall.symbol) game_matrix.update_floors_in_matrix(game_floor.coordinates, game_wall.symbol, columns) game_matrix.update_ladders_in_matrix(game_floor.coordinates, game_ladder.coordinates, game_ladder.symbol, game_floor.gap) game_matrix.update_coins_in_matrix(game_coin.coordinates, game_coin.symbol) game_matrix.update_character_in_matrix(game_player.y, game_player.x, game_player.symbol) game_matrix.update_character_in_matrix(game_donkey.y, game_donkey.x, game_donkey.symbol) game_matrix.update_character_in_matrix(game_princess.y, game_princess.x, game_princess.symbol) while True: termios.tcflush(sys.stdin, termios.TCIOFLUSH) game_matrix.update_character_in_matrix(game_donkey.y, game_donkey.x, game_donkey.trace) game_fireball_list = game_donkey.manageFireball(rows, columns, game_matrix, game_floor.coordinates, game_fireball_list) for fireball in game_fireball_list: game_matrix.update_character_in_matrix(fireball.y, fireball.x, fireball.trace) fireball.move(columns, game_matrix, game_player, game_ladder, game_wall.symbol, game_floor) game_matrix.update_character_in_matrix(fireball.y, fireball.x, fireball.symbol) game_donkey.move(game_matrix.grid, game_player) game_matrix.update_ladders_in_matrix(game_floor.coordinates, game_ladder.coordinates, game_ladder.symbol, game_floor.gap) game_matrix.update_coins_in_matrix(game_coin.coordinates, game_coin.symbol) game_matrix.update_character_in_matrix(game_donkey.y, game_donkey.x, game_donkey.symbol) game_matrix.update_character_in_matrix(game_player.y, game_player.x, game_player.symbol) game_matrix.print_matrix(game_player.score, game_player.lives) direction = None start = time.time() if keyboard.kbhit(): direction = keyboard.getch() termios.tcflush(sys.stdin, termios.TCIOFLUSH) time.sleep(0.01) end = time.time() if(end - start > 0.3): game_player.motion = Motion.REST if direction == 'q' or game_player.lives == 0: next_level = False return elif game_player.winGame(game_princess, game_matrix) == 1: score = game_player.score game_matrix.print_matrix(game_player.score, game_player.lives) game_matrix.reset(columns, rows) game_matrix.level += 1 time.sleep(3) del game_player del game_wall del game_floor del game_ladder del game_coin del game_donkey game_fireball_list = [] del game_princess return elif direction not in (Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST, Direction.JUMP): continue else: game_matrix.update_character_in_matrix(game_player.y, game_player.x, game_player.trace) game_player.climb(direction, game_matrix, game_ladder, game_floor, game_coin) game_player.jump(direction, columns, rows, game_matrix, game_ladder, game_floor, game_wall.symbol, game_coin, game_donkey, game_fireball_list) game_player.fall(columns, direction, game_matrix, game_ladder, game_floor, game_wall.symbol, game_coin, game_donkey, game_fireball_list) game_matrix.update_character_in_matrix(game_player.y, game_player.x, game_player.trace) game_player.move(direction, columns, rows, game_matrix, game_wall.symbol, game_floor.symbol, game_ladder.symbol, game_coin) game_matrix.update_ladders_in_matrix(game_floor.coordinates, game_ladder.coordinates, game_ladder.symbol, game_floor.gap) game_matrix.update_coins_in_matrix(game_coin.coordinates, game_coin.symbol) game_matrix.update_character_in_matrix(game_player.y, game_player.x, game_player.symbol)
def wait_for_enter(): while True: if keyboard.getch() == '\r': break