コード例 #1
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def process_shooting(screen: curses.window, cur_player: Player, game: Game,
                     is_human: bool):
    """
    function for processing current player's shot
    """
    # shoot
    succ, hit = game.player_shoot()
    # if player chose an inappropriate cell, do nothing
    if not succ:
        game.turn -= 1
    else:
        screen.clear()

        message = "You missed" if is_human else "AI missed"
        if hit:
            message = "You hit enemy ship" if is_human else "AI hit enemy ship"
            game.check_victory()
            game.turn -= 1

        # printing the result of the shot to the screen
        if is_human:
            print_to_center(screen, [message])
        else:
            y_shot = cur_player.enemy_field.y_cur
            x_shot = cur_player.enemy_field.x_cur
            print_to_center(screen,
                            [f"AI has shot to {y_shot} {x_shot}", message])

        screen.refresh()
        screen.getch()

    screen.refresh()
コード例 #2
0
ファイル: state.py プロジェクト: nickgashkov/jocus
    def render(self, window: curses.window) -> None:
        window.clear()

        for coin in self.coins:
            window.addstr(coin.x, coin.y, "o")

        window.addstr(self.player.x, self.player.y, "*")
コード例 #3
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def start_game(screen: curses.window, mheight: int, mwidth: int) -> None:
    """
    function for starting a new game
    mheight: map height
    mwidth: map width
    """
    # reading player's name
    screen.clear()
    print_to_center(screen, ['Enter your name: '])
    screen.refresh()
    curses.curs_set(1)
    curses.echo()
    name = screen.getstr().decode("utf-8")
    curses.curs_set(0)
    curses.noecho()

    screen.clear()
    print_to_center(screen, ['Preparing the game...'])
    screen.refresh()

    # initializing a new game
    game = Game(mheight, mwidth)
    # making necessary preparations
    game.prepare_game(player_name=name)
    # playing the game
    play_game(screen=screen, game=game)
コード例 #4
0
ファイル: danmu.py プロジェクト: NaviHX/pytools
def input_thread(inputw: curses.window, roomid: str):
    while True:
        msg = inputw.getstr()
        inputw.clear()

        # send msg
        send_danmu(roomid=roomid, msg=msg)
コード例 #5
0
ファイル: extra1.py プロジェクト: TeunKoenders/aoc2020
def curses_program(screen: curses.window):
    y, x = screen.getmaxyx()
    o = Ocean(x - 1, y - 1)
    screen.clear()
    curses.resizeterm(y, x)

    for instruct in data:
        screen.clear()
        curr_north, curr_east = c.north, c.east
        c.execute_instruction(instruct)
        new_north, new_east = c.north, c.east

        if new_north < curr_north:
            for i in range(abs(curr_north - new_north)):
                o.move_ocean_south()
                o.draw(screen)
        else:
            for i in range(abs(curr_north - new_north)):
                o.move_ocean_north()
                o.draw(screen)

        if new_east < curr_east:
            for i in range(abs(curr_east - new_east)):
                o.move_ocean_west()
                o.draw(screen)
        else:
            for i in range(abs(curr_east - new_east)):
                o.move_ocean_east()
                o.draw(screen)
コード例 #6
0
def main(stdscr: curses.window):
    stdscr.clear()

    curses_utils = CursesUtils(stdscr)
    curses_utils.draw_start_screen()

    board = Board(height=20, width=10)
    GameLoop(board, curses_utils, tick_frequency=0.5).run()
コード例 #7
0
ファイル: game.py プロジェクト: nickgashkov/jocus
def render_welcome_screen(window: curses.window) -> None:
    window.clear()

    window.addstr(0, 10, "jocus 0.0.1")
    window.addstr(1, 10, "collect coins and you win")
    window.addstr(3, 10, "press any key to start...")

    window.refresh()
コード例 #8
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def declare_winner(screen: curses.window, game: Game):
    """
    function for printing the winner to the screen
    """
    screen.clear()
    message = f'Congrats! Player {game.winner} has won!'
    print_to_center(screen, [message])
    screen.refresh()
    screen.getch()
コード例 #9
0
ファイル: battleship.py プロジェクト: edyapups/battleship
def main(screen: curses.window, height, width):
    game: Optional[Game] = None
    curses.curs_set(0)
    while True:
        display_string_builder: list[str, ...] = list()
        display_string_builder.append('###########################')
        display_string_builder.append('#  WELCOME TO BATTLESHIP  #')
        display_string_builder.append('###########################')
        display_string_builder.append('')

        if game and game.winner:
            display_string_builder.append(
                f'The winner of the last game is {game.winner}!')
            display_string_builder.append('')

        display_string_builder.append('Press n to start new game.')
        display_string_builder.append('Press l to load the game (if exists).')
        display_string_builder.append('Press q to quit the game.')

        screen.clear()
        check_text_size(display_string_builder, *screen.getmaxyx())
        display_string = '\n'.join(display_string_builder)
        screen.addstr(0, 0, display_string)

        input_character = screen.getch()

        if input_character == ord('q'):
            return

        if input_character in (ord('n'), ord('l')):
            if input_character == ord('l'):
                try:
                    with open(SAVE_FILE_NAME, 'rb') as file:
                        game = pickle.load(file)
                except OSError:
                    continue
            else:
                first_player = HumanPlayer('You')
                second_player = RandomPlayer('Robot')
                game = Game(first_player=first_player,
                            second_player=second_player,
                            board_size=(height, width))
            try:
                game.play(screen)
            except QuitSignal as qs:
                if qs.signal_type == QuitSignal.BACK_TO_MAIN_MENU:
                    continue
                if qs.signal_type == QuitSignal.QUIT:
                    return
                if qs.signal_type == QuitSignal.QUIT_AND_SAVE:
                    with open(SAVE_FILE_NAME, 'wb') as file:
                        pickle.dump(game, file, pickle.HIGHEST_PROTOCOL)
                        return
コード例 #10
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def display_game(screen: curses.window, cur_player: Player, game: Game):
    """
    function for printing game on the console
    """
    # obtain coordinates for displaying fields
    sheight, swidth = screen.getmaxyx()
    my_coords, enemy_coords = game.display_field(sheight=sheight,
                                                 swidth=swidth)

    # print fields and stats on the console
    screen.clear()
    display_field(screen, my_coords, cur_player, True, game=game)
    display_field(screen, enemy_coords, cur_player, False, game=game)
    stats = game.num_alive_ships()
    display_stats(screen=screen, statistics=stats[0], my=True, game=game)
    display_stats(screen=screen, statistics=stats[1], my=False, game=game)
コード例 #11
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def main(screen: curses.window, mheight: int, mwidth: int):
    # removing cursor
    curses.curs_set(0)
    # setting color for menu
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)

    # things to be printed
    prev_game = load_game()

    str_start_game = "Start New Game"
    str_load_game = "Load Game"
    str_exit = "Exit"
    menu_items = [str_load_game, str_start_game, str_exit
                  ] if prev_game else [str_start_game, str_exit]

    cur_index = 0  # selected menu item
    display_menu(screen, menu_items, cur_index)

    while True:
        # listen to input
        key = screen.getch()

        # handling navigation
        if key == curses.KEY_UP and cur_index > 0:
            cur_index -= 1
        elif key == curses.KEY_DOWN and cur_index < len(menu_items) - 1:
            cur_index += 1
        # handling Enter button
        elif key == curses.KEY_ENTER or key in [10, 13]:
            cur_item = menu_items[cur_index]

            if cur_item == str_start_game:
                # adjust length of the symbols
                Field.recal_sybms(len(str(mwidth)))
                # start new game
                start_game(screen, mheight, mwidth)
            elif cur_item == str_load_game:
                # adjust length of the symbols
                Field.recal_sybms(len(str(prev_game.map_width)))
                # continue last saved game
                play_game(screen, game=prev_game)
            elif cur_item == str_exit:
                return

        screen.clear()
        display_menu(screen, menu_items, cur_index)
コード例 #12
0
ファイル: __main__.py プロジェクト: TooTiredOne/battleships
def process_human_move(screen: curses.window, cur_player: Player, game: Game):
    """
    function for listening to player's input and taking appropriate actions
    """
    buttons_move_cursor = [
        curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT,
        ord('w'),
        ord('s'),
        ord('a'),
        ord('d')
    ]

    buttons_shoot = [curses.KEY_ENTER, 10, 12, 13, 14]

    while True:
        # get fields
        my_field = cur_player.my_field
        enemy_field = cur_player.enemy_field

        display_game(screen, cur_player, game)

        # listen to the input
        key = screen.getch()
        # move corresponding cursors
        if key in buttons_move_cursor:
            move_cursor(key,
                        my_field=my_field,
                        enemy_field=enemy_field,
                        game=game)
        # shoot at the current location of the cursor
        elif key in buttons_shoot:
            process_shooting(screen, cur_player, game, is_human=True)
            break
        # save the game
        elif key == ord('o'):
            screen.clear()
            save_game(game)
            print_to_center(screen, ['The game was saved'])
            screen.getch()
            game.turn -= 1
            break
コード例 #13
0
    def _main(stdscr: curses.window):
        maxy, maxx = 0, 0

        examples = []
        count = 1
        while 1:
            # Prompt
            maxy, maxx = stdscr.getmaxyx()
            stdscr.clear()

            stdscr.addstr(
                0, 0, "Enter example: (hit Ctrl-G to execute, Ctrl-C to exit)",
                curses.A_BOLD)
            editwin = curses.newwin(5, maxx - 4, 2, 2)
            rectangle(stdscr, 1, 1, 1 + 5 + 1, maxx - 2)

            # Printing is part of the prompt
            cur = 8

            def putstr(str, x=0, attr=0):
                nonlocal cur
                # This is how we handle going off the bottom of the scren lol
                if cur < maxy:
                    stdscr.addstr(cur, x, str, attr)
                    cur += (len(str.split("\n")) or 1)

            for ex, buff, vals, err in reversed(examples):
                putstr(f"Example {ex}:", attr=curses.A_BOLD)

                for l in buff.split("\n"):
                    putstr(f"    | {l}")

                putstr("")

                if err:
                    err = str(err)
                    err = err.split("\n")
                    putstr("  Error:")
                    for l in err:
                        putstr(f"    {l}", attr=curses.COLOR_YELLOW)

                elif vals:
                    putstr("  Value:")
                    for x, t in zip(range(1, 1 << 64), vals):
                        putstr(f" {x:>3}) " + repr(t))

                putstr("")

            stdscr.refresh()

            # Readf rom the user
            box = Textbox(editwin)
            try:
                box.edit()
            except KeyboardInterrupt:
                break

            buff = box.gather().strip()
            if not buff:
                continue

            vals, err = handle(buff, count)

            examples.append((count, buff, vals, err))

            count += 1
            stdscr.refresh()
コード例 #14
0
def main(s: curses.window, a: list[str], c: int, o: list[bool]):
    """Lists system specs"""
    s.clear()
    s.refresh()

    io.printw("System Specs:\n " + platform.uname().system + ", {}, {}, {}".format(platform.uname().processor, platform.uname().machine, platform.uname().version) )