def doWin(self): #self.stdscr.clear() self.stdscr.addstr(10, 24, "┌--------------------------------┐") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(12, 24, "| You win! |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(14, 24, "└--------------------------------┘") self.stdscr.refresh() curses.delay_output(1500) self.stdscr.addstr(12, 24, "| Score: {:,}".format(self.g.score)) self.stdscr.refresh() curses.delay_output(1500) self.stdscr.addstr(10, 24, "┌--------------------------------┐") self.stdscr.addstr(11, 24, "| Play again? |") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(13, 24, "| 'y' for yes, 'n' for no |") self.stdscr.addstr(14, 24, "└--------------------------------┘") self.stdscr.refresh() self.stdscr.nodelay(False) c = self.stdscr.getch() while c not in (ord('y'), ord('n')): c = self.stdscr.getch() if c == ord('y'): self.restart = True if not self.restart: raise ZeroDivisionError self.stdscr.nodelay(True)
def refreshAnimation(self): self.stdscr.clear() curses.delay_output(self.time) # change so updates in real time self.down_counter += 1 self.displayBoard() # score self.stdscr.addstr(20, 52, "lines completed: {0}".format(self.g.clearedLines)) self.stdscr.addstr(22, 42, "Type 'q' to quit or 'p' for pause.") self.stdscr.addstr(15, 52, "level: {0}".format(self.g.level)) self.stdscr.addstr(17, 48, "--------------------------") self.stdscr.addstr(18, 48, " Score {:,} ".format(self.g.score)) self.stdscr.addstr(19, 48, "--------------------------") # next piece box for i in range(len(self.nextPieceBoarder)): self.stdscr.addstr(i + 1, 49, self.nextPieceBoarder[i]) nextPieceLines = self.g.nextPieceToString() for i, line in enumerate(nextPieceLines): for j, ch in enumerate(line): if ch.isdigit(): color = int(ch) self.stdscr.addstr(i + 5, 56 + j, ch, curses.color_pair(color)) else: self.stdscr.addstr(i + 5, 56 + j, ch, self.boardColor) if self.g.clearedLines - self.level_constant*self.g.level >= 0: self.down_constant -= self.level_decrement self.g.level += 1 if self.g.level == 11: self.doWin()
def main(t): curses.curs_set(0) a, b = curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION) t.addstr(2, 0, f"a={a}, b={b}") pt = Point() curses.delay_output(100) mx, my = 0, 0 while True: # draw t.addstr(0, 0, f"x={mx}, y={my}") a, mx, my, _, mask = curses.getmouse() t.addstr(4, 0, f"x={pt.x}, y={pt.y}") # input windll.user32.GetCursorPos(byref(pt)) c = t.getch() if c == ord('q'): break if c == curses.KEY_MOUSE: t.addstr(1, 0, "MOUSE") a, mx, my, _, mask = curses.getmouse()
def init(self): self.window = curses.initscr() self.initted = True self.ymax, self.xmax = self.window.getmaxyx() terminfo = curses.longname() assert '256' in terminfo # your env TERM must be xterm-256color! assert curses.has_colors() curses.start_color() curses.use_default_colors() ctr = 1 for fg in CLRS: for bg in CLRS: if ctr <= curses.COLORS-1 and fg != bg: curses.init_pair(ctr, CLRS[fg], CLRS[bg]) pairs[(fg,bg)] = curses.color_pair(ctr) ctr += 1 curses.meta(1) curses.noecho() curses.cbreak() curses.curs_set(0) curses.delay_output(0) curses.mouseinterval(150) availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS) assert availmask != 0 # mouse must be available! self.window.leaveok(1) self.window.scrollok(0) self.window.keypad(1) if NONBLOCKING: self.window.nodelay(1) self.window.timeout(NONBLOCKING_TIMEOUT) else: self.window.nodelay(0) self.window.timeout(-1) self.window.refresh()
def main_loop(cd, args): """Endless loop until maximum failed defenses or non-comb death occurs.""" # S.attack_limit > len(S.attack) because we need only the minimum failed # defenses. S.message = ('Quit at any time with the ESC key.') cd.display_message(S.message) # Supply command-line arguments, if present. if args.repeat: counter = args.repeat else: counter = 0 # Endless loop. while (S.attack_limit > len(S.attack) and S.attack_limit > len(S.bystander)): if T.time_limit and T.time_to_display < 0: cd.end_game() else: # Somewhere in this cycle the number of bystanders left is wrong. T.update() curses.delay_output(10) cd.display_defense(S.defense) attack_defend_cycle(args) cd.display_message(S.message) cd.display_score(S.score, S.attack_limit-len(S.attack), S.attack_limit-len(S.bystander)) # cd.refresh() # this causes problems S.message = ('''Your player has been destroyed in battle. Game over.''') cd.display_message(S.message) cd.end_game()
def doMove(self): last_move = 0 shape_change = False for i in range(1000): # improves reactivity c = self.stdscr.getch() if c == curses.KEY_DOWN: # moves piece down faster self.down_counter = self.down_constant curses.delay_output(self.time) if not self.has_landed: self.has_landed = self.g.fallPiece() self.displayBoard() if self.has_landed: self.down_counter = 1 if c == curses.KEY_LEFT: # moves blocks to the left last_move = -1 elif c == curses.KEY_RIGHT: # moves piece to the right last_move = 1 elif not shape_change and c == curses.KEY_UP: # rotates piece self.g.rotatePiece() shape_change = True elif c == ord('m'): self.doMenu() elif c == ord('q'): self.doQuit() elif c == ord('p'): self.doPause() self.g.movePiece(last_move)
def _run(self,screen): '''function runs the whole programm, but it's used by curses wrapper''' screen.clear() self.init_colors() cs.curs_set(0) while True: screen.move(self.cursor_pos.y+self.cursor_pos.virtual_y,self.cursor_pos.x) self.print_action_line(screen) if not self.see_commands: if self.see_action_history: self.print_all_lines(screen,self.action_history) self.print_cursor(screen,self.action_history) else: self.print_all_lines(screen,self.lines) self.print_cursor(screen,self.lines) else: data = [] for key in Keys: string = f"{key} -> {Keys[key]}" data.append(string) self.print_all_lines(screen,data) self.print_cursor(screen,data) self.print_state_line(screen) self.process_key(screen) screen.refresh() cs.delay_output(50)
def do_win(self): self.stdscr.addstr(10, 24, "┌--------------------------------┐") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(12, 24, "| You win! |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(14, 24, "└--------------------------------┘") self.stdscr.refresh() curses.delay_output(1500) s = ("Moves made: {0}".format(self.num_moves)).center(32) self.stdscr.addstr(12, 24, "|" + s +"|") self.stdscr.refresh() curses.delay_output(1500) self.stdscr.addstr(9, 24, "┌--------------------------------┐") self.stdscr.addstr(10, 24, "| Play again? |") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(14, 24, "| 'y' for yes, 'n' for no |") self.stdscr.addstr(15, 24, "└--------------------------------┘") self.stdscr.refresh() c = self.stdscr.getch() while c not in (ord('y'), ord('n')): c = self.stdscr.getch() if c == ord('y'): self.restart = True if not self.restart: raise ZeroDivisionError
def monsters_add(self, win, lvl): if lvl == 0: win.addstr(27, 16, 'НЕ ЗАЖИМАЙТЕ КЛАВИШИ, УДАЧИ!') else: win.addstr(27, 16, 'NEXT LEVEL: LAST MONSTERS WENT HOME') if lvl % 3 == 2: win.addstr(27, 9, 'NEXT LEVEL: LAST DAMNED CAPITALISTS WENT HOME') win.addstr(self.level + 1, 0, ' ' * 60) curses.delay_output(1000) #time.sleep(1.5) def clear_output(): time.sleep(4) win.addstr(27, 0, ' ' * 60) t = threading.Thread(target=clear_output) t.start() self.stage = [[self.level, 29], [self.level, 30], [self.level, 31], [self.level, 32], [self.level, 33]] for i in range(self.win_borders[1])[14:-14]: for j in range(self.win_borders[0])[7:7 + self.col_monsters]: self.monsters.add((j, i)) win.addch(j, i, self.monster[lvl % 3])
def display_screen(self): self.stdscr.nodelay(1) self.stdscr.timeout(self.speed) while True: self.display_words() curses.delay_output(self.speed) key = self.stdscr.getch() if self.speed_up(key): self.speed -= 10 self.stdscr.timeout(self.speed) elif self.speed_down(key): self.speed += 10 self.stdscr.timeout(self.speed) elif self.increase_char_width(key): self.char_width += 1 elif self.decrease_char_width(key): self.char_width -= 1 elif self.move_backward(key): self.position -= 10 elif self.move_forward(key): self.position += 10 elif self.space(key): self.stdscr.nodelay(0) x = self.stdscr.getch() self.stdscr.nodelay(1) self.stdscr.timeout(self.speed) elif key == '\x1b': return if self.position + 1 == len(self.words): self.stdscr.clear() break
def _show(_i): x = int(size * _i / count) win.addstr("%s[%s%s] %i/%i\r" % (prefix, "#" * x, "." * (size - x), _i, count)) win.refresh() curses.delay_output(9999) win.clear()
def run(self) -> None: win = curses.initscr() curses.curs_set(0) limits = win.getmaxyx() if arguments.rows > limits[0] - 1 or arguments.cols > limits[1] - 1: raise ValueError( f'Невозможно отрисовать картинку такого размера. Максимальный размер {limits[0]}x{limits[1]}.' ) curses.noecho() win = curses.newwin(self.life.rows + 2, self.life.cols + 2, 0, 0) win.nodelay(True) running = True pause = False while running: if not self.life.is_changing or self.life.is_max_generations_exceeded: running = False char = win.getch() if char == ord(' '): pause = not pause if char == ord('s'): save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.life.save(Path(f"saves/life_{save_time}.txt")) if char == ord('q'): running = False if not pause: win.clear() curses.delay_output(50) self.draw_borders(win) self.draw_grid(win) self.life.step() win.refresh() curses.endwin()
def refreshAnimation(self): self.stdscr.clear() curses.delay_output(self.time) # change so updates in real time self.down_counter += 1 self.displayBoard() # score self.stdscr.addstr(20, 52, "lines completed: {0}".format(self.g.clearedLines)) self.stdscr.addstr(22, 42, "Type 'q' to quit, 'm' for menu,") self.stdscr.addstr(23, 52, "'p' to pause.") self.stdscr.addstr(15, 52, "level: {0}".format(self.g.level)) self.stdscr.addstr(17, 48, "--------------------------") self.stdscr.addstr(18, 48, " Score {:,} ".format(self.g.score)) self.stdscr.addstr(19, 48, "--------------------------") # next piece box for i in range(len(self.nextPieceBoarder)): self.stdscr.addstr(i + 1, 49, self.nextPieceBoarder[i]) nextPieceLines = self.g.nextPieceToString() for i, line in enumerate(nextPieceLines): for j, ch in enumerate(line): if ch.isdigit(): color = int(ch) self.stdscr.addstr(i + 5, 56 + j, ch, curses.color_pair(color)) else: self.stdscr.addstr(i + 5, 56 + j, ch, self.boardColor) if self.g.clearedLines - self.level_constant*self.g.level >= 0: self.down_constant -= self.level_decrement self.g.level += 1 if self.g.level == 11: self.doWin()
def do_win(self): self.stdscr.addstr(10, 24, "┌--------------------------------┐") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(12, 24, "| You win! |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(14, 24, "└--------------------------------┘") self.stdscr.refresh() curses.delay_output(1500) s = ("Moves made: {0}".format(self.num_moves)).center(32) self.stdscr.addstr(12, 24, "|" + s + "|") self.stdscr.refresh() curses.delay_output(1500) self.stdscr.addstr(9, 24, "┌--------------------------------┐") self.stdscr.addstr(10, 24, "| Play again? |") self.stdscr.addstr(11, 24, "| |") self.stdscr.addstr(13, 24, "| |") self.stdscr.addstr(14, 24, "| 'y' for yes, 'n' for no |") self.stdscr.addstr(15, 24, "└--------------------------------┘") self.stdscr.refresh() c = self.stdscr.getch() while c not in (ord('y'), ord('n')): c = self.stdscr.getch() if c == ord('y'): self.restart = True if not self.restart: raise ZeroDivisionError
def ai_refresh(self): self.refresh_screen() self.print_speed() self.print_direction() if not self.ai_paused: self.stdscr.addstr( 21, 5, " Press 'm' for menu, 'p' to pause, 'up'/'down' to incr/decr speed" ) else: self.stdscr.addstr( 21, 5, " Press 'left' to go back one step, and 'right' to go forward" ) self.stdscr.addstr( 22, 5, " 'p' to unpause/continue, and 'm' to access the menu. " ) self.stdscr.refresh() i = 0 while i < self.wait_time: if not self.ai_paused: self.handle_inputs() curses.delay_output(10) i += 1
def doMove(self): last_move = 0 shape_change = False for i in range(1000): # improves reactivity c = self.stdscr.getch() if c == curses.KEY_DOWN: # moves piece down faster self.down_counter = self.down_constant curses.delay_output(self.time) if not self.has_landed: self.has_landed = self.g.fallPiece() self.displayBoard() if self.has_landed: self.down_counter = 1 if c == curses.KEY_LEFT: # moves blocks to the left last_move = -1 elif c == curses.KEY_RIGHT: # moves piece to the right last_move = 1 elif not shape_change and c == curses.KEY_UP: # rotates piece self.g.rotatePiece() shape_change = True elif c == ord('p'): self.doPause() elif c == ord(' '): # if spacebar, immediately drop to bottom self.g.dropPiece() self.has_landed = True break elif c == ord('q'): self.doQuit() self.down_counter = 1 self.g.movePiece(last_move)
def run(self) -> None: screen = curses.initscr() screen = curses.newwin(self.life.rows + 2, self.life.cols + 2, 0, 0) curses.noecho() screen.nodelay(True) curses.curs_set(0) running = True is_paused = False while running: if (self.life.is_changing == False or self.life.is_max_generations_exceeded == True): running = False button = screen.getch() if button == ord("q"): running = False elif button == ord(" "): is_paused = True if not is_paused else False elif button == ord("s"): self.life.save(Path("save.txt")) if is_paused == False: curses.delay_output(30) self.draw_grid(screen) self.life.step() self.draw_borders(screen) curses.endwin()
def main_loop(cd): """Endless loop until maximum failed defenses or non-comb death occurs.""" # S.attack_limit > len(S.attack) because we need only the minimum failed # defenses. while (S.attack_limit >= len(S.attack) and S.attack_limit >= len(S.noncombatant)): if T.time_limit and T.time_to_display < 0: cd.end_game() else: # Somewhere in this cycle the number of noncombatants left is wrong. T.update() curses.delay_output(10) cd.display_defense(S.defense) attack_defend_cycle(cd) cd.display_message(S.message) cd.display_score(S.score, S.level, T.time_to_display_str, S.attack_limit-len(S.attack), S.attack_limit-len(S.noncombatant)) cd.refresh() S.message = ('''Your player has been destroyed in battle. ''' '''Game over; ctrl-c to close window.''') cd.display_message(S.message) # curses.delay_output(4000) cd.stdscr.noutrefresh() curses.doupdate() while True: pass
def do_welcome(self): """ Handles welcome screen """ self.stdscr.nodelay(True) self.stdscr.addstr(0, 0, welcome_message[0]) start = False blink_counter = 1 blink = True animate_counter = 0 refresh_counter = 10 while (not start): c = self.stdscr.getch() for i in range(10000): c = self.stdscr.getch() if c != -1: start = True break if refresh_counter == 10: refresh_counter = 1 if animate_counter == len(welcome_message): animate_counter = 0 self.stdscr.addstr(0, 10, welcome_message[animate_counter]) animate_counter += 1 if blink: self.stdscr.addstr(18, 22, " ") else: self.stdscr.addstr(18, 25, " Press ANY key to start! ") blink = not blink blink_counter = 0 refresh_counter += 1 self.stdscr.addstr(23, 0, "v{0} Eric Pai ©2014".format(self.version)) curses.delay_output(5) blink_counter += 1 self.stdscr.refresh() self.stdscr.nodelay(False)
def main_loop(cd): """Endless loop until maximum failed defenses or non-comb death occurs.""" # S.attack_limit > len(S.attack) because we need only the minimum failed # defenses. while (S.attack_limit > len(S.attack) and S.attack_limit > len(S.noncombatant) - 1): if T.time_limit and T.time_to_display < 0: cd.end_game() else: T.update() curses.delay_output(10) cd.display_defense(S.defense) attack_defend_cycle(cd) cd.display_score(S.score, T.time_to_display_str, S.attack_limit-len(S.attack), S.attack_limit-len(S.noncombatant)+1) cd.display_message(S.message) S.message = ('''Your player has been destroyed in battle. ''' '''Game over; ctrl-c to close window.''' + ' ' + str(S.attack_limit) + ' ' + str(len(S.noncombatant))) cd.display_message(S.message) cd.stdscr.noutrefresh() curses.doupdate() while True: pass
def highlight_failure(self, object, y, x, length): """Reverse item and turn it the color of an attack. Intended for use with failed attacks or non-combatants hit.""" for color in self.fade_colors['fade in and reverse']: object.chgat( y, x, length, curses.A_REVERSE | curses.color_pair(color)) self.refresh() curses.delay_output(40)
def main_loop(cd): while cd.S.damage > 0: curses.delay_output(10) cd.display_score() cd.display_message() cd.display_defense() attack_defend_cycle(cd) if cd.S.damage <= 0: cd.S.message = 'Your player has been destroyed in battle. Game over.'
def fade_out(self, object, y, x, length): """Make item fade out gradually. Intended for use with defeated attack strings. """ for color in self.fade_colors[object]: object.chgat(y, x, length, curses.color_pair(color)) self.refresh() curses.delay_output(40)
def part2(prog, memory=2 ** 8): prog[0] = 2 state = State(prog + [0] * memory, 0, 0, None, None) score = 0 board_state = defaultdict(int) output = [] ball = None paddle = None stdscr = curses.initscr() curses.delay_output(100) curses.noecho() curses.cbreak() while True: state = run(state) if state is None: break else: output.append(state.output) if len(output) == 3: x, y, tid = output ## Check for score and update screen if x == -1: score = tid else: board_state[(x, y)] = tid update(stdscr, x, y, tid, score) ## Check for ball or paddle if tid == 4: ball = (x, y) elif tid == 3: paddle = (x, y) if ball is not None and paddle is not None: move = next_move(ball, paddle) else: move = None ## Clear output and update state output = [] state = State(state.prog, state.loc, state.rel_base, [move], None) else: pass curses.echo() curses.nocbreak() curses.endwin() return board_state, score
def print_hand(hand, window, first_card_hidden=False): x = 0 for i in range(len(hand)): if i == 0 and first_card_hidden: print_card_rear(window, 0, x) else: print_card(hand[i], window, 0, x) x += 3 curses.delay_output(delay) window.refresh()
def run(self): event = 0 self.screen.nodelay(True) while True: self.screen.erase() self.handle(event) self.update() self.screen.refresh() curses.delay_output(20) event = self.screen.getch()
def getTarget( ): #Move the snake to eat the food according the path discovered by bfs() global count if bfs(FOOD, snake) == True: while (snake[0].getX() == targetx and snake[0].getY() == targety) == False: if bfs( FOOD, snake ) == True: #After each step do bfs again so that the snake can find the best path if recon( ) == True: #Before movement, it first sends out a virtual snake to see if this path is safe. for part in range(0, len(snake)): if part == 0: #Move the snake head based on the child node in bfsmap previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX( bfsmap[previousY][previousX].getChildX()) snake[part].setY( bfsmap[previousY][previousX].getChildY()) elif part == 1: previous = bodyMove( previousX, previousY, part, snake ) #Move the snake part to the position which used to be occupied by the part in front of it else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) if targetx == snake[0].getX() and targety == snake[0].getY( ): #Eat the food and extend the snake body snake[len(snake) - 1].setBodypart("+") snake.append(Body(previous[0], previous[1])) snake[len(snake) - 1].setBodypart("X") count += 1 matrix[targety][targetx].setBodypart( " " ) #delete the food in the matrix, so that the snake can discover the newly produced food myscreen.addstr(0, 12, str(count)) myscreen.addstr(previous[1], previous[0], Body.getTailpart(), curses.color_pair(1)) else: myscreen.addstr(previous[1], previous[0], " ") myscreen.refresh() curses.delay_output(100) else: #if the path is not safe, just chase its tails and go to eat the food when the path is safe getTail() break #break otherwise it might chase its tail forever after eating the food else: #if it can't see the food, just chase its tails and go to eat the food when the path is safe getTail() break else: #if it can't see the food, just chase its tails and go to eat the food when the path is safe getTail()
def main_loop(w): while w.S.damage > 0: # Different subwindows: scores, main window, messages, defense-strings. # Add code only to update every second or on change. curses.delay_output(25) w.display_score() w.display_message() w.display_defense() attack_defend_cycle(w) if w.S.damage <= 0: w.message = 'Your player has been destroyed in battle. Game over.'
def render_progress_bar(self, rg=random.randrange(0, 200, 10)): win = curses.newwin(20, 100, 0, 0) win.refresh() pb = progressBar(0, 100, 80) for i in range(100): pb.updateAmount(i) # win.clear() win.addstr(pb.progBar) win.refresh() curses.curs_set(0) win.move(0, 0) for i in range(rg): curses.delay_output(9999) win.clear()
def draw_life(self, screen, delay: int = 500) -> None: screen.clear() try: self.draw_borders(screen) self.draw_grid(screen) self.draw_borders(screen) self.draw_text(screen) except curses.error: raise ValueError( "The window is too small for the grid of this size") screen.refresh() curses.delay_output(delay)
def ai_refresh(self): self.refresh_screen() self.print_speed() self.print_direction() if not self.ai_paused: self.stdscr.addstr(21, 5, " Press 'm' for menu, 'p' to pause, 'up'/'down' to incr/decr speed") else: self.stdscr.addstr(21, 5, " Press 'left' to go back one step, and 'right' to go forward") self.stdscr.addstr(22, 5, " 'p' to unpause/continue, and 'm' to access the menu. ") self.stdscr.refresh() i = 0 while i < self.wait_time: if not self.ai_paused: self.handle_inputs() curses.delay_output(10) i += 1
def do_shake_method(self): """ 'Shakes' the top piece. Provides visual feedback when the user makes an error. """ if self.curr_disk is not None: disk = self.curr_disk.to_lines(self.g.num_disks, True, self.g.numbers) for i in range(len(disk)): self.stdscr.addstr(i+2, self.g.curr_pole * 27, disk[i].center(24)) self.stdscr.refresh() curses.delay_output(25) for i in range(len(disk)): self.stdscr.addstr(i+2, self.g.curr_pole * 27 + 2, disk[i].center(24)) self.stdscr.refresh() curses.delay_output(25) for i in range(len(disk)): self.stdscr.addstr(i+2, self.g.curr_pole * 27 + 1, disk[i].center(24)) self.do_shake = False
def main(stdscr): curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(10, curses.COLOR_RED, curses.COLOR_WHITE) stdscr.nodelay(False) stdscr.leaveok(True) stdscr.clear() stdscr.refresh() curses.delay_output(1) key_buffer = [] y, x = stdscr.getmaxyx() grid = Grid(stdscr, y - 20, x - 20, 10, 10, test_dict()) while True: try: try: key = stdscr.getkey() except: key = None if key == '\n': handle_user_input(stdscr, ''.join(key_buffer)) key_buffer = [] continue if key == 'q': break y, x = stdscr.getmaxyx() grid.update( y - 20, x - 20, key) if key is not None: key_buffer.append(key) else: sleep(0.1) except KeyboardInterrupt: pass
def show(self, target="player"): p0, p1, p2 = self.dominant_cnt if self.visible: field = "" p1c, p2c = 0, 0 for i in range(self.R): line = "".join([("_", "o", "x")[self.players[i][j]] for j in range(self.C)]) p1c += line.count("o") p2c += line.count("x") field += ";%s¥n" % line msg = "Step: %d | %s [o]: %d (%d) | %s [x]: %d (%d) | entropy: %.5f" % ( self.step, self.names[0], p1, p1c, self.names[1], p2, p2c, self.entropy) self.messages.append(field + msg) self.stdscr.addstr(1, 3, msg) self.stdscr.refresh() for i in range(self.R): for j in range(self.C): if target == "player": self.pad.addstr( i + 1, j + 1, (" ", "o", "x")[self.players[i][j]], curses.color_pair(self.players[i][j] + 1)) if target == "dominant": self.pad.addstr( i + 1, j + 1, (" ", "o", "x")[self.dominant_players[i][j]], curses.color_pair(self.players[i][j] + 1)) elif target == "count": self.pad.addstr( i + 1, j + 1, ("%d" % self.cnt[i][j] if self.cnt[i][j] else " "), curses.color_pair(self.dominant_players[i][j] + 1)) self.pad.refresh(self.pminrow, self.pmincol, self.sminrow, self.smincol, self.smaxrow, self.smaxcol) curses.delay_output(self.wait_time) else: p1c, p2c = 0, 0 for i in range(self.R): line = "".join([("_", "o", "x")[self.players[i][j]] for j in range(self.C)]) p1c += line.count("o") p2c += line.count("x") print ";%s" % line print "Step: %d | %s [o]: %d (%d) | %s [x]: %d (%d) | entropy: %.5f" % ( self.step, self.names[0], p1, p1c, self.names[1], p2, p2c, self.entropy)
def main(stdscr): i = 0 limit = 100 progress = ProgressBar(stdscr) stdscr.nodelay(True) while stdscr.getch() == -1 and i <= limit: stdscr.clear() # Clear screen stdscr.addstr(f'{i} New line. Window size(w = {stdscr.getmaxyx()[1]}, ' f'h = {stdscr.getmaxyx()[0]})') stdscr.refresh() progress.refresh(i / limit) curses.delay_output(50) i += 1 stdscr.nodelay(False) stdscr.getch()
def bounce_fortune(stdscr): height, width = stdscr.getmaxyx() ypos, xpos = random.randrange(0, height - 1), random.randrange(0, width - 1) ydir, xdir = random.choice([-1, 1]), random.choice([-1, 1]) stdscr.nodelay(1) c = None fortune = get_fortune() for c in fortune: if ypos in {0, height - 1}: ydir *= -1 if xpos in {0, width - 1}: xdir *= -1 ypos += ydir xpos += xdir stdscr.addstr(ypos, xpos, c) curses.delay_output(50) stdscr.refresh()
def render_progress_bar_loc(self, y, x, rg=random.randrange(0, 200, 10)): """ DEFUNCT: Should render an array of independent progress bars. """ winlist = [] for i in range(10): winlist.append(curses.newwin(20, 100, i, x)) winlist[-1].refresh for win in winlist: pb = progressBar(0, 100, 80) pb.updateAmount(i) # win.clear() win.addstr(pb.progBar) win.refresh() curses.curs_set(0) win.move(0, 0) for i in range(rg): curses.delay_output(9999) win.clear()
def jugar(ventana1, matriz1): """ Genera los ciclos del juego de la vida segun los puntos ingresados y los siguientes que se van generando .""" curses.noecho() ventana1.nodelay(True) ventana1.refresh() while (ventana1.getch() != ord('q')): matriz2 = calcular(matriz1) for fila in range (1, 26): for columna in range (1, 26): if matriz2[fila][columna] == 'X': ventana1.addstr(fila, columna, 'X') else: ventana1.addstr(fila, columna, " ") ventana1.refresh() curses.delay_output(400) matriz1 = matriz2 curses.endwin() imprimir_matriz(matriz1) #Imprime la ultima matriz que se generó
def do_shake_method(self): """ 'Shakes' the top piece. Provides visual feedback when the user makes an error. """ if self.curr_disk is not None: disk = self.curr_disk.to_lines(self.g.num_disks, True, self.g.numbers) for i in range(len(disk)): self.stdscr.addstr(i + 2, self.g.curr_pole * 27, disk[i].center(24)) self.stdscr.refresh() curses.delay_output(25) for i in range(len(disk)): self.stdscr.addstr(i + 2, self.g.curr_pole * 27 + 2, disk[i].center(24)) self.stdscr.refresh() curses.delay_output(25) for i in range(len(disk)): self.stdscr.addstr(i + 2, self.g.curr_pole * 27 + 1, disk[i].center(24)) self.do_shake = False
def add(self, win, it, prefix="", size=60): curses.curs_set(0) # Set cursor invisibley count = len(it) def _show(_i): x = int(size * _i / count) win.addstr("%s[%s%s] %i/%i\r" % (prefix, "#" * x, "." * (size - x), _i, count)) win.refresh() curses.delay_output(9999) win.clear() _show(0) for i, item in enumerate(it): yield item _show(i + 1) win.addstr("\n") win.refresh() curses.delay_output(9999) win.clear() curses.curs_set(1)
def doWelcome(self): self.stdscr.addstr(0, 0, welcomeMessage[0]) start = False blink_counter = 1 blink = True animate_counter = 0 refresh_counter = 10 while (not start): c = self.stdscr.getch() for i in range(10000): c = self.stdscr.getch() if c != -1: start = True break if refresh_counter == 10: refresh_counter = 1 if animate_counter == len(welcomeMessage): animate_counter = 0 self.stdscr.addstr(0, 0, welcomeMessage[animate_counter]) animate_counter += 1 if blink: self.stdscr.addstr(14, 22, "┌--------------------------------┐") self.stdscr.addstr(15, 22, "| |") self.stdscr.addstr(16, 22, "| |") self.stdscr.addstr(17, 22, "| |") self.stdscr.addstr(18, 22, "└--------------------------------┘") else: self.stdscr.addstr(14, 22, "┌--------------------------------┐") self.stdscr.addstr(15, 22, "| |") self.stdscr.addstr(16, 22, "| Press ANY key to start! |") self.stdscr.addstr(17, 22, "| |") self.stdscr.addstr(18, 22, "└--------------------------------┘") blink = not blink blink_counter = 0 refresh_counter += 1 #self.stdscr.addstr(23, 70, "Eric Pai") self.stdscr.addstr(23, 0, "v{0} Eric Pai ©2014".format(self.version)) curses.delay_output(5) blink_counter += 1 self.stdscr.refresh()
def main(scrn): ch = CursesHandler(scrn.subwin(5,80, 19,0)) ch.setLevel(logging.INFO) logging.getLogger().addHandler(ch) logging.getLogger().setLevel(logging.DEBUG) logging.debug("debug") logging.info("info") logging.warning("warning") logging.error("error") logging.critical("critical") win = scrn.subwin(10,80, 0,0) for i in range(0,10): win.addstr(i,0, str(i)) win.refresh() curses.delay_output(250) logging.info("Now i = " + str(i)) win.getch()
def main_loop(w): while True: # Different subwindows: scores, main window, messages, defense-strings.. # Add code only to update every second or on change. curses.delay_output(25) w.display_score() w.display_message() w.display_defense() # Get next character in regex string. try: c = w.window.getch() if c == 127: w.defense = w.defense[:-1] # For checking other delete characters, use w.defense += str(c) else: w.defense += chr(c) except ValueError: pass # Append to regex string and try against attack and non-combatant # strings. Must display what we have in special window, so user seems # to be typing into window. pass
def top(): standard_screen = StdScreen() standard_screen.disable_cursor_and_key_echo() lc = LayoutCreator(standard_screen.MAX_WIDTH, standard_screen.MAX_HEIGHT) layouts = lc.create_layouts() containers = create_app_containers(layouts, lc.cgroup_names) # Thread to periodically fetch data # and update the view. data_updater = BackgroundThread( DataCollector().update_widget_data, REFRESH_INTERVAL, containers ) data_updater.start() # Prevents used from bombarding with # key events. delay_output(1000) current_hightlight = containers[0] # Wait forever until we receive containers[0].process_list_bar.set_highlight(True) # an exit key. try: while True: key = standard_screen.stdscr.getch() if key in EXIT_KEYS: break current_hightlight = dispatch_to_container(containers, current_hightlight, key) data_updater.stop() endwin() except Exception: raise
def getTarget(): #Move the snake to eat the food according the path discovered by bfs() global count if bfs(FOOD, snake) == True: while (snake[0].getX() == targetx and snake[0].getY() == targety) == False: if bfs(FOOD, snake) == True: #After each step do bfs again so that the snake can find the best path if recon() == True: #Before movement, it first sends out a virtual snake to see if this path is safe. for part in range(0, len(snake)): if part == 0: #Move the snake head based on the child node in bfsmap previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX(bfsmap[previousY][previousX].getChildX()) snake[part].setY(bfsmap[previousY][previousX].getChildY()) elif part == 1: previous = bodyMove(previousX, previousY, part, snake) #Move the snake part to the position which used to be occupied by the part in front of it else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) if targetx == snake[0].getX() and targety == snake[0].getY(): #Eat the food and extend the snake body snake[len(snake) - 1].setBodypart("+") snake.append(Body(previous[0], previous[1])) snake[len(snake) - 1].setBodypart("X") count += 1 matrix[targety][targetx].setBodypart(" ") #delete the food in the matrix, so that the snake can discover the newly produced food myscreen.addstr(0, 12, str(count)) myscreen.addstr(previous[1], previous[0], Body.getTailpart(), curses.color_pair(1)) else: myscreen.addstr(previous[1], previous[0], " ") myscreen.refresh() curses.delay_output(100) else: #if the path is not safe, just chase its tails and go to eat the food when the path is safe getTail() break #break otherwise it might chase its tail forever after eating the food else: #if it can't see the food, just chase its tails and go to eat the food when the path is safe getTail() break else: #if it can't see the food, just chase its tails and go to eat the food when the path is safe getTail()
def main_loop(cd): """Endless loop until maximum failed defenses or non-comb death occurs.""" # S.attack_limit > len(S.attack) because we need only the minimum failed # defenses. while (S.attack_limit > len(S.attack) and S.attack_limit > len(S.bystander)): if T.time_limit and T.time_to_display < 0: cd.end_game() else: # Somewhere in this cycle the number of bystanders left is wrong. T.update() curses.delay_output(10) cd.display_defense(S.defense) attack_defend_cycle() cd.display_message(S.message) cd.display_score(S.score, S.attack_limit-len(S.attack), S.attack_limit-len(S.bystander)) # cd.refresh() # this causes problems S.message = ('''Your player has been destroyed in battle. Game over.''') cd.display_message(S.message) # curses.delay_output(4000) cd.stdscr.noutrefresh() curses.doupdate()
def render(self, win, it, prefix="", size=60): """ Actually renders the progress bar in the specified curses window. """ curses.curs_set(0) # Set cursor invisibley count = len(it) def _show(_i): x = int(size * _i / count) win.addstr("%s[%s%s] %i/%i\r" % (prefix, "#" * x, "." * (size - x), _i, count)) win.refresh() curses.delay_output(9999) win.clear() _show(0) for i, item in enumerate(it): yield item _show(i + 1) win.addstr("\n") win.refresh() curses.delay_output(9999) win.clear() curses.curs_set(1)
def main(scr): """Run inside a curses wrapper.""" _curses.use_default_colors() _curses.noecho() _curses.cbreak() _curses.curs_set(0) _curses.delay_output(0) outprev = '' while True: out = '' fmt = "{0:30}{1}\n" for each in _pickle.load(sin): name, val = each name = '{0} {1} '.format(name[:29], '.' * (28 - len(name[:29]))) out += fmt.format(name, val) if out and out != outprev: scr.clear() try: scr.addstr(0, 0, out) except _curses.error: scr.addstr(0, 0, "Error: Output line too long?") outprev = out scr.refresh()
def play(contexts): """Play back a sequence of `contexts`.""" try: win = curses.initscr() curses.start_color() curses.use_default_colors() curses.noecho() for context in contexts: # transition effect if context.transition is not None: if isinstance(context.transition, int): for _ in xrange(context.transition): curses.flash() curses.delay_output(350) else: y, x = win.getmaxyx() for i in xrange(x): for j in xrange(y): if i != x-1 or j != y-1: win.addch(j, i, ord(context.transition)) win.refresh() curses.delay_output(7) # load next slide curses.delay_output(200) curses.curs_set(context.cursor) win.clear() context.prepare(win) # mainloop while 1: c = win.getch() try: context.process(win, c) except Exception: break # finished y, x = win.getmaxyx() outro = " Press ESC to exit presentation mode. " win.addnstr(y-1, max(0, x-len(outro)-1), outro, x-1, curses.A_REVERSE) while 1: c = win.getch() if c == 27: break except KeyboardInterrupt: pass finally: curses.reset_shell_mode() curses.endwin()
def getTail(): #direct the snake to chase its tail global wandermap tailX = snake[len(snake) - 1].getX() tailY = snake[len(snake) - 1].getY() tailAvailable = False getfood = False max = -1 maxAdj = -1 for i in range( 0, len(adjacency[snake[0].getY()][snake[0].getX()]) ): #Call bfsWander() to discover the path from an adjacent position to its tail and choose the one has the longest path, #so that the snake can move as long as possible to get better chance to discover the food package = bfsWander( adjacency[snake[0].getY()][snake[0].getX()][i].getX(), adjacency[snake[0].getY()][snake[0].getX()][i].getY(), tailX, tailY) if package[0] == True: tailAvailable = True if package[1] > max: max = package[1] maxAdj = i if tailAvailable == True: #When there is a path to its tail, chase it bfsWander(adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getX(), adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getY(), tailX, tailY) #establish the longest path wandermap[snake[0].getY()][snake[0].getX()].setParentX( adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getX() ) #establish path from snake head to its adjacent position wandermap[snake[0].getY()][snake[0].getX()].setParentY( adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getY()) for part in range( 0, len(snake)): #move snake head to its adjacent position if part == 0: previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX( adjacency[previousY][previousX][maxAdj].getX()) snake[part].setY( adjacency[previousY][previousX][maxAdj].getY()) elif part == 1: previous = bodyMove(previousX, previousY, part, snake) else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) myscreen.addstr(previous[1], previous[0], " ") while (snake[0].getX() == tailX and snake[0].getY() == tailY) == False: if bfs(FOOD, snake) == True and recon( ) == True: #When chasing the tail, if it finds a safe path to eat the food, go to eat it getTarget() getfood = True break #after ate the food, no longer chase its tail else: for part in range(0, len(snake)): if part == 0: previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX( wandermap[previousY][previousX].getParentX()) snake[part].setY( wandermap[previousY][previousX].getParentY()) elif part == 1: previous = bodyMove(previousX, previousY, part, snake) else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) myscreen.addstr(previous[1], previous[0], " ") myscreen.refresh() curses.delay_output(100) if snake[0].getX() == tailX and snake[0].getY() == tailY: break if bfs(FOOD, snake) == True and recon( ) == True and getfood == False: #When it gets to the original tail position and there is a safe path for the food, go to eat it. getTarget() elif getfood == False: #if the food has not been eaten and there is no safe path, continue to chase the tail getTail() else: print("can't see tail") myscreen.getch()
import curses,curses.panel,curses.ascii win=curses.initscr() curses.curs_set(0) curses.start_color() curses.init_pair(1,curses.COLOR_CYAN,curses.COLOR_WHITE) curses.init_pair(2,curses.COLOR_RED,curses.COLOR_WHITE) size=win.getmaxyx() win.bkgd(curses.color_pair(1)) win.keypad(1) win.nodelay(1) win.border('|','|','*','*','(',')','(',')') win.getch() win.addstr(size[0]/2-5,2," .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. ",curses.color_pair(2)) win.addstr(size[0]/2-4,2,"| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |",curses.color_pair(2)) win.addstr(size[0]/2-3,2,"| | ________ | || | _________ | || | _________ | || | _____ _____ | || | _______ | || | _________ | || | _______ | |",curses.color_pair(2)) win.addstr(size[0]/2-2,2,"| | |_ ___ `. | || | |_ ___ | | || | |_ ___ | | || ||_ _||_ _|| || | / ___ | | || | |_ ___ | | || | |_ __ \ | |",curses.color_pair(2)) win.addstr(size[0]/2-1,2,"| | | | `. \ | || | | |_ \_| | || | | |_ \_| | || | | | | | | || | | (__ \_| | || | | |_ \_| | || | | |__) | | |",curses.color_pair(2)) win.addstr(size[0]/2,2,"| | | | | | | || | | _| _ | || | | _| | || | | ' ' | | || | '.___`-. | || | | _| _ | || | | __ / | |",curses.color_pair(2)) win.addstr(size[0]/2+1,2,"| | _| |___.' / | || | _| |___/ | | || | _| |_ | || | \ `--' / | || | |`\____) | | || | _| |___/ | | || | _| | \ \_ | |",curses.color_pair(2)) win.addstr(size[0]/2+2,2,"| | |________.' | || | |_________| | || | |_____| | || | `.__.' | || | |_______.' | || | |_________| | || | |____| |___| | |",curses.color_pair(2)) win.addstr(size[0]/2+3,2,"| | | || | | || | | || | | || | | || | | || | | |",curses.color_pair(2)) win.addstr(size[0]/2+4,2,"| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |",curses.color_pair(2)) win.addstr(size[0]/2+5,2," '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' ",curses.color_pair(2)) win.refresh() win.clear() win.border('|','|','*','*','(',')','(',')') curses.delay_output(800) curses.endwin()
def run(key3,m): key=KEY_RIGHT pause=0 while key!=27: ovr=0 cnt=0 flag=4 self.win.addstr(0,18,' Codes collected : '+str(self.count)+' ') self.win.addstr(0,2,' Level : '+str(self.level)+' ') self.win.timeout(180-self.count*5-self.level*10) getkey = self.win.getch() if getkey!=27: if m==0: if getkey==-1: key=key else: key=getkey elif m==1: key=key3 m=0 else: key=getkey if key==KEY_RIGHT and pause==0: self.robot.insert(0,[self.robot[0][0]+1,self.robot[0][1]]) for j in range(0,self.r): self.win.addch(self.robot[1][1]-j,self.robot[1][0]-(self.r-1),' ') if self.win.inch(self.robot[0][1]-j,self.robot[0][0])==32: cnt=cnt+1 if cnt==self.r: ovr=1 else: ovr=0 cnt=0 elif key==KEY_LEFT and pause==0: self.robot.insert(0,[self.robot[0][0]-1,self.robot[0][1]]) for j in range(0,self.r): self.win.addch(self.robot[1][1]-j,self.robot[1][0],' ') if self.win.inch(self.robot[0][1]-j,self.robot[0][0]-(self.r-1))==32: cnt=cnt+1 if cnt==self.r: ovr=1 else: ovr=0 cnt=0 elif key==KEY_UP and pause==0: self.robot.insert(0,[self.robot[0][0],self.robot[0][1]-1]) for j in range(0,self.r): self.win.addch(self.robot[1][1],self.robot[1][0]-j,' ') if self.win.inch(self.robot[0][1]-(self.r-1),self.robot[0][0]-j)==32: cnt=cnt+1 if cnt==self.r: ovr=1 else: ovr=0 cnt=0 elif key==KEY_DOWN and pause==0: self.robot.insert(0,[self.robot[0][0],self.robot[0][1]+1]) for j in range(0,self.r): self.win.addch(self.robot[1][1]-(self.r-1),self.robot[1][0]-j,' ') if self.win.inch(self.robot[0][1],self.robot[0][0]-j)==32: cnt=cnt+1 if cnt==self.r: ovr=1 else: ovr=0 cnt=0 elif key==27: flag=2 break elif key==ord('p') or key==ord('P'): if pause==0: pause=1 key=KEY_RIGHT continue else: key=KEY_RIGHT pause=0 continue else: key=KEY_RIGHT if ovr==1 and pause==0: level11() elif ovr==0 and pause==0: if self.level==1: flag=level10() elif self.level==2: flag=level20() elif self.level==3: flag=level30(key) if flag==0 or flag==1 or flag==2 or flag==3: break endwin() F=40 #size of square field sx=0#starting x coordinate of field sy=0#starting y coordinate of field win = newwin(F,F,sy,sx) win.keypad(1) win.nodelay(1) win.border('|','|','-','-','+','+','+','+') if flag==0: win.addstr(15,15,'Bomb exploded.',color_pair(3)) win.addstr(17,9,'Unsuccesful in diffusing Bomb.') win.addstr(19,12,'Score : ' +str(self.count*10),color_pair(1)) if flag==1: win.addstr(15,15,'You Won.',color_pair(2)) win.addstr(17,12,'Score : ' +str(self.s),color_pair(1)) if flag==2: win.addstr(15,8,'You chose to quit the game.') win.addstr(17,12,'Score : '+str(self.count*10),color_pair(1)) if flag==3: win.addstr(15,15,'Game Over.',color_pair(3)) win.addstr(17,15,'Score : '+str(self.count*10),color_pair(1)) win.refresh() delay_output(200) endwin() return flag
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS - 1) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) # availmask indicates that mouse stuff not available. if availmask != 0: curses.mouseinterval(10) # just verify these don't cause errors m = curses.getmouse() curses.ungetmouse(*m)
win.nodelay(1) win.border('|','|','*','*','(',')','(',')') win.getch() for i in x: win.addstr(size[0]/2-9,size[1]/2-20," __________",curses.color_pair(2)) win.addstr(size[0]/2-8,size[1]/2-20," ______/ ________ \______",curses.color_pair(2)) win.addstr(size[0]/2-7,size[1]/2-20," _/ ____________ \_",curses.color_pair(2)) win.addstr(size[0]/2-6,size[1]/2-20," _/____________ ____________\_",curses.color_pair(2)) win.addstr(size[0]/2-5,size[1]/2-20," / ___________ \ / ___________ \ ",curses.color_pair(2)) win.addstr(size[0]/2-4,size[1]/2-20," / /XXXXXXXXXXX\ \/ /XXXXXXXXXXX\ \ ",curses.color_pair(2)) win.addstr(size[0]/2-3,size[1]/2-20," / /############/ \############\ \ ",curses.color_pair(2)) win.addstr(size[0]/2-2,size[1]/2-20," | \XXXXXXXXXXX/ _ _ \XXXXXXXXXXX/ |",curses.color_pair(2)) win.addstr(size[0]/2-1,size[1]/2-20,"__|\_____ ___ // \\\ ___ _____/|__",curses.color_pair(2)) win.addstr(size[0]/2,size[1]/2-20,"[_ \ \ X X / / _]",curses.color_pair(2)) win.addstr(size[0]/2+1,size[1]/2-20,"__| \ \ / / |__",curses.color_pair(2)) win.addstr(size[0]/2+2,size[1]/2-20,"[____ \ \ \ ____________ / / / ____]",curses.color_pair(2)) win.addstr(size[0]/2+3,size[1]/2-20," \ \ \ \/||.||.||.||.||\/ / / /",curses.color_pair(2)) win.addstr(size[0]/2+4,size[1]/2-20," \_ \ \ ||.||.||.||.|| / / _/",curses.color_pair(2)) win.addstr(size[0]/2+5,size[1]/2-20," \ \ ||.||.||.||.|| / /",curses.color_pair(2)) win.addstr(size[0]/2+6,size[1]/2-20," \_ ||_||_||_||_|| _/",curses.color_pair(2)) win.addstr(size[0]/2+7,size[1]/2-20," \ ........... /",curses.color_pair(2)) win.addstr(size[0]/2+8,size[1]/2-20," \________________/",curses.color_pair(2)) curses.beep() win.addstr(5, size[1]/2-len(b)/2,i,curses.A_BLINK | curses.color_pair(2)|curses.A_UNDERLINE|curses.A_BOLD) curses.delay_output(80) win.refresh() win.clear() win.border('|','|','*','*','(',')','(',')') curses.delay_output(1200) curses.endwin()
def getTail(): #direct the snake to chase its tail global wandermap tailX = snake[len(snake) - 1].getX() tailY = snake[len(snake) - 1].getY() tailAvailable = False getfood = False max = -1 maxAdj = -1 for i in range(0, len(adjacency[snake[0].getY()][snake[0].getX()])): #Call bfsWander() to discover the path from an adjacent position to its tail and choose the one has the longest path, #so that the snake can move as long as possible to get better chance to discover the food package = bfsWander(adjacency[snake[0].getY()][snake[0].getX()][i].getX(), adjacency[snake[0].getY()][snake[0].getX()][i].getY(), tailX, tailY) if package[0] == True: tailAvailable = True if package[1] > max: max = package[1] maxAdj = i if tailAvailable == True: #When there is a path to its tail, chase it bfsWander(adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getX(), adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getY(), tailX, tailY)#establish the longest path wandermap[snake[0].getY()][snake[0].getX()].setParentX(adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getX())#establish path from snake head to its adjacent position wandermap[snake[0].getY()][snake[0].getX()].setParentY(adjacency[snake[0].getY()][snake[0].getX()][maxAdj].getY()) for part in range(0, len(snake)): #move snake head to its adjacent position if part == 0: previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX(adjacency[previousY][previousX][maxAdj].getX()) snake[part].setY(adjacency[previousY][previousX][maxAdj].getY()) elif part == 1: previous = bodyMove(previousX, previousY, part, snake) else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) myscreen.addstr(previous[1], previous[0], " ") while (snake[0].getX() == tailX and snake[0].getY() == tailY) == False: if bfs(FOOD, snake) == True and recon() == True: #When chasing the tail, if it finds a safe path to eat the food, go to eat it getTarget() getfood = True break #after ate the food, no longer chase its tail else: for part in range(0, len(snake)): if part == 0: previousX = snake[part].getX() previousY = snake[part].getY() snake[part].setX(wandermap[previousY][previousX].getParentX()) snake[part].setY(wandermap[previousY][previousX].getParentY()) elif part == 1: previous = bodyMove(previousX, previousY, part, snake) else: previous = bodyMove(previous[0], previous[1], part, snake) myscreen.addstr(snake[part].getY(), snake[part].getX(), snake[part].getBodypart(), curses.color_pair(1)) myscreen.addstr(previous[1], previous[0], " ") myscreen.refresh() curses.delay_output(100) if snake[0].getX() == tailX and snake[0].getY() == tailY: break if bfs(FOOD, snake) == True and recon() == True and getfood == False: #When it gets to the original tail position and there is a safe path for the food, go to eat it. getTarget() elif getfood == False: #if the food has not been eaten and there is no safe path, continue to chase the tail getTail() else: print("can't see tail") myscreen.getch()
#