杰瑞科技汇

mushclient python

Of course! Using Python with MUSHclient is a powerful way to automate tasks, create complex triggers, aliases, and timers, and enhance your MUDding experience. The primary method for this is through the MUSHclient Python Plugin.

mushclient python-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from setup to advanced usage.


Prerequisites: Getting Python Ready

Before you start, you need to ensure your Python environment is correctly configured to work with MUSHclient.

A. Install Python

If you don't have it, download and install Python from python.org. Crucially, during installation, check the box that says "Add Python to PATH". This makes it much easier to run from the command line.

B. Install MUSHclient

If you haven't already, download and install MUSHclient from gammon.com.au.

mushclient python-图2
(图片来源网络,侵删)

C. Install the Python Plugin

  1. In MUSHclient, go to the File menu -> Plugin Manager.
  2. Click the Install button.
  3. Find and select the mcp.py plugin file. This file is usually located in your MUSHclient installation directory, often in a sub-folder like Plugins or worlds.
  4. Click Open. The plugin will be installed.

Your First Script: The World Object

The heart of MUSHclient's Python interface is the world object. This object gives you access to almost everything in MUSHclient: sending commands, managing triggers, handling input, etc.

Let's write a simple "Hello, World!" script to confirm everything is working.

A. Access the Script Editor

  1. In MUSHclient, go to the Tools menu -> Script Editor.
  2. Make sure the "Plugin" tab is selected.
  3. From the "Plugin" dropdown, select the Python plugin you just installed.

B. Write and Run the Script

Paste the following code into the editor:

# This is a simple comment in Python
# Get a reference to the MUSHclient world object
# The 'world' object is automatically provided by the plugin
my_world = world
# Use the Note method to display a message in the output window
# This is great for debugging.
my_world.Note("Hello from Python!")
# You can also send a command to the MUD
# my_world.Send("look")

To run this script:

mushclient python-图3
(图片来源网络,侵删)
  • Press the Run button (the green "play" icon) in the script editor toolbar.
  • You should see a new line appear in your main MUSHclient window that says: [00:00:00] Hello from Python!

Congratulations! You've successfully run your first Python script in MUSHclient.


Core Concepts: Triggers, Aliases, and Timers

These are the three fundamental building blocks of MUSHclient automation. Here's how to create them with Python.

A. Triggers: Automated Responses to MUD Output

A trigger fires when text from the MUD matches a specific pattern.

Example: A trigger to automatically pick up gold when it appears.

# In the Script Editor
def OnPluginInstall():
  # This function runs when the plugin is loaded
  world.Note("Installing my gold pickup trigger.")
  # world.AddTrigger(pattern, script, [enabled], [keep_evaluating], [group], [sequence])
  # pattern: A regular expression to match.
  # script: The name of the function to run when triggered.
  world.AddTrigger("You see (\d+) gold coins here.", "PickupGold", True, True)
def PickupGold(name, line, wildcards):
  # This is the function that runs when the trigger matches.
  # 'wildcards' is a list of strings captured by the parentheses in the regex.
  # wildcards[0] will contain the number of gold coins.
  gold_amount = wildcards[0]
  world.Note(f"Picking up {gold_amount} gold coins.")
  world.Send(f"get {gold_amount} gold")
# Don't forget to call the install function when the script starts
OnPluginInstall()

B. Aliases: Custom Commands

An alias lets you replace a short command with a longer one or a complex script.

Example: An alias to quickly check your character's stats.

# In the Script Editor
def OnPluginInstall():
  world.Note("Installing my 'stats' alias.")
  # world.AddAlias(name, script, [prompt], [enabled], [keep_evaluating], [group])
  world.AddAlias("stats", "DoStats", True)
def DoStats(name, line, wildcards):
  # 'line' contains the full command you typed.
  # 'wildcards' contains any parts captured by parentheses in the alias pattern.
  world.Note("Executing stats command.")
  world.Send("score")
  world.Send("inventory")
OnPluginInstall()

Now, if you type stats and press Enter, it will automatically send score and inventory to the MUD.

C. Timers: Scheduled Actions

A timer runs a script after a specified number of seconds.

Example: A timer to remind you to drink a potion every 5 minutes.

# In the Script Editor
def OnPluginInstall():
  world.Note("Installing my potion timer.")
  # world.AddTimer(name, seconds, script, [one_shot], [enabled])
  # one_shot = True means it runs once and is deleted.
  # one_shot = False means it repeats.
  world.AddTimer("potion_reminder", 300, "DrinkPotion", False, True)
def DrinkPotion(name, line, wildcards):
  world.Note("5 minutes are up! Drinking potion.")
  world.Send("drink potion")
OnPluginInstall()

The World Object: A Handy Reference

Here are some of the most useful methods of the world object.

Method Description Example
world.Send(text) Sends text to the MUD as if you typed it. world.Send("north")
world.Note(text) Displays a message in the main output window. Great for debugging. world.Note("Script started.")
world.Window(text) Displays a message in a separate window (requires a window to be created first). world.Window("Combat Log: " + text)
world.SetVariable(name, value) Saves a variable with the plugin. Persists across MUSHclient sessions. world.SetVariable("player_hp", 100)
world.GetVariable(name) Retrieves a saved variable. hp = world.GetVariable("player_hp")
world.Execute(command) Executes a MUSHclient menu command (e.g., to open a window). world.Execute("show world")
world.GetLine() Gets the text from the command line (input box). cmd = world.GetLine()
world.SetLine(text) Sets the text in the command line. world.SetLine("say Hello")
world.Replace(line, text) Replaces the command line with new text and executes it. world.Replace("say Hello")

Best Practices and Tips

A. Error Handling

Your scripts can crash. Always wrap potentially risky code in a try...except block to prevent your entire plugin from failing.

try:
  # Code that might cause an error
  hp = world.GetVariable("player_hp")
  world.Send("heal " + str(hp))
except Exception as e:
  # If an error occurs, log it
  world.Note(f"An error occurred: {e}")

B. Loading and Saving Code

For complex projects, writing code directly in the MUSHclient script editor is cumbersome. It's much better to:

  1. Write your Python code in an external file (e.g., my_awesome_plugin.py) using a proper code editor like VS Code, Sublime Text, or PyCharm.
  2. In the MUSHclient Script Editor, go to File -> Load from file and select your Python file.
  3. To save your changes from MUSHclient back to the file, go to File -> Save to file.

C. The world object is global

You don't need to define my_world = world in every function. The world object is always available. You can just use world.Send(...) directly.

D. Getting Help

The absolute best resource is the MUSHclient Help File.

  1. In MUSHclient, press F1 or go to Help -> MUSHclient Help.
  2. Navigate to Plugins -> Python Plugin.
  3. This section contains a complete list of all world methods, variables, and examples. It's your bible for MUSHclient scripting.

A Complete Example: A Simple Health Monitor

Let's combine triggers and aliases into a useful plugin that tracks your health.

# In the Script Editor (or a separate .py file)
# Plugin state variables
health = 100
max_health = 100
def OnPluginInstall():
  world.Note("Installing Health Monitor Plugin.")
  # Trigger for health updates
  world.AddTrigger("You are (\d+) hit points?", "UpdateHealth", True, True)
  # Trigger for max health changes
  world.AddTrigger("Your maximum hit points are now (\d+).", "UpdateMaxHealth", True, True)
  # Alias for checking health
  world.AddAlias("hp", "CheckHealth", True)
def UpdateHealth(name, line, wildcards):
  global health
  health = int(wildcards[0])
  world.Note(f"Health updated: {health}/{max_health}")
def UpdateMaxHealth(name, line, wildcards):
  global max_health
  max_health = int(wildcards[0])
  world.Note(f"Max health updated: {health}/{max_health}")
def CheckHealth(name, line, wildcards):
  world.Note(f"Your current health is: {health}/{max_health}")
# Run the install function when the plugin starts
OnPluginInstall()

This plugin will automatically update your health when the MUD sends messages like "You are 75 hit points." and will respond to the hp command with your current status.

分享:
扫描分享到社交APP
上一篇
下一篇