欢迎访问宙启技术站
智能推送

使用urwid和Python创建交互式终端游戏

发布时间:2024-01-14 08:40:08

urwid是一个Python库,用于创建终端用户界面(TUI)。它提供了一组简单但功能强大的小部件,可以用于构建交互式终端应用程序,包括终端游戏。在本文中,我们将使用urwid创建一个简单的井字棋游戏作为示例。

首先,我们需要安装urwid库。可以通过运行以下命令来安装urwid:

pip install urwid

接下来,我们将编写一个井字棋游戏的代码。以下是一个使用urwid实现的简单井字棋游戏的示例:

import urwid

# 游戏逻辑
class TicTacToeGame:
    def __init__(self):
        self.board = [' '] * 9
        self.current_player = 'X'

    def make_move(self, position):
        if self.board[position] == ' ':
            self.board[position] = self.current_player
            self.current_player = 'O' if self.current_player == 'X' else 'X'

    def check_winner(self):
        winning_patterns = (
            [0, 1, 2], [3, 4, 5], [6, 7, 8],  # 横向
            [0, 3, 6], [1, 4, 7], [2, 5, 8],  # 纵向
            [0, 4, 8], [2, 4, 6]  # 对角线
        )

        for pattern in winning_patterns:
            if self.board[pattern[0]] == self.board[pattern[1]] == self.board[pattern[2]] != ' ':
                return self.board[pattern[0]]

        if ' ' not in self.board:
            return 'Tie'

        return None

# 游戏界面
class TicTacToeUI:
    def __init__(self):
        self.game = TicTacToeGame()

        self.title_text = urwid.Text('Tic Tac Toe')
        self.instructions_text = urwid.Text('Player X: Make your move.')

        self.board_buttons = []
        for i in range(9):
            button = urwid.Button(' ')
            urwid.connect_signal(button, 'click', self.handle_button_click, i)
            self.board_buttons.append(button)

        self.restart_button = urwid.Button('Restart')
        urwid.connect_signal(self.restart_button, 'click', self.restart_game)

        self.widgets = [
            urwid.Padding(self.title_text, align='center', width=('relative', 100)),
            urwid.Padding(self.instructions_text, align='center', width=('relative', 100)),
            urwid.GridFlow(self.board_buttons, 3, 3, 1, 'center'),
            urwid.Padding(self.restart_button, align='center', width=('relative', 100))
        ]

        self.ui = urwid.Pile(self.widgets)

    def handle_button_click(self, button, position):
        if self.game.check_winner() is None:
            self.game.make_move(position)
            button.set_label(self.game.board[position])

            winner = self.game.check_winner()
            if winner is not None:
                if winner == 'Tie':
                    self.instructions_text.set_text('It\'s a tie!')
                else:
                    self.instructions_text.set_text(f'Player {winner} wins!')
            else:
                current_player = 'X' if self.game.current_player == 'O' else 'O'
                self.instructions_text.set_text(f'Player {current_player}: Make your move.')

    def restart_game(self, button):
        self.game = TicTacToeGame()
        self.instructions_text.set_text('Player X: Make your move.')
        for button in self.board_buttons:
            button.set_label(' ')

    def run(self):
        urwid.MainLoop(self.ui).run()

# 程序入口
if __name__ == '__main__':
    game_ui = TicTacToeUI()
    game_ui.run()

在这个示例中,我们定义了一个TicTacToeGame类来处理游戏的逻辑。它包括一个游戏板状态的列表,一个当前玩家的标记,以及处理游戏移动和检查胜利状态的方法。

接下来,我们定义了一个TicTacToeUI类来处理游戏的用户界面。它使用urwid小部件来创建一个标题,一条指示文本,一个网格布局的游戏板按钮以及一个重启按钮。我们通过连接按钮点击事件来处理用户的移动,并在按钮上显示对应的玩家标记。我们还更新指示文本以反映当前玩家和游戏结果。

最后,在程序的主入口中,我们创建了一个TicTacToeUI实例并运行它的run方法来启动游戏。

要运行该脚本,请保存为tictactoe.py并在终端中运行python tictactoe.py

这只是一个简单的井字棋游戏示例,您可以根据自己的需求和喜好对其进行扩展和修改。urwid提供了许多其他小部件和布局选项,您可以使用它们来创建更复杂的终端应用程序和游戏。