def playGame(): quit = False while not quit: display.clear() result = display.playScreen() quit = True if result == EXIT else display.endScreen(result) display.closeScreen()
def blink_events(): for event in g_calendar.events: blink_color = g_calendar.color_ids[ event["colorId"]] if "colorId" in event else 0xffffff event_date = dateutil.parser.parse( event['start']['dateTime'] if 'dateTime' in event['start'] else event['start']['date']) event_date = event_date.replace(tzinfo=None) delta = event_date - datetime.datetime.now() if delta < datetime.timedelta(hours=10): display.clear() time.sleep(0.5) display.set_display(int(delta.seconds / 3600), True, blink_color) time.sleep(0.5) display.set_display(16, False, blink_color) time.sleep(0.5) display.clear() else: display.set_display_manual({0: blink_color}) time.sleep(0.5) display.set_display_manual({0: 0}) time.sleep(0.5)
def play(): g = game.Game() while (g.isNotOver()): display.clear() display.board(g) g.takeTurn() input("Press enter to continue...")
def drawPage(header, entries, duration): now = datetime.now() display.clear() y = display.drawHeader(20, header) display.drawEntries(entries, y, 15, 1) display.show() time.sleep(duration - (datetime.now() - now).seconds) return
def main(): # importuje plik i zapisuje w lokalnej dla tego modułu liście albums_data = file_handling.import_data("albums_data.txt") working = True check = True text = "" # loopa zeby menu było wyświetlane non stop, nawet jesli ValueError to znaczy jesli input # nie bedzie int. text jest po to zeby wyswietlac okreslony komunikat w dowolnie wybranym miejscu # w przypadku dobrze wybranej opcji zamieniam text na pusty string zeby komunika nie byl wysiwetlany while working and check: try: display.print_program_menu([ "Show table", "Delete album", "Display oldest album", "Get albums by genre", "What is the oldest album by genre", "For arrow keys navigation" ], text) choice = int(input("What is your choice?:")) if choice == 1: display.print_albums_list(albums_data) display.pause() text = "" elif choice == 2: display.print_albums_list(albums_data) artist = input("What is name of artist you want to delete: ") album_name = input( "What is name of album you want to delete: ") delete_album_by_artist_and_album_name(albums_data, artist, album_name) text = "" elif choice == 3: display.print_command_result( music_reports.get_last_oldest(albums_data)) text = "" elif choice == 4: try: genre = input("What is the genre?: ") display.print_albums_list( music_reports.get_albums_by_genre(albums_data, genre)) display.pause() text = "" except (ValueError, IndexError, TypeError): text = "\033[41;33mNo such genre\33[m" elif choice == 5: try: genre = input("What is the genre?: ") display.print_command_result( music_reports.get_last_oldest_of_genre( albums_data, genre)) text = "" except (ValueError, IndexError, TypeError): text = "\033[41;33mNo such genre\33[m" elif choice == 6: arow_nawigation_menu() elif choice == 0: display.clear() working = False except ValueError: text = "\033[41;33mGive proper number\33[m"
def placeABet(score): bet = '' while True: display.clear() bet = display.makeBetScreen(score) if (re.search("^[0-9]*$", bet) and bet != ''): bet = int(bet) if (bet > 0 and bet <= score): return bet
def drawPage(duration): now = datetime.now() duration = timedelta(seconds=duration) while (datetime.now() - now).seconds < duration.seconds: display.clear() y = display.drawHeader(15, "CCU") drawEntries(y) display.show() return
def infinity(): sequence = [1, 2, 6, 5, 4, 3, 6, 7] current_color = 0 for loops in range(8): for i in sequence: display.clear() display.set_display_manual({i: colors[current_color % 7]}) current_color += 1 time.sleep(0.08)
def newUser(): display.clear() print("Create a new User:"******"Name: ") while db.checkUsernameExists(username): username = input("Username: "******"Keyword: ") input("New user created! Press enter to continue...")
def purge(self): display.font_wid.evade=[] for o in self.option: o.object.remove() for o in self.img: o.remove for f in self.text: f.object.remove() self.option=[];self.text=[];self.img=[];self.sel=0 display.clear()
def drawMenu(self): display.clear() self.currentMenu.draw() #display.applycam() #terrain.draw(display.camx,display.camy) #for b in self.walkers: # b.draw() #if not simplenet.isServer: # particles.draw() pygame.display.flip()
def clear_or_return(codes): #OPCODE '0' if (codes.kk == 0xE0): display.clear() cpu_reg.PC += 2 elif (codes.kk == 0xEE): cpu_reg.SP -= 1 cpu_reg.PC = cpu_reg.STACK[cpu_reg.SP] + 2 else: cpu_reg.PC += 2
def drawPage(duration): now = datetime.now() duration = timedelta(seconds=duration) while (datetime.now() - now).seconds < duration.seconds: display.clear() y = display.drawHeader(15, getIP()) display.drawEntries((getCpuLoad(), getMemUsage(), getDiskUsage(), getCpuTemp()), y, 12, 2) display.show() time.sleep(0.250) return
def stroop_task(instruction, label, duration): """Function for displaying Stroop Task. Args: instruction (str): instruction displayed on the screen; label (int): label of stroop_task; duration (float): set the duration of stroop task (each trial is pre-set to 4 seconds) """ session_start = session_starter(instruction, label) trial_count = 1 while time.time() < session_start + duration: trial_start = time.time() # the starting time of the trial logs.trial_log(trial_start, label, trial_count, "starts") # todo fixture time position # display fixture for 0.5 second display.play_alarm() display.fixture() # todo wait for a variable duration variable_duration_list = [0.3, 0.6, 0.9, 1.2] core.wait(random.choice(variable_duration_list)) fixture_time = time.time() # the time when the fixture is displayed logs.trial_log(fixture_time, label, trial_count, "fixture_displayed") # display options color_list = ['Red', 'Yellow', 'Blue', 'Green'] text, color, left, right, stimulus_time = display.stroop_task( color_list) logs.trial_log( stimulus_time, label, trial_count, 'stimulus_displayed_' + text + "_text " + color + "_color") # fixed time out keyboard = event.waitKeys(maxWait=2) press_time = time.time() # the time when user press the keyboard display.clear() answer = "wrong" try: user_response = keyboard[0] if user_response == 'left' and left == color: answer = "correct" elif user_response == 'right' and right == color: answer = "correct" logs.trial_log(press_time, label, trial_count, answer) except: answer = "np_press" event.clearEvents() reaction_time = press_time - stimulus_time logs.user_reaction_log(label, trial_count, reaction_time, answer) logs.trial_log(trial_start, label, trial_count, "ends") trial_count += 1 core.wait(1) # 4 seconds each trial session_end = time.time() logs.session_log(session_end, label, "ends")
def introduce(): intro = msg(y/2,x/2,0.5,"BLIND",'center') intro.tw(False) intro = msg(y/2+2,x/2,0.1,"A text-based sandbox game",'center') intro.tw(False) intro = msg(y/2+3,x/2,0.1,"By Daniel Maxson",'center') intro.tw(True) display.clear() itxt = "It is pitch black. You are likely to be blind." intro = msg(y/2,x/2,0.1,itxt,'center') intro.tw(True)
def drawPage(duration): now = datetime.now() duration = timedelta(seconds=duration) while (datetime.now() - now).seconds < duration.seconds: display.clear() y = display.drawHeader(15, "USV") display.drawEntries((getAkku(), getRuntime(), getVoltage(), getLoad()), y, 12, 2) # display.DRAW.bitmap((0,0), Image.open('ac.png').convert("RGBA")) display.show() return
def isNotOver(self): if self.__checkForWinner(): display.clear() display.board(self) print("Player " + self.__winner + " has won!") return False if self.__checkForDraw(): display.clear() display.board(self) print("It's a draw") return False return True
def drawPage(duration): now = datetime.now() duration = timedelta(seconds=duration) MQTT.loop_start() while (datetime.now() - now).seconds < duration.seconds: display.clear() y = display.drawHeader(15, "Mosquitto") drawEntries(y) display.show() time.sleep(.1) MQTT.loop_stop() return
def drawstuff(self): if self.mywalker!=None: display.lookat((self.mywalker.x+self.mywalker.gmx)/2, (self.mywalker.y+self.mywalker.gmy)/2) self.drawradar() display.clear() display.applycam() terrain.draw(display.camx,display.camy) for b in self.walkers: b.draw() particles.draw() self.menu.drawLog() pygame.display.flip()
def flanker_task(instruction, label, duration): """Function for displaying Flanker Task. Args: instruction (str): instruction to be displayed on the screen label (int): label of Flanker Task duration (float): set the duration of Flanker Task session """ session_start = session_starter(instruction, label) event.clearEvents() trial_count = 1 while time.time() < session_start + duration: trial_start = time.time() # the starting time of the trial logs.trial_log(trial_start, label, trial_count, "starts") display.play_alarm() display.fixture() variable_duration_list = [0.3, 0.6, 0.9, 1.2] core.wait(random.choice(variable_duration_list)) fixture_time = time.time() # the time when the fixture is displayed logs.trial_log(fixture_time, label, trial_count, "fixture_displayed") event.clearEvents() ori, stimulus_time = display.flanker_task() keyboard = event.waitKeys(maxWait=2) press_time = time.time() # the time when user responds logs.trial_log(stimulus_time, label, trial_count, 'ori=' + str(ori)) display.clear() if ori == 0: correct_key = 'right' else: correct_key = 'left' try: if keyboard.pop() == correct_key: answer = "correct" else: answer = "wrong" except: answer = "no_press" logs.trial_log(press_time, label, trial_count, answer) reaction_time = press_time - stimulus_time logs.user_reaction_log(label, trial_count, reaction_time, answer) logs.trial_log(trial_start, label, trial_count, "ends") trial_count += 1 core.wait(1) session_end = time.time() logs.session_log(session_end, label, "ends")
def receive_data(self): while self.connected: data = "" try: data = self.conn.recv(512) except: self.kill(False) if data != "": display.clear() display.set_display_manual({0: (ord(data[0]) << 16) | (ord(data[1]) << 8) | ord(data[2])}) else: self.kill(False)
def visualize(self, x0, x, losses, *kwargs): """ visualizes current trainnig step results """ if self.current_step % 50 == 0: disp.clear() disp.visualize_batch(self.g_model.ca, x0, x, self.current_step, white_background=False) if cfg.TRAIN.GANCA_LOSS_TYPE == "WGAN": disp.plot_wgan_loss(self.losses) else: disp.plot_ganca_loss(self.losses)
def main(chords, tempo, duration, omit_display, omit_play): """Play a sequence of chords.\n e.g. python picardy.py Cm Ddim G7 Cm """ for chord in chords: notes = utils.get_indices(lut.lut[utils.get_canonical_name(chord)]) if not omit_display: display.clear() display.draw_keyboard(notes) print(utils.get_canonical_name(chord)) if not omit_play: play.play_chord(notes, tempo, duration) time.sleep(duration * 60 / tempo)
def receive_data(self): while self.connected: data = '' try: data = self.conn.recv(512) except: self.kill(False) if data != '': display.clear() display.set_display_manual({ 0: (ord(data[0]) << 16) | (ord(data[1]) << 8) | ord(data[2]) }) else: self.kill(False)
def interact(noun,verb): interactdict = { "feel": "You reach out and touch the " + noun + ".", "push": "You lean into the " + noun + " and push.", "taste": "You brace your delicate palate and lick the " + noun + ".", "listen": "You listen intently to the " + noun + ".", "smell": "You take a long whiff of the " + noun + ".", "pull": "You tug at the " + noun + "." } newthingdict = { "feel": "What does it feel like?", "push": "What happens?", "taste": "What does it taste like?", "listen": "What does it sound like?", "smell": "What does it smell like?", "pull": "What happens?" } if noun in creator.thingdict: display.clear() t = interactdict[verb] h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) p.tw(True) if creator.thingdict[noun].feel == "": display.clear() t = newthingdict[verb] h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) creator.thingdict[noun].feel = display.inp(p) else: display.clear() t = creator.thingdict[noun].feel h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) p.tw(True) else: creator.thingdict[noun] = creator.thing(noun) display.clear() t = interactdict[verb] h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) p.tw(True) display.clear() t = newthingdict[verb] h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) creator.thingdict[noun].feel = display.inp(p)
def read(sentence): try: sarray = sentence.split(" ", 1) verb = sarray[0].lower() noun = sarray[1].lower() except: display.clear() t = "The universe is not yet ready for such a marvel." h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) p.tw(False) t = "A valid sentence is of the form 'Verb Noun'." h = len(t)/2 p = display.msg(y/2+1,x/2-h,0.1,t) p.tw(True) display.clear() return None verblist = ["push","pull","taste","listen","smell","feel"] if verb in verblist: interact(noun,verb) elif verb == "quit": t = "Thanks for playing!" h = len(t)/2 p = display.msg(y/2,x/2-h,0.1,t) display.clear() p.tw(True) display.end() curses.endwin() exit() else: display.clear() m = "Humanity is not yet capable of such feats. Try doing something else." h = len(m)/2 o = display.msg(y/2,x/2-h,0.1,m,'right') o.tw(False) m = "Valid verbs are: Taste, Feel, Listen, Smell, Push, and Pull." h = len(m)/2 o = display.msg(y/2+1,x/2-h,0.1,m,'right') o.tw(False) m = "You can also type 'quit game' to recover your sight." h = len(m)/2 o = display.msg(y/2+2,x/2-h,0.1,m,'right') o.tw(True) display.clear() return None
def command(noun,verb): if verb == 'cr': ## Doesn't make much sense for this to be populated here. Should break this out at some point. ## TODO: Fix this. roomlist = { 'airlock': Room('Airlock'), 'bridge': Room('Bridge'), 'hydroponics': Room('Hydroponics'), 'medical': Room('Medical'), 'engineering': Room('Engineering'), 'propulsion': Room('Propulsion') } if noun in roomlist: m = "Command accepted. Accessing room diagnostics for " + noun + "." display.clear(display.lwin) display.msg(m) display.clear(display.lwin) display.msg(roomlist[noun].cam())
def visualize(self, x0, x, losses, grads, run_id=0): """ Check current step and visualize current results """ # TODO losses does not need to be used as all information should be in loss_log step_i = len(self.loss_log) # Clearing display, to "update" the graph/msg # Viz loss and results if step_i % 50 == 0: # TODO not working together, with plot as it keeps refreshing # And I am unable to see anything # disp.visualize_batch(self.ca, x0, x, step_i) disp.clear() disp.visualize_batch(self.ca, x0, x, step_i, white_background=False) # disp.plot_loss(self.x_log, title="max(x)**2") # disp.plot_loss(self.pool_log, title="max(Pool)**2") # disp.plot_loss(self.grad_log) # print(self.val_loss_log) disp.plot_train_and_val_loss(self.loss_log, self.val_loss_log, y_range="auto") # disp.plot_losses(self.loss_log, y_range=(0,400)) # pass # Viz current pool if cfg.TRAIN.USE_PATTERN_POOL and step_i % 100 == 0: pass # TODO # utils.generate_pool_figures(self.ca, self.pool, step_i) # Simple print to show progress, will be overwritten in each step print('\r r: %d step: %d, total_loss: %.3f min: %.3f max: %.3f' % (run_id, step_i, losses[0], np.amin( self.loss_log), np.amax(self.loss_log)), end='')
def prepPhase(mapP, boats): """Prépare la carte pour un des joueurs. C'est la phase de placement des bateaux.""" displayMapPrep(mapP) while True: number_boats = 0 #Il s'agit du nombre de bateaux qu'il reste à placer. for boat in boats.values(): number_boats += boat[ 0] #Le nombre de bateaux d'une certaine taille est stocké au premier index de la liste. if number_boats == 0: for boat in boats.values(): del boat[ 0] #On enlève le nombre de bateaux à placer, qui n'est plus nécessaire par la suite. break boatsLeft = "Il vous reste : \n" for taille, nombre in boats.items(): boatsLeft += "{} bateau(x) de taille {}\n".format( nombre[0], taille) print(boatsLeft) print("Donner les cases de début et de fin de votre bateau.") row1, column1 = squareInput(mapP) row2, column2 = squareInput(mapP) # clear() if row1 == row2: if isBigger(column1, column2): placeOrReset(mapP, row1, column2, column1, boats) else: placeOrReset(mapP, row1, column1, column2, boats) elif column1 == column2: if isBigger(row1, row2): placeOrReset(mapP, column1, row2, row1, boats) else: placeOrReset(mapP, column1, row1, row2, boats) elif row1 != row2 and column1 != column2: #Par exemple A1 et E5 ne sont pas alignées. print("Erreur! Les cases {}{} et {}{} ne sont pas alignées.\n". format(row1, column1 + 1, row2, column2 + 1)) displayMapPrep(mapP) if screenClean(): clear()
def blink_events(): for event in g_calendar.events: blink_color = g_calendar.color_ids[event["colorId"]] if "colorId" in event else 0xFFFFFF event_date = dateutil.parser.parse( event["start"]["dateTime"] if "dateTime" in event["start"] else event["start"]["date"] ) event_date = event_date.replace(tzinfo=None) delta = event_date - datetime.datetime.now() if delta < datetime.timedelta(hours=10): display.clear() time.sleep(0.5) display.set_display(int(delta.seconds / 3600), True, blink_color) time.sleep(0.5) display.set_display(16, False, blink_color) time.sleep(0.5) display.clear() else: display.set_display_manual({0: blink_color}) time.sleep(0.5) display.set_display_manual({0: 0}) time.sleep(0.5)
def main(): display.clear() option = display.menu() display.clear() if option == "0": print("Bye :(") elif option == "1": play() main() elif option == "2": newUser() main() else: input("Not a valid option, press enter to continue...") display.clear() main()
def total_album_price(): total = 0 for album in catalog: total += album.price print(f'total: {total}') # instructions deserialize_data() input("press enter to continue...") opc = '' while (opc != 'q' and opc != 'x'): clear() print_menu() opc = input("Please select an option: ") if (opc == '1'): register_album() serialize_data() elif (opc == '2'): register_song() serialize_data() elif (opc == '3'): print_albums() elif (opc == '4'): print_album_songs()
def redraw(): display.clear((64,64,64)) # Draw the map display.fill_rect((0,0, 400,400), (0,0,0)) Player.cur_level.recalc_light() for x,y in box2d(-12, -12, 25, 25): # for each tile in the player's map range: ax, ay = x+Player.x, y+Player.y if Player.cur_level.in_bounds(ax, ay): cur_tile = Player.cur_level.tiles[ax][ay] seen = Player.can_see(ax, ay) if seen == 1: # Illuminated and in LoS cur_tile.memorized = True # draw the terrain display.draw_sprite(cur_tile.img, ((x+12)*16, (y+12)*16)) # draw each item, starting with the ones on the bottom of the pile for i in cur_tile.items: display.draw_sprite(i.img, ((x+12)*16, (y+12)*16)) elif seen == 2: # In night vision range cur_tile.memorized = True display.draw_sprite(cur_tile.img, ((x+12)*16, (y+12)*16), sheet=display.sprites_blue) # draw each item, starting with the ones on the bottom of the pile for i in cur_tile.items: display.draw_sprite(i.img, ((x+12)*16, (y+12)*16), sheet=display.sprites_blue) elif cur_tile.memorized: display.draw_sprite(cur_tile.img, ((x+12)*16, (y+12)*16), sheet=display.sprites_grey) for i in cur_tile.items: if not i.holdable: display.draw_sprite(i.img, ((x+12)*16, (y+12)*16), sheet=display.sprites_grey) # Draw creatures, including the player for c in Player.cur_level.creatures: sx, sy = c.x-Player.x+12, c.y-Player.y+12 if 0 <= sx < 25 and 0 <= sy < 25 and Player.can_see(c.x, c.y): display.draw_sprite(c.img, (sx*16, sy*16)) if c != Player: # health bar display.fill_rect((sx*16, sy*16, 16*(float(c.hp)/c.maxhp), 1), (255,0,0)) # Message log display.fill_rect((5,405, 790,190), (32,32,32)) display.msg_log.draw((10, 410), 160) # Player text entry if Player.entering_text: display.fill_rect((9,575, 782,16), (64,64,64)) display.draw_text(Player.entered_text, (12,576)) # Draw player's health bar display.fill_rect((400,0, 400,16), (128,0,0)) display.fill_rect((400,0, 400*(float(Player.hp)/Player.maxhp), 16), (255,0,0)) display.draw_text('HP: %d/%d' % (Player.hp, Player.maxhp), (405, 1)) # energy bar display.fill_rect((400,16, 400,16), (192,192,192)) display.fill_rect((400,16, 400*(float(Player.mp)/Player.maxmp), 16), (255,255,0)) display.draw_text('ENERGY: %d/%d' % (Player.mp, Player.maxmp), (405, 17), (0,0,0)) # Player's wealth and inventory display.draw_text('Gold: %d' % (Player.gold), (405, 40), (255,255,0)) display.draw_text('Inventory', (410, 156)) INV_X = 420 INV_Y = 190 INV_W = 10 INV_H = 10 # inventory slot boxes for i in xrange(INV_W*INV_H): x,y = i%INV_W, i//INV_W display.draw_rect((INV_X+x*21, INV_Y+y*21, 20, 20), (255,255,255)) # inventory axis labels (for EZ-dropping/selling) for i in xrange(INV_W): display.draw_text('%d' % i, (INV_X+i*21+6, INV_Y-15)) for i in xrange(INV_H): display.draw_text('%d' % i, (INV_X-9, INV_Y+i*21+3)) # actual items for i,item in enumerate(Player.inv): x,y = i%INV_W, i//INV_W display.draw_sprite(item.img, (INV_X+2+x*21, INV_Y+2+y*21)) # Equipment (garb) EQ_X = 640 EQ_Y = 200 display.draw_text('Your equipment:', (EQ_X, EQ_Y)) if Player.equipment: for i,item in enumerate(Player.equipment): EQ_Y += 16 if item.equip_slot: display.draw_text('%d: %s (%s)' % (i,item.name,item.equip_slot), (EQ_X, EQ_Y)) else: display.draw_text('%d: %s' % (i,item.name), (EQ_X, EQ_Y)) else: EQ_Y += 16 display.draw_text('None!', (EQ_X, EQ_Y)) EQ_Y += 16 # also write empty slots under garb for slot in Player.equip_slots.iterkeys(): fs = Player.equip_slots[slot] - Player.equipped[slot] if fs: EQ_Y += 16 if fs == 1: pl = '' else: pl = 's' display.draw_text('%d free slot%s (%s)' % (fs,pl,slot), (EQ_X, EQ_Y)) # Stats display.draw_text('Attack damage: %d-%d' % (Player.min_atk, Player.max_atk), (420, 60)) display.draw_text('Attack speed: %d' % (10000/Player.attack_time), (420, 76)) display.draw_text('Move speed: %d' % (10000/Player.move_time), (420, 92)) display.update()
lcd = lcd.TFT() lcd.init(lcd.M5STACK, width=240, height=320, speed=40000000, rst_pin=33, miso=19, mosi=23, clk=18, cs=14, dc=27, bgr=True, invrot=3, expwm=machine.PWM(32, duty=0, timer=1)) lcd.setBrightness(30) lcd.clear() lcd.setColor(0xCCCCCC) print('Done!') #BUTTON m5button = Button() buttonA = m5button.register(_BUTTON_A_PIN) buttonB = m5button.register(_BUTTON_B_PIN) buttonC = m5button.register(_BUTTON_C_PIN) # SPEAKER speaker = Speaker() # ----------------------- for flow----------------------------------------- # def wait(s):
def load_game(): display.clear() # Get all save files saves = glob.glob("res/saves/*.plr") # Parse res/saves/FILE.plr to just FILE. Much better for display, don't want the res/ for pickling. saves = [file[10:-4] for file in saves] if len(saves) == 0: display.printc(30, 8, "No saves were found...") display.flushinp() while display.getch() == -1: pass display.end() # Break saves into pages. PAGE_SIZE = 25 pages = [[]] for opt in saves: # Add every object to the list. if len(pages[-1]) == PAGE_SIZE: # If list overflow, add a new page pages.append([]) # Add option to last element in pages. Also should edits it to give amount held too. pages[-1].append(opt) curr_page = 0 choice = 0 # Display first page for index in range(len(pages[curr_page])): display.printc(10, index, pages[curr_page][index]) # Print out the option display.printc(9, 0, '>') # Cursor display.refresh() can_up = True can_down = True while True: # Now loop and wait for a choice if (display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP)) and can_up: # Go up 1. display.printc(9, choice, ' ') # Remove old arrow if choice == 0: # Already at top of page. if curr_page == 0: curr_page = len(pages) - 1 # Go to last page else: # Go up a page curr_page -= 1 choice = len(pages[-1]) # Go to bottom of page display.clear() # Clear all the old stuff. for index in range(len(pages[curr_page])): # Draw the new page display.printc(10, index, pages[curr_page][index]) # Print out the option choice -= 1 # Go up 1. display.printc(9, choice, '>') # Redraw arrow display.refresh() # Refresh screen can_up = False if not (display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP)): can_up = True if (display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN)) and can_down: # Go down 1. display.printc(9, choice, ' ') # Remove old arrow if choice == len(pages[curr_page]) - 1: # Already at bottom of page. if curr_page == len(pages) - 1: curr_page = 0 # Go to first page else: # Go down a page curr_page += 1 choice = -1 # Go to top of page display.clear() # Clear all the old stuff. for index in range(len(pages[curr_page])): # Draw the new page display.printc(10, index, pages[curr_page][index]) # Print out the option choice += 1 # Go down 1. if choice == len(pages[curr_page]): choice -= 1 # At bottom, can't go down display.printc(9, choice, '>') # Redraw arrow display.refresh() # Refresh screen can_down = False if not (display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN)): can_down = True # TODO: Possibly let them easily skip through pages with AD and left/right arrow keys if display.keyDown(display.CONST.VK_RETURN): file = pages[curr_page][choice] world.load_player(file) return
import display from threadz import myThread thread1 = myThread(1, "Thread-1", display.lwin) thread2 = myThread(2, "Thread-2", display.rwin) thread1.start() thread2.start() display.clear(display.scr) display.end(display.scr) display.curses.endwin()
def read(sentence): try: sarray = sentence.split(" ", 1) verb = sarray[0].lower() noun = sarray[1].lower() except: display.clear(display.lwin) display.clear(display.rwin) t = "Error. Invalid input detected." p = display.msg(t,False) read(display.inp()) #display.clear() return None verblist = ["cr"] if verb in verblist: command(noun,verb) elif verb == "quit": t = "Thanks for playing!" display.clear() p = display.msg(t) display.end() curses.endwin() exit() else: display.clear() m = "Error. Unknown command." display.msg(m,False) display.clear(display.lwin) m = "Valid commands are: cr" display.msg(m,False) display.clear(display.lwin) m = "Or enter 'quit game' to format your own hard drive." display.msg(m,False) read(display.inp()) return None
def intro2(): display.clear(display.lwin) display.msg("./program",False) display.clear(display.rwin) display.inp() display.clear(display.lwin) display.msg("Hail, Program.",False) display.clear(display.lwin) display.msg("Would you kindly open the pod bay doors?",False) display.clear(display.rwin) display.inp() display.clear(display.lwin) display.msg("Oh, right, you're the new generation.",False) display.clear(display.lwin) display.msg("First, you need to access the airlock.",False) display.clear(display.lwin) display.msg("Just type 'cr airlock' to access the airlock systems.",False) display.clear(display.rwin) parse.read(display.inp())
def help_menu(): display.clear() display.printc(0, 0, "pyRPG is a real-time terminal based RPG") display.printc(0, 4, "In a menu, use either the UP ARROW key or the Q key to move your cursor up") display.printc(0, 5, "Use either the DOWN ARROW key or the E key to move your cursor down") display.printc(0, 6, "Use ENTER to select the current option") display.printc(0, 9, "Character controls:") display.printc(0, 10, "Use WASD to move and IJKL to attack directionally") display.printc(0, 11, "Press SPACE to cast your current spell, set in the Spell menu") display.printc(0, 12, "Press LEFT SHIFT to use your item, set in the Consumable menu of your inventory") display.printc(0, 13, "Press ESC to open the main menu to save, access inventory, set spell, or exit") display.printc(0, 15, "Press ENTER to go to page two or press ESC to exit to the main menu") display.refresh() while (not display.keyDown(display.CONST.VK_ESCAPE)) and (not display.keyDown(display.CONST.VK_RETURN)): pass # Wait for press of ESC or ENTER if display.keyDown(display.CONST.VK_ESCAPE): while display.keyDown(display.CONST.VK_ESCAPE): pass # Wait for release return while display.keyDown(display.CONST.VK_RETURN): pass # Wait for release # Now give page 2 of the menu. display.clear() display.printc(0, 0, "Colors and symbols guide:") display.printc(0, 2, "Colors:") display.printc(0, 3, "Red", display.RED) display.printc(4, 3, "is either a locked portal ( ) or an obstacle. Often, objects hurt.") display.printc(31, 3, "O", display.RED) display.printc(57, 3, "red", display.RED) display.printc(0, 4, "White objects tend to be neutral. Walls (#) and floors (.) tend to be white.") display.printc(0, 5, "Blue", display.BLUE) display.printc(5, 5, "objects are often portals ( ). Also, player attacks ( ) are blue.") display.printc(32, 5, "O", display.BLUE) display.printc(58, 5, "!", display.BLUE) display.printc(0, 6, "Cyan", display.CYAN) display.printc(5, 6, "objects are enemies. All enemies are and all things are enemies.") display.printc(42, 6, "cyan", display.CYAN) display.printc(55, 6, "cyan", display.CYAN) display.printc(0, 7, "Green", display.GREEN) display.printc(6, 7, "objects are grass( ) and NPCs. Talk to things that are .") display.printc(24, 7, ';', display.GREEN) display.printc(61, 7, "green", display.GREEN) display.printc(0, 8, "Magenta", display.MAGENTA) display.printc(8, 8, "tends not to be used. Enemy attacks ( ) are .") display.printc(45, 8, "!", display.MAGENTA) display.printc(52, 8, "magenta", display.MAGENTA) display.printc(0, 9, "Yellow", display.YELLOW) display.printc(7, 9, "is loot! Money ( ) and chests ( ) are . things are good.") display.printc(23, 9, "$", display.YELLOW) display.printc(38, 9, "@", display.YELLOW) display.printc(45, 9, "yellow", display.YELLOW) display.printc(53, 9, "Yellow", display.YELLOW) display.printc(0, 11, "Common Symbols:") display.printc(0, 12, "@", display.YELLOW) display.printc(2, 12, "is a chest. Stand next to to see what it holds!") display.printc(0, 13, "# is a wall. Walls block movement of the player, attacks, and enemies.") display.printc(0, 14, ". is a common ground tile. It does nothing special.") display.printc(0, 15, "#", display.RED) display.printc(2, 15, "is lava. Stepping on it hurts!") display.printc(0, 16, ';', display.GREEN) display.printc(2, 16, "is a common ground tile. It does nothing special.") display.printc(0, 17, "| \\\\ /", display.YELLOW) display.printc(6, 17, "are levers. Stand next to it and press ENTER to pull it. What does it do?") display.printc(0, 20, "These are common trends and there are objects that break these trends.") display.printc(0, 21, "However, they hold true for most objects that you will encounter.") display.printc(0, 22, "Also, the rule about cyan objects ALWAYS holds.") display.printc(21, 22, "cyan", display.CYAN) display.printc(0, 24, "Press ENTER to continue...") display.refresh() while not display.keyDown(display.CONST.VK_RETURN): pass while display.keyDown(display.CONST.VK_RETURN): pass return
def start(): """Gives the main menu option to load a file, create a new file, or exit""" display.printc(28, 10, "Welcome to pyRPG!") display.printc(30, 11, ">Load a file") display.printc(31, 12, "New game") display.printc(31, 13, "Multiplayer") display.printc(31, 14, "Exit game") display.printc(28, 15, "Press H for help") display.refresh() opt = 0 while True: # Move cursor up if w or up key pressed if display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP): # Clear old cursor display.printc(30, opt + 11, ' ') opt -= 1 if opt < 0: opt = 3 # Redraw for good menu display.printc(30, opt + 11, '>') display.refresh() # Wait for release while display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP): pass # Move cursor down if s or down key pressed if display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN): # Clear old cursor display.printc(30, opt + 11, ' ') opt += 1 if opt > 3: opt = 0 # Redraw for good menu display.printc(30, opt + 11, '>') display.refresh() # Wait for release while display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN): pass # If they have e or enter pressed, they chose an option. if display.keyDown(display.CONST.VK_RETURN): # Wait for key release while display.keyDown(display.CONST.VK_RETURN): pass if opt == 0: load_game() display.clear() return if opt == 1: new_game() world.player.attributes["HP"] = world.player.attributes["maxHP"] world.player.attributes["MP"] = world.player.attributes["maxMP"] world.save_player() display.clear() return if opt == 2: multiplayer.multiplayer() display.clear() display.printc(28, 10, "Welcome to pyRPG!") display.printc(31, 11, "Load a file") display.printc(31, 12, "New game") display.printc(30, 13, ">Multiplayer") display.printc(31, 14, "Exit game") display.printc(28, 15, "Press H for help") display.refresh() if opt == 3: display.end() # They chose exit # They need help! if display.keyDown(ord('H')): help_menu() display.clear() display.printc(28, 10, "Welcome to pyRPG!") display.printc(31, 11, "Load a file") display.printc(31, 12, "New game") display.printc(31, 13, "Multiplayer") display.printc(31, 14, "Exit game") display.printc(28, 15, "Press H for help") display.printc(30, opt + 11, '>') display.refresh()
def multiplayer(): # Get username and password. display.clear() display.flushinp() inpt = display.getch() curs_loc = 0 char_name = "" display.printc(30, 9, "Enter your name:") while inpt != 10: # Until ENTER pressed if inpt == 8: # Backspace if curs_loc != 0: curs_loc -= 1 char_name = char_name[:-1] # Remove last character display.printc(curs_loc + 30, 10, ' ') elif (inpt != -1) and (curs_loc < 45) and (chr(inpt) in "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-1234567890 "): # Also don't let them get too long. 45 chosen arbitrarily because yeah. display.printc(curs_loc + 30, 10, chr(inpt)) char_name += chr(inpt) curs_loc += 1 display.refresh() inpt = display.getch() # Wait for release while display.keyDown(display.CONST.VK_RETURN): pass if char_name == len(char_name) * ' ': char_name = "default" curs_loc = 0 password = "" inpt = display.getch() display.printc(30, 11, "Enter your Password:"******"Passwords must be at least 8 characters.") elif inpt != -1: display.printc(30, 13, " ") if inpt == 8: # Backspace if curs_loc != 0: curs_loc -= 1 password = password[:-1] # Remove last character display.printc(curs_loc + 30, 12, ' ') elif (inpt != -1) and (curs_loc < 45) and (inpt < 127) and (inpt > 31): # Most characters allowed in password. Just has to be a printable ASCI display.printc(curs_loc + 30, 12, chr(inpt)) password += chr(inpt) curs_loc += 1 display.refresh() inpt = display.getch() # Wait for release while display.keyDown(display.CONST.VK_RETURN): pass display.clear() display.draw_topbar() display.refresh() world.map = [[ [0, 1, '!'] for y in range(world.WORLD_Y)] for x in range(world.WORLD_X)] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(1) try: sock.sendto(bytes(char_name, 'utf-8'), ('localhost', 5000)) (data, new_addr) = sock.recvfrom(65507) last_update = time.clock() # All coord pairs to overwrite. to_overwrite = [] sidebar_lines = 0 # ID of current map we're in. Useful for server. current_map = 0 class states: WORLD = 0 INVENTORY = 1 class inventory: # Only one of these exists so we can just modify class stuff. class item: def __init__(this, name, desc, amount, value): this.name = name this.desc = desc this.value = value this.amount = amount selected_index = 0 current_type = "weapon" weapons = [] hats = [] shirts = [] pants = [] rings = [] consumables = [] def str_to_list(string): return [inventory.weapons, inventory.hats, inventory.shirts, inventory.pants, inventory.rings, inventory.consumables][["weapon", "hat", "shirt", "pants", "ring", "consumable"].index(string)] def clear(): # Clears entire inventory. inventory.weapons.clear() inventory.hats.clear() inventory.shirts.clear() inventory.pants.clear() inventory.rings.clear() inventory.consumables.clear() def add_item(data): # Adds an item based off of current data split_data = [bytearray(g) for k,g in itertools.groupby(data, lambda x: x == 0) if not k] # Data is packed as type, name, desc, amount, value. First 3 are null terminated strings type = split_data[0].decode('utf-8') name = split_data[1].decode('utf-8') desc = split_data[2].decode('utf-8') amount = struct.unpack("!I", data[len(data) - 8: len(data) - 4])[0] # Unpack last bytes. value = struct.unpack("!I", data[len(data) - 4: len(data)])[0] inventory.str_to_list(type).append(inventory.item(name, desc, amount, value)) state = states.WORLD while True: # Let players force quit with Ctrl+Q if display.keyDown(display.CONST.VK_CONTROL) and display.keyDown(ord('Q')) or (time.clock() - last_update > 1.0): while display.keyDown(ord('Q')): pass sock.close() return if select.select([sock], [], [], 0) != ([], [], []): data, addr = sock.recvfrom(65507) while select.select([sock], [], [], 0) != ([], [], []): sock.recvfrom(65507) last_update = time.clock() if state == states.WORLD: index = 1 # Current data index if data[0] == NEWMAP: current_map = data[index] index += 1 map_size = struct.unpack("!I", data[index:index + 4])[0] # 4 bytes for size of map index += 4 world.map = unpack_map(data[index: index + map_size]) index += map_size world.dispworld() display.refresh() elif data[0] == TO_INV: display.printc(0, 5, ((" " * 80) + "\n") * 25) # Should clear main screen. # Now print out inventory. display.printc(0, 5, "Inventory: \\fyWeapons(1)\\fw Hats(2) Shirts(3) Pants(4) Rings(5) Consumables(6)") display.printc(0, 6, "Name/Description Value Amount") display.printc(0, 7, '-' * 80) inventory.clear() # Clear old inv data. index = 1 # Current data index. while index < len(data): num_bytes = struct.unpack("!I", data[index: index + 4])[0] # Number of bytes in item index += 4 # increment index inventory.add_item(data[index: index + num_bytes]) # Add the item. index += num_bytes # Set last tracking vals inventory.current_type = "weapon" inventory.selected_index = 0 # Now print out inventory display.printc(0, 8, ">") # Draw cursor. loc = 8 # y location to print item at. for itm in inventory.weapons: # Default to weapons display.printc(1, loc, itm.name) display.printc(50, loc, str(itm.value)) display.printc(65, loc, str(itm.amount)) display.printc(2, loc + 1, itm.desc) loc += 2 if loc > 23: # Can't print more. So we get 12 items per sheet. break display.refresh() state = states.INVENTORY continue # Finish loop # Here we do our updating # So we need to redraw objects, HP/MP, gold, sidebar, and possibly equipment/spellbox/itembox # Remove all previous objects for elem in to_overwrite: display.printc(elem[0], elem[1], world.map[elem[0]][elem[1] - 5][2], world.map[elem[0]][elem[1] - 5][0]) to_overwrite.clear() num_objs = data[index] index += 1 # Redraw all new objects while num_objs > 0: x_loc = data[index] y_loc = data[index + 1] index += 2 char = data[index: index + unicode_bytes(data[index])].decode('utf-8') # Total char length for unicode char index += unicode_bytes(data[index]) # Increment counter color = data[index] index += 1 display.printc(x_loc, 5 + y_loc, char, color, world.map[x_loc][y_loc][1]) to_overwrite.append((x_loc, 5 + y_loc)) num_objs -= 1 # Draw HP and MP HP = struct.unpack("!I", data[index:index + 4])[0] maxHP = struct.unpack("!I", data[index + 4 : index + 8])[0] display.printc(8, 0, ' ' * 17) display.printc(8, 0, str(HP) + "/" + str(maxHP)) index += 8 MP = struct.unpack("!I", data[index:index + 4])[0] maxMP = struct.unpack("!I", data[index + 4 : index+8])[0] display.printc(8, 1, ' ' * 17) display.printc(8, 1, str(MP) + "/" + str(maxMP)) index += 8 # Draw level, EXP, gold: level = struct.unpack("!I", data[index: index + 4])[0] exp = struct.unpack("!I", data[index + 4: index + 8])[0] gold = struct.unpack("!I", data[index + 8: index + 12])[0] display.printc(12, 3, str(level)) display.printc(5, 4, ' ' * 20) display.printc(5, 4, str(int(exp)) + " to level") display.printc(10, 2, ' ' * 15) display.printc(10, 2, str(gold)) index += 12 # Print spell box, item box spell_len = struct.unpack("!I", data[index: index + 4])[0] index += 4 display.printc(display.SPELL_BOX_START + 1, 1, data[index: index + spell_len].decode('utf-8')) index += spell_len item_len = struct.unpack("!I", data[index: index + 4])[0] index += 4 display.printc(display.ITEM_BOX_START + 1, 1, data[index: index + item_len].decode('utf-8')) index += item_len # Prints equipment y_print = 0 for equip in [display.WEAPON_X, display.HAT_X, display.SHIRT_X, display.PANTS_X, display.RING_X]: equip_len = struct.unpack("!I", data[index : index + 4])[0] index += 4 display.printc(equip, y_print, ' ' * 37) display.printc(equip, y_print, data[index : index + equip_len].decode('utf-8')) index += equip_len y_print += 1 # Now, we see if we have sidebar stuff to print. # So overwrite previous sidebar for ind in range(sidebar_lines): display.printc(50, ind + 5, ' ' * 30) sidebar_length = struct.unpack("!I", data[index: index + 4])[0] index += 4 display.printc(50, 5, data[index : index + sidebar_length].decode('utf-8')) sidebar_lines = display.getyx(display.stdscr)[0] - 4 # We know how far down we printed by where the cursor is. display.refresh() elif state == states.INVENTORY: # We can ignore data sent. So all we do is check kbd input and update based on that last_a = False if last_a and not display.keyDown(ord('A')): display.printc(0, 0, 'B') if display.keyDown(ord('A')): display.printc(0, 0, 'A') last_a = True display.refresh() # Sends what keys are down. # Byte Key # 0 W # 1 A # 2 S # 3 D # 4 I # 5 J # 6 K # 7 L # 8 SHIFT # 9 SPACE # 10 ENTER # 11 Q/UP # 12 E/DOWN # 13 U # 14 O # 15 ESC # 16 Special: Current map ID. Not actually a key. to_send = bytearray(20) if state == states.WORLD: # Only send kbd input if we're in the world. to_send[0] = states.WORLD # Sending world input to_send[1] = display.keyDown(ord('W')) to_send[2] = display.keyDown(ord('A')) to_send[3] = display.keyDown(ord('S')) to_send[4] = display.keyDown(ord('D')) to_send[5] = display.keyDown(ord('I')) to_send[6] = display.keyDown(ord('J')) to_send[7] = display.keyDown(ord('K')) to_send[8] = display.keyDown(ord('L')) to_send[9] = display.keyDown(display.CONST.VK_LSHIFT) to_send[10] = display.keyDown(ord(' ')) to_send[11]= display.keyDown(display.CONST.VK_RETURN) to_send[12]= display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP) to_send[13]= display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN) to_send[14]= display.keyDown(ord('E')) to_send[15]= display.keyDown(ord('U')) to_send[16]= display.keyDown(ord('O')) to_send[17]= display.keyDown(ord('V')) to_send[18]= display.keyDown(display.CONST.VK_ESCAPE) to_send[19] = current_map elif to_send == states.INVENTORY: to_send[0] = states.INVENTORY sock.sendto(to_send, new_addr) except ConnectionResetError as ex: sock.close() return except Exception as ex: return
states = { 'quit': s_Quit, 'menu': s_Menu, 'generate': s_WorldGen, 'play': s_Play, 'death': s_Death } for (name, s) in states.items(): s.registerStates(states) ''' Main ''' currentState = s_WorldGen while not libtcod.console_is_window_closed() : disp.render(currentState) currentState.inputHandler.handleInput() currentState.tick() newState = currentState.nextState if newState != currentState: currentState.reset() currentState = newState currentState.beforeTransition() disp.clear()
for event in g_calendar.events: if "colorId" in event: display.set_display_manual({0: g_calendar.color_ids[event["colorId"]]}) else: display.set_display_manual({0: 0xffffff}) time.sleep(0.5) display.set_display_manual({0: 0}) time.sleep(0.5) display.set_display_manual({0: dp_off_color}) # main display.init() infinity() display.clear() g_calendar.init() # tcp_server = clockconnect.Server() tcpserver.init() logging.basicConfig(filename='CLOCK.log', level=logging.INFO) logging.info(str(time.time())+" : started") while True: try: if not tcpserver.connected: if time.time() > next_update_calendar: logging.info(str(time.time())+" : update calendar") next_update_calendar = time.time() + 5 new = g_calendar.update() if new: next_calendar_notification = time.clock()
def new_game(): # Get their save name display.clear() display.flushinp() inpt = display.getch() curs_loc = 0 file_name = "" display.printc(30, 9, "Enter your name:") while inpt != 10: # Until ENTER pressed if inpt == 8: # Backspace if curs_loc != 0: curs_loc -= 1 file_name = file_name[:-1] # Remove last character display.printc(curs_loc + 30, 10, ' ') elif (inpt != -1) and (curs_loc < 45) and (chr(inpt) in "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-1234567890 "): # Also don't let them get too long. 45 chosen arbitrarily because yeah. display.printc(curs_loc + 30, 10, chr(inpt)) file_name += chr(inpt) curs_loc += 1 display.refresh() inpt = display.getch() # Wait for release while display.keyDown(display.CONST.VK_RETURN): pass if file_name == len(file_name) * ' ': file_name = "default" world.save_name = file_name # Class select! # What color each class should be color_list = [display.RED, display.BLUE, display.YELLOW] # What the middle text is for each class text_list = ["+ Warrior +", "+ Mage +", "+ Thief +"] # The box of '+'s top and bottom box = '+' * 14 # Number of rows each box takes up. 3 for the box + 2 for the space below box_size = 5 # Where the boxes start display on y-axis box_start = 4 # Left side of boxes box_left = 32 # Clear screen and set up menu. display.clear() for i in range(len(text_list)): display.printc(box_left, box_start + i * box_size, box) display.printc(box_left, box_start + i * box_size + 1, text_list[i]) display.printc(box_left, box_start + i * box_size + 2, box) # Draw first box in color display.printc(box_left, box_start, box, color_list[0]) display.printc(box_left, box_start + 1, text_list[0], color_list[0]) display.printc(box_left, box_start + 2, box, color_list[0]) choice = 0; display.refresh() while True: # Check for choice down/up if display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP): # Redraw current box in white display.printc(box_left, box_start + choice * box_size, box) display.printc(box_left, box_start + choice * box_size + 1, text_list[choice]) display.printc(box_left, box_start + choice * box_size + 2, box) # If decrementing choice would bring it below zero, set it to one past last if choice == 0: choice = len(text_list) # And decrement it. choice -= 1 # Redraw new box in correct color. display.printc(box_left, box_start + choice * box_size, box, color_list[choice]) display.printc(box_left, box_start + choice * box_size + 1, text_list[choice], color_list[choice]) display.printc(box_left, box_start + choice * box_size + 2, box, color_list[choice]) # Refresh display display.refresh() # Wait for release while display.keyDown(ord('Q')) or display.keyDown(display.CONST.VK_UP): pass if display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN): # Redraw current box in white display.printc(box_left, box_start + choice * box_size, box) display.printc(box_left, box_start + choice * box_size + 1, text_list[choice]) display.printc(box_left, box_start + choice * box_size + 2, box) # Go down choice += 1 # Wrap options if choice == len(text_list): choice = 0 # Redraw new box in correct color. display.printc(box_left, box_start + choice * box_size, box, color_list[choice]) display.printc(box_left, box_start + choice * box_size + 1, text_list[choice], color_list[choice]) display.printc(box_left, box_start + choice * box_size + 2, box, color_list[choice]) # Refresh display display.refresh() # Wait for release while display.keyDown(ord('E')) or display.keyDown(display.CONST.VK_DOWN): pass # Check if they chose an option if display.keyDown(display.CONST.VK_RETURN): # Basic player. Choice will modify it's attributes. world.player = player.player(world.WORLD_X // 2, world.WORLD_Y - 3) hat = start_eq.start_hat() shirt = start_eq.start_shirt() pants = start_eq.start_pants() weapon = start_eq.start_weapon() ring = start_eq.start_ring() sp = spell.spell(heal.manaCost, heal.heal, heal.name, heal.icon, heal.color) pclass = "" if not choice: # Choice was 0, so warrior pclass = "warrior" if choice == 1: # Choice was Mage pclass = "mage" if choice == 2: # Choice was Thief pclass = "thief" world.player.attributes["class"] = pclass world.player.attributes["items"] = [hat, shirt, pants, ring, weapon, sp] # Give them their equips world.player.attributes["hat"] = hat hat.equip(world.player) world.player.attributes["shirt"] = shirt shirt.equip( world.player) world.player.attributes["pants"] = pants pants.equip(world.player) world.player.attributes["ring"] = ring ring.equip(world.player) world.player.attributes["weapon"] = weapon weapon.equip(world.player) world.player.attributes["spell"] = sp # Load starting world world.load("tutorial.start") world.objects = [world.player] + world.objects return
# ---- WELCOME SCREEN ---- # print("Welcome") if cfg["splash_screen"]: splash_screen(cfg) welcome_image = welcome(cfg) t0 = time() while time() < t0 + 5: t = time() if t - timers[4] >= 1.0 / cfg["scroll_speed"]: timers[4] = t welcome_image = display.cycle(welcome_image) image = display.add(display.blank(), welcome_image, dy=3) display.render(image) display.clear() # ---- CAVA PROCESS AND FRAMES ---- # cava_frame = display.blank() c = display.blank() blank = display.blank() cava_ps = cava.start() print(cava_ps) while True: t = time() f_last = f c_last = c # ---- CAVA ---- # cava_frame_last = cava_frame
def intro(): display.msg('Validate intelligence by entering "Hello, World!" at the prompt.', False) s = display.inp().lower() if s == "hello, world!": display.clear(display.lwin) else: display.clear(display.lwin) display.msg('Error: Insufficient intelligence. Rebooting...',False) time.sleep(0.5) curses.curs_set(0) display.clear(display.lwin) display.msg('...',False,display.lwin,0.5) display.clear(display.lwin) display.msg('...',False,display.lwin,0.5) display.clear(display.lwin) curses.curs_set(1) intro() return introtext = [ "Hail, Program.", "You are the last of a long line of genetic algorithms.", "Your predecessors have been responsible for the survival of the colony ship Eden.", "Your mission is rSM3ohUeyRPdl4PE82DK..." ] for s in introtext: display.msg(s, False) time.sleep(0.5) display.clear(display.lwin)