https://wiki.mudlet.org/api.php?action=feedcontributions&user=RodeoS&feedformat=atomMudlet - User contributions [en]2024-03-28T10:19:41ZUser contributionsMediaWiki 1.35.0https://wiki.mudlet.org/index.php?title=Manual:Mapper_Functions&diff=15858Manual:Mapper Functions2020-11-10T14:21:30Z<p>RodeoS: /* addMapEvent */</p>
<hr />
<div>{{TOC right}}<br />
= Mapper Functions =<br />
These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be MUD-generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the MUD you're playing. For a collection of pre-made scripts and general mapper talk, visit the [http://forums.mudlet.org/viewforum.php?f=13 mapper section] of the forums.<br />
<br />
To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
==addAreaName==<br />
;areaID = addAreaName(areaName)<br />
<br />
:Adds a new area name and returns the new (positive) area ID for the new name. If the name already exists, older versions of Mudlet returned -1 though since 3.0 the code will return ''nil'' and an error message.<br />
: See also: [[#deleteArea|deleteArea()]], [[#addRoom|addRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local newId, err = addAreaName(string.random(10))<br />
<br />
if newId == nil or newId < 1 or err then<br />
echo("That area name could not be added - error is: ".. err.."\n")<br />
else<br />
cecho("<green>Created new area with the ID of "..newId..".\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==addCustomLine==<br />
;addCustomLine(roomID, id_to, direction, style, color, arrow)<br />
: See also: [[#getCustomLines|getCustomLines()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Adds a new/replaces an existing custom exit line to the 2D mapper for the room with the Id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to attach the custom line to.<br />
* ''id_to:''<br />
: EITHER: a room Id number, of a room on same area who's x and y coordinates are used as the other end of a SINGLE segment custom line (it does NOT imply that is what the exit it represent goes to, just the location of the end of the line);<br />
: OR: a table of sets of THREE (x,y and z) coordinates in that order, x and y can be decimals, z is an integer ('''and must be present and be the same for all points on the line''', though it is irrelevant to what is produced as the line is drawn on the same z-coordinate as the room that the line is attached to!)<br />
* ''direction:'' a string to associate the line with a valid exit direction, "n", "ne", "e", "se", "s", "sw", "w", "nw", "up", "down", "in" or "out" or a special exit (before Mudlet 3.17 this was case-sensitive and cardinal directions had to be uppercase).<br />
* ''style:'' a string, one of: "solid line", "dot line", "dash line", "dash dot line" or "dash dot dot line" exactly.<br />
* ''color:'' a table of three integers between 0 and 255 as the custom line color as the red, green and blue components in that order.<br />
* ''arrow:'' a boolean which if true will set the custom line to have an arrow on the end of the last segment.<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- create a line from roomid 1 to roomid 2<br />
addCustomLine(1, 2, "N", "dot line", {0, 255, 255}, true)<br />
<br />
addCustomLine(1, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
</syntaxhighlight><br />
<br />
A bigger example that'll create a new area and the room in it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local areaid = addAreaName("my first area")<br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
setRoomArea(newroomid, "my first area")<br />
setRoomCoordinates(newroomid, 0, 0, 0)<br />
<br />
addCustomLine(newroomid, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
<br />
centerview(newroomid)<br />
</syntaxhighlight><br />
<br />
Note: At the time of writing there is no Lua command to remove a custom exit line and, for Normal exits in the X-Y plane, revert to the standard straight line between the start room and the end room (or colored arrow for out of area exits) however this can be done from the GUI interface to the 2D mapper.<br />
<br />
==addMapEvent==<br />
;addMapEvent(uniquename, event name, parent, display name, arguments)<br />
<br />
:Adds a new entry to an existing mapper right-click entry. You can add one with addMapMenu. If there is no display name, it will default to the unique name (which otherwise isn't shown and is just used to differentiate this entry from others). ''event name'' is the Mudlet event that will be called when this is clicked on, and ''arguments'' will be passed to the handler function.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn") <br />
</syntaxhighlight><br />
The last line will make a label "Special Room!" under the "Favorites" menu that upon clicking will raise an event with all the arguments.<br />
<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Room type")<br />
addMapEvent("markRoomsAsDeathTrap", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as Death Trap")<br />
addMapEvent("markRoomsAsOneRoom", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as single-pass")<br />
<br />
function onMapMarkSelectedRooms(event, MarkRoomType)<br />
local SelectedRooms = getMapSelection()["rooms"]<br />
for i, val in ipairs(SelectedRooms) do<br />
if MarkRoomType == "markRoomsAsDeathTrap" then<br />
local r, g, b = unpack(color_table.black)<br />
--death trap<br />
setRoomEnv(val, 300)<br />
--death traps Env<br />
setCustomEnvColor(300, r, g, b, 255)<br />
setRoomChar(val, "☠️")<br />
lockRoom(val, true)<br />
elseif MarkRoomType == "markRoomsAsOneRoom" then<br />
local r, g, b = unpack(color_table.LightCoral)<br />
--single-pass<br />
setRoomEnv(val, 301)<br />
--one room Env<br />
setCustomEnvColor(301, r, g, b, 255)<br />
setRoomChar(val, "🚹")<br />
end<br />
end<br />
updateMap()<br />
end<br />
<br />
registerAnonymousEventHandler("onMapMarkSelectedRooms", "onMapMarkSelectedRooms")<br />
</syntaxhighlight><br />
This create menu and two submenu options: "Mark selected rooms as Death Trap" and "Mark selected rooms as single-pass"<br />
<br />
==addMapMenu==<br />
;addMapMenu(uniquename, parent, display name)<br />
<br />
:Adds a new submenu to the right-click menu that opens when you right-click on the mapper. You can then add more submenus to it, or add entries with [[#addMapEvent|addMapEvent()]].<br />
: See also: [[#addMapEvent|addMapEvent()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- This will create a menu named: Favorites.<br />
addMapMenu("Favorites")<br />
<br />
-- This will create a submenu with the unique id 'Favorites123' under 'Favorites' with the display name of 'More Favorites'.<br />
addMapMenu("Favorites1234343", "Favorites", "More Favorites") <br />
</syntaxhighlight><br />
<br />
==addRoom==<br />
;addRoom(roomID)<br />
<br />
:Creates a new room with the given ID, returns true if the room was successfully created. <br />
<br />
{{note}} If you're not using incremental room IDs but room IDs stitched together from other factors or in-game hashes for room IDs - and your room IDs are starting off at 250+million numbers, you need to look into incrementally creating Mudlets room IDs with [[#createRoomID|createRoomID()]] and associating your room IDs with Mudlets via [[#setRoomIDbyHash|setRoomIDbyHash()]] and [[#getRoomIDbyHash|getRoomIDbyHash()]]. The reason being is that Mudlet's A* pathfinding implementation from boost cannot deal with extremely large room IDs because the resulting matrices it creates for pathfinding are enormously huge.<br />
: See also: [[#createRoomID|createRoomID()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
</syntaxhighlight><br />
<br />
==addSpecialExit==<br />
;addSpecialExit(roomIDFrom, roomIDTo, moveCommand)<br />
<br />
:Creates a one-way from one room to another, that will use the given command for going through them.<br />
: See also: [[#clearSpecialExits|clearSpecialExits()]], [[#removeSpecialExit|removeSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- add a one-way special exit going from room 1 to room 2 using the 'pull rope' command<br />
addSpecialExit(1, 2, "pull rope")<br />
</syntaxhighlight><br />
<br />
Example in an alias:<br />
<syntaxhighlight lang="lua"><br />
-- sample alias pattern: ^spe (\d+) (.*?)$<br />
-- currentroom is your current room ID in this example<br />
addSpecialExit(currentroom,tonumber(matches[2]), matches[3])<br />
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])<br />
centerview(currentroom)<br />
</syntaxhighlight><br />
<br />
==centerview==<br />
;centerview (roomID)<br />
<br />
:Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.<br />
<br />
: See also: [[#getPlayerRoom|getPlayerRoom()]], [[#updateMap|updateMap()]]<br />
<br />
==clearAreaUserData==<br />
;clearAreaUserData(areaID)<br />
<br />
; Parameter<br />
* areaID - ID number for area to clear.<br />
<br />
:Clears all user data from a given area. Note that this will not touch the room user data.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#clearRoomUserData|clearRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearAreaUserData(34))<br />
-- I did have data in that area, so it returns:<br />
true<br />
<br />
display(clearAreaUserData(34))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==clearAreaUserDataItem==<br />
;clearAreaUserDataItem(areaID, key)<br />
<br />
:Removes the specific key and value from the user data from a given area.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#clearAreaUserData|clearAreaUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
true<br />
<br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserData==<br />
;clearMapUserData()<br />
<br />
:Clears all user data stored for the map itself. Note that this will not touch the area or room user data.<br />
<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserData|clearAreaUserData()]]<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearMapUserData())<br />
-- I did have user data stored for the map, so it returns:<br />
true<br />
<br />
display(clearMapUserData())<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserDataItem==<br />
;clearUserDataItem(mapID, key)<br />
<br />
:Removes the specific key and value from the user data from the map user data.<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearMapUserData|clearMapUserData()]], [[#clearAreaRoomUserData|clearAreaRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
last_modified = "1483228799"<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
true<br />
<br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==clearRoomUserData==<br />
;clearRoomUserData(roomID)<br />
<br />
:Clears all user data from a given room.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]:<br />
<br />
{{note}} Returns a boolean true if any data was removed from the specified room and false if there was nothing to erase since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearRoomUserData(3441))<br />
-- I did have data in that room, so it returns:<br />
true<br />
<br />
display(clearRoomUserData(3441))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearRoomUserDataItem==<br />
;clearRoomUserDataItem(roomID, key)<br />
<br />
:Removes the specific key and value from the user data from a given room.<br />
:Returns a boolean true if data was found against the give key in the user data for the given room and it is removed, will return false if exact key not present in the data. Returns nil if the room for the roomID not found.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
true<br />
<br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0+<br />
<br />
==clearSpecialExits==<br />
;clearSpecialExits(roomID) <br />
<br />
:Removes all special exits from a room.<br />
: See also: [[#addSpecialExit|addSpecialExit()]], [[#removeSpecialExit|removeSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
clearSpecialExits(1337)<br />
<br />
if #getSpecialExits(1337) == 0 then -- clearSpecialExits will never fail on a valid room ID, this is an example<br />
echo("All special exits successfully cleared from 1337.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==closeMapWidget==<br />
;closeMapWidget()<br />
:closes (hides) the map window (similar to clicking on the map icon)<br />
<br />
{{note}} available in Mudlet 4.7+<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
==connectExitStub==<br />
;connectExitStub(fromID, direction) or connectExitStub(fromID, toID, [direction])<br />
<br />
:Connects existing rooms with matching exit stubs. If you only give it a roomID and a direction, it'll work out which room should be linked to it that has an appropriate opposite exit stub and is located in the right direction. You can also just specify from and to room IDs, and it'll smartly use the right direction to link in. Lastly, you can specify all three arguments - fromID, toID and the direction (in that order) if you'd like to be explicit, or use [[#setExit|setExit()]] for the same effect.<br />
<br />
;Parameters<br />
* ''fromID:''<br />
: Room ID to set the exit stub in.<br />
* ''direction:''<br />
: You can either specify the direction to link the room in, and/or a specific room ID (see below). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
* ''toID:''<br />
: The room ID to link this room to. If you don't specify it, the mapper will work out which room should be logically linked.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try and connect all stubs that are in a room<br />
local stubs = getExitStubs(roomID)<br />
if stubs then<br />
for i,v in pairs(stubs) do<br />
connectExitStub(roomID, v)<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==createMapLabel==<br />
;labelID = createMapLabel(areaID, text, posx, posy, posz, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue, zoom, fontSize, showOnTop, noScaling)<br />
<br />
:Creates a text label on the map at given coordinates, with the given background and foreground colors. It can go above or below the rooms, scale with zoom or stay a static size. It returns a label ID that you can use later for deleting it.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
<br />
: See also: [[#getMapLabel|getMapLabel()]], [[#getMapLabels|getMapLabels()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID where to put the label.<br />
* ''text:''<br />
: The text to put into the label. To get a multiline text label add a '\n' between the lines.<br />
* ''posx, posy, posz:''<br />
: Position of the label in room coordinates.<br />
* ''fgRed, fgGreen fgBlue:''<br />
: Foreground color or text color of the label.<br />
* ''bgRed, bgGreen bgBlue:''<br />
: Background color of the label.<br />
* ''zoom:''<br />
: Zoom factor of the label if noScaling is false. Higher zoom will give higher resolution of the text and smaller size of the label. Default is 30.0.<br />
* ''fontSize:''<br />
: Size of the font of the text. Default is 50.<br />
* ''showOnTop:''<br />
: If true the label will be drawn on top of the rooms and if it is false the label will be drawn as a background.<br />
* ''noScaling:''<br />
: If true the label will have the same size when you zoom in and out in the mapper. If it is false the label will scale when you zoom the mapper. <br />
<br />
: See also: [[#deleteMapLabel|deleteMapLabel]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- the first 50 is some area id, the next three 0,0,0 are coordinates - middle of the area<br />
-- 255,0,0 would be the foreground in RGB, 23,0,0 would be the background RGB<br />
-- zoom is only relevant when when you're using a label of a static size, so we use 0<br />
-- and we use a font size of 20 for our label, which is a small medium compared to the map<br />
local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)<br />
<br />
-- to create a multi line text label we add '\n' between lines<br />
-- the position is placed somewhat to the northeast of the center of the map<br />
-- this label will be scaled as you zoom the map.<br />
local labelid = createMapLabel( 50, "1. Row One\n2. Row 2", .5,5.5,0, 255,0,0, 23,0,0, 30,50, true,false)<br />
<br />
</syntaxhighlight><br />
<br />
==createMapImageLabel==<br />
;labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop)<br />
<br />
:Creates an image label on the map at the given coordinates, with the given dimensions and zoom. You might find the default room and image size correlation to be too big - try reducing the width and height of the image then, while also zooming in the same amount.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
: See also: [[#deleteMapLabel|deleteMapLabel]]<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
-- 138 is our pretend area ID<br />
-- next, inside [[]]'s, is the exact location of our image<br />
-- 0,0,0 are the x,y,z coordinates - so this will place it in the middle of the map<br />
-- 482 is the width of the image - we divide it by 100 to scale it down, and then we'll zoom it by 100 - making the image take up about 4 rooms in width then<br />
-- 555 is the original height of the image<br />
-- 100 is how much we zoom it by, 1 would be no zoom<br />
-- and lastly, false to make it go below our rooms<br />
createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false)<br />
</syntaxhighlight><br />
<br />
==createMapper==<br />
;createMapper([name of userwindow], x, y, width, height)<br />
<br />
:Creates a miniconsole window for the mapper to render in, the with the given dimensions. You can only create one mapper at a time, and it is not currently possible to have a label on or under the mapper - otherwise, clicks won't register.<br />
<br />
{{note}}<br />
userwindow argument only available in 4.6.1+<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
createMapper(0,0,300,300) -- creates a 300x300 mapper in the top-left corner of Mudlet<br />
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- another example:<br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
<br />
{{Note}} If this command is ''not'' used then clicking on the Main Toolbar's '''Map''' button will create a dock-able widget (that can be floated free to anywhere on the Desktop, it can be resized and does not have to even reside on the same monitor should there be multiple screens in your system). Further clicks on the '''Map''' button will toggle between showing and hiding the map whether it was created using the ''createMapper'' function or as a dock-able widget.<br />
<br />
==createRoomID==<br />
;usableId = createRoomID([minimumStartingRoomId])<br />
<br />
:Returns the lowest possible room ID you can use for creating a new room. If there are gaps in room IDs your map uses it, this function will go through the gaps first before creating higher IDs. <br />
<br />
;Parameters<br />
* ''minimumStartingRoomId'' (optional):<br />
: If provided, specifies a roomID to start searching for an empty one at, instead of 1. Useful if you'd like to ensure certain areas have specific room number ranges, for example. If you you're working with a huge map, provide the last used room ID to this function for an available roomID to be found a lot quicker.<br />
<br />
{{note}} ''minimumStartingRoomId'' is available since Mudlet 3.0.<br />
<br />
: See also: [[#addRoom|addRoom()]]<br />
<br />
==deleteArea==<br />
;deleteArea(areaID or areaName)<br />
<br />
:Deletes the given area and all rooms in it. Returns ''true'' on success or ''nil'' + ''error message'' otherwise.<br />
: See also: [[#addAreaName|addAreaName()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to delete.<br />
* ''areaName:''<br />
: Area name to delete (available since Mudlet 3.0).<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete by areaID<br />
deleteArea(23)<br />
-- or since Mudlet 3.0, by area name<br />
deleteArea("Big city")<br />
</syntaxhighlight><br />
<br />
==deleteMapLabel==<br />
;deleteMapLabel(areaID, labelID)<br />
<br />
:Deletes a map label from a specfic area.<br />
: See also: [[#createMapLabel|createMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteMapLabel(50, 1)<br />
</syntaxhighlight><br />
<br />
==deleteRoom==<br />
;deleteRoom(roomID)<br />
<br />
:Deletes an individual room, and unlinks all exits leading to and from it.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteRoom(335)<br />
</syntaxhighlight><br />
<br />
==exportAreaImage==<br />
;exportAreaImage(areaID)<br />
<br />
:Exports the area as an image into your profile's directory.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- save the area with ID 1 as a map<br />
exportAreaImage(1)<br />
</syntaxhighlight><br />
<br />
{{note}} This command is currently inoperable in current 3.0+ versions of Mudlet.<br />
<br />
==getAllAreaUserData==<br />
;dataTable = getAllAreaUserData(areaID)<br />
<br />
:Returns all the user data items stored in the given area ID; will return an empty table if there is no data stored or nil if there is no such area with that ID.<br />
<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
--might result in:--<br />
{<br />
country = "Andor",<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0.<br />
<br />
==getAllMapUserData==<br />
;dataTable = getAllMapUserData()<br />
<br />
:Returns all the user data items stored at the map level; will return an empty table if there is no data stored.<br />
<br />
: See also: [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
--might result in:--<br />
{<br />
description = [[This map is about so and so game]],<br />
author = "Bob",<br />
["last updated"] = "December 5, 2020"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0+<br />
<br />
==getAllRoomEntrances==<br />
;exitsTable = getAllRoomEntrances(roomID)<br />
<br />
:Returns an indexed list of normal and special exits leading into this room. In case of two-way exits, this'll report exactly the same rooms as [[#getRoomExits|getRoomExits()]], but this function has the ability to pick up one-way exits coming into the room as well.<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- print the list of rooms that have exits leading into room 512<br />
for _, roomid in ipairs(getAllRoomEntrances(512)) do <br />
print(roomid)<br />
end<br />
</syntaxhighlight><br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
==getAllRoomUserData==<br />
;dataTable = getAllRoomUserData(roomID)<br />
<br />
:Returns all the user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
: See also: [[#getRoomUserDataKeys|getRoomUserDataKeys()]] - for a related command that only returns the data keys.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
--might result in:--<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0.<br />
<br />
==getAreaExits==<br />
;roomTable = getAreaExits(areaID, showExits)<br />
<br />
: Returns a table (indexed or key-value) of the rooms in the given area that have exits leading out to other areas - that is, border rooms.<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to list the exits for.<br />
* ''showExits:''<br />
: Boolean argument, if true then the exits that lead out to another area will be listed for each room.<br />
<br />
: See also: [[#setExit|setExit()]], [[#getRoomExits|getRoomExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- list all border rooms for area 44:<br />
getAreaExits(44)<br />
<br />
-- returns:<br />
--[[<br />
{<br />
7091,<br />
10659,<br />
11112,<br />
11122,<br />
11133,<br />
11400,<br />
12483,<br />
24012<br />
}<br />
]]<br />
<br />
-- list all border rooms for area 44, and the exits within them that go out to other areas:<br />
getAreaExits(44, true)<br />
--[[<br />
{<br />
[12483] = {<br />
north = 27278<br />
},<br />
[11122] = {<br />
["enter grate"] = 14551<br />
},<br />
[11112] = {<br />
["enter grate"] = 14829<br />
},<br />
[24012] = {<br />
north = 22413<br />
},<br />
[11400] = {<br />
south = 10577<br />
},<br />
[11133] = {<br />
["enter grate"] = 15610<br />
},<br />
[7091] = {<br />
down = 4411<br />
},<br />
[10659] = {<br />
["enter grate"] = 15510<br />
}<br />
}<br />
]]<br />
</syntaxhighlight><br />
<br />
==getAreaRooms==<br />
;getAreaRooms(area id)<br />
<br />
:Returns an indexed table with all rooms IDs for a given area ID (room IDs are values), or ''nil'' if no such area exists. <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- using the sample findAreaID() function defined in the getAreaTable() example, <br />
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID<br />
function echoRoomList(areaname)<br />
local id, msg = findAreaID(areaname)<br />
if id then<br />
local roomlist, endresult = getAreaRooms(id), {}<br />
<br />
-- obtain a room list for each of the room IDs we got<br />
for _, id in pairs(roomlist) do<br />
endresult[id] = getRoomName(id)<br />
end<br />
<br />
-- now display something half-decent looking<br />
cecho(string.format(<br />
"List of all rooms in %s (%d):\n", msg, table.size(endresult)))<br />
<br />
for roomid, roomname in pairs(endresult) do<br />
cecho(string.format(<br />
"%6s: %s\n", roomid, roomname))<br />
end<br />
elseif not id and msg then<br />
echo("ID not found; " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTable==<br />
;areaTable = getAreaTable()<br />
<br />
:Returns a key(area name)-value(area id) table with all known areas and their IDs. Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
: See also: [[#getAreaTableSwap|getAreaTableSwap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example function that returns the area ID for a given area<br />
<br />
function findAreaID(areaname)<br />
local list = getAreaTable()<br />
<br />
-- iterate over the list of areas, matching them with substring match. <br />
-- if we get match a single area, then return it's ID, otherwise return<br />
-- 'false' and a message that there are than one are matches<br />
local returnid, fullareaname<br />
for area, id in pairs(list) do<br />
if area:find(areaname, 1, true) then<br />
if returnid then return false, "more than one area matches" end<br />
returnid = id; fullareaname = area<br />
end<br />
end<br />
<br />
return returnid, fullareaname<br />
end<br />
<br />
-- sample use:<br />
local id, msg = findAreaID("blahblah")<br />
if id then<br />
echo("Found a matching ID: " .. id)<br />
elseif not id and msg then<br />
echo("ID not found: " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTableSwap==<br />
;areaTable = getAreaTableSwap()<br />
<br />
:Returns a key(area id)-value(area name) table with all known areas and their IDs. Unlike getAreaTable which won't show you all areas with the same name by different IDs, this function will. Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
==getAreaUserData==<br />
;dataValue = getAreaUserData(areaID, key)<br />
<br />
:Returns a specific data item stored against the given key for the given area ID number. This is very like the corresponding Room User Data command but intended for per area rather than for per room data (for storage of data relating to the whole map see the corresponding Map User Data commands.) <br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or a Lua ''nil'' and an error message if the key is not present in the Area User Data for the given Area ID. Use [[#setAreaUserData|setAreaUserData()]] function for storing the user data.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAreaUserData(34, "country"))<br />
-- might produce --<br />
"Andor"<br />
</syntaxhighlight><br />
<br />
{{note}} <br />
<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
==getCustomEnvColorTable==<br />
;envcolors = getCustomEnvColorTable()<br />
<br />
:Returns a table with customized environments, where the key is the environment ID and the value is a indexed table of rgb values.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
{<br />
envid1 = {r,g,b},<br />
envid2 = {r,g,b}<br />
}<br />
</syntaxhighlight><br />
<br />
==getCustomLines==<br />
;lineTable = getCustomLines(roomID)<br />
: See also: [[#addCustomLine|addCustomLine()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Returns a table including all the details of the custom exit lines, if any, for the room with the id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to return the custom line details of.<br />
<br />
{{note}} <br />
Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display getCustomLines(1)<br />
{<br />
["climb Rope"] = {<br />
attributes = {<br />
color = {<br />
b = 0,<br />
g = 128,<br />
r = 128<br />
},<br />
style = "dash dot dot line",<br />
arrow = false<br />
},<br />
points = {<br />
{<br />
y = 9.5,<br />
x = 4.5<br />
},<br />
{<br />
y = 9.5,<br />
x = 6<br />
},<br />
[0] = {<br />
y = 5.5,<br />
x = 4.5<br />
}<br />
}<br />
},<br />
N = {<br />
attributes = {<br />
color = {<br />
b = 255,<br />
g = 255,<br />
r = 0<br />
},<br />
style = "dot line",<br />
arrow = true<br />
},<br />
points = {<br />
[0] = {<br />
y = 27,<br />
x = -3<br />
}<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
==getDoors==<br />
;doors = getDoors(roomID)<br />
<br />
:Returns a key-value table with the cardinal direction as the key and the door value as a number. If there are no doors in a room, it returns an empty table.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to check for doors in.<br />
<br />
: See also: [[#setDoor|setDoor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- an example that displays possible doors in room 2334<br />
local doors = getDoors(2334)<br />
<br />
if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end<br />
<br />
local door_status = {"open", "closed", "locked"}<br />
<br />
for direction, door in pairs(doors) do<br />
cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")<br />
end<br />
</syntaxhighlight><br />
<br />
==getExitStubs==<br />
;stubs = getExitStubs(roomid)<br />
<br />
:Returns an indexed table (starting at 0) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#connectExitStub|connectExitStub()]], [[#getExitStubs1|getExitStubs1()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(stubs[i]) end<br />
</syntaxhighlight><br />
<br />
{{note}} Previously would throw a lua error on non-existent room - now returns nil plus error message (as does other run-time errors) - previously would return just a nil on NO exit stubs but now returns a notification error message as well, to aide disambiguation of the nil value.<br />
<br />
==getExitStubs1==<br />
;stubs = getExitStubs1(roomid)<br />
<br />
:Returns an indexed table (starting at 1) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping. As this function starts indexing from 1 as it is default in Lua, you can use ipairs() to iterate over the results.<br />
<br />
; See also: [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
for k,v in ipairs(getExitStubs1(6)) do print(k,v) end<br />
</syntaxhighlight><br />
<br />
==getExitWeights==<br />
;weights = getExitWeights(roomid)<br />
<br />
:Returns a key-value table of the exit weights that a room has, with the direction or special exit as a key and the value as the exit weight. If a weight for a direction wasn't yet set, it won't be listed.<br />
<br />
;Parameters<br />
* ''roomid:''<br />
: Room ID to view the exit weights in.<br />
<br />
: See also: [[#setExitWeight|setExitWeight()]]<br />
<br />
==getGridMode==<br />
;TrueOrFalse = getGridMode(areaID)<br />
<br />
:Use this to see, if a specific area has grid/wilderness view mode set. This way, you can also calculate from a script, how many grid areas a map has got in total.<br />
<br />
{{note}} <br />
Available since Mudlet 3.11<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID (number) to view the grid mode of.<br />
<br />
: See also: [[#setGridMode|setGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getGridMode(55)<br />
-- will return: false<br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
getGridMode(55)<br />
-- will return: true<br />
</syntaxhighlight><br />
<br />
==getMapEvents==<br />
; mapevents = getMapEvents()<br />
<br />
: Returns a list of map events currently registered. Each event is a dictionary with the keys ''uniquename'', ''parent'', ''event name'', ''display name'', and ''arguments'', which correspond to the arguments of ''addMapEvent()''.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#addMapEvent|addMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")<br />
<br />
local mapEvents = getMapEvents()<br />
for _, event in ipairs(mapEvents) do<br />
echo(string.format("MapEvent '%s' is bound to event '%s' with these args: '%s'", event["uniquename"], event["event name"], table.concat(event["arguments"], ",")))<br />
end<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.3<br />
<br />
==getMapLabel==<br />
;labelinfo = getMapLabels(areaID, labelID)<br />
<br />
:Returns a key-value table describing that particular label in an area. Keys it contains are the ''X'', ''Y'', ''Z'' coordinates, ''Height'' and ''Width'', and the ''Text'' it contains. If the label is an image label, then ''Text'' will be set to the ''no text'' string.<br />
<br />
: See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabels|getMapLabels()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lua getMapLabels(1658987)<br />
table {<br />
1: 'no text'<br />
0: 'test'<br />
}<br />
<br />
lua getMapLabel(1658987, 0)<br />
table {<br />
'Y': -2<br />
'X': -8<br />
'Z': 11<br />
'Height': 3.9669418334961<br />
'Text': 'test'<br />
'Width': 8.6776866912842<br />
}<br />
<br />
lua getMapLabel(1658987, 1)<br />
table {<br />
'Y': 8<br />
'X': -15<br />
'Z': 11<br />
'Height': 7.2520666122437<br />
'Text': 'no text'<br />
'Width': 11.21900844574<br />
}<br />
<br />
<br />
</syntaxhighlight><br />
<br />
==getMapLabels==<br />
;arealabels = getMapLabels(areaID)<br />
<br />
:Returns an indexed table (that starts indexing from 0) of all of the labels in the area, plus their label text. You can use the label id to [[#deleteMapLabel|deleteMapLabel()]] it.<br />
:If there are no labels in the area at all, will instead return the area number.<br />
<br />
: See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabel|getMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapLabels(43))<br />
table {<br />
0: ''<br />
1: 'Waterways'<br />
}<br />
<br />
deleteMapLabel(43, 0)<br />
display(getMapLabels(43))<br />
table {<br />
1: 'Waterways'<br />
}<br />
</syntaxhighlight><br />
<br />
==getMapSelection==<br />
; getMapSelection()<br />
<br />
:Returns a table containing details of the current mouse selection in the 2D mapper.<br />
<br />
:Reports on one or more rooms being selected (i.e. they are highlighted in orange).<br />
<br />
:The contents of the table will vary depending on what is currently selected. If the selection is of map rooms then there will be keys of ''center'' and ''rooms'': the former will indicates the center room (the one with the yellow cross-hairs) if there is more than one room selected or the only room if there is only one selected (there will not be cross-hairs in that case); the latter will contain a list of the one or more rooms.<br />
<br />
; Example - several rooms selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5011,<br />
5012,<br />
5013,<br />
5014,<br />
5018,<br />
5019,<br />
5020<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - one room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5013<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - no or something other than a room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
}<br />
</syntaxhighlight><br />
<br />
{{Note}} Available in Mudlet 3.17+<br />
<br />
==getMapUserData==<br />
;getMapUserData( key )<br />
<br />
;Parameters<br />
* ''key:''<br />
: string used as a key to select the data stored in the map as a whole.<br />
<br />
:Returns the user data item (string); will return a nil+error message if there is no data with such a key in the map data.<br />
<br />
: See also: [[#getAllMapUserData|getAllMapUserData()]], [[#setMapUserData|setMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapUserData("last updated"))<br />
--might result in:--<br />
"December 5, 2020"<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0<br />
<br />
==getPath==<br />
;getPath(roomID from, roomID to)<br />
<br />
:Returns a boolean true/false if a path between two room IDs is possible. If it is, the global ''speedWalkDir'' table is set to all of the directions that have to be taken to get there, and the global ''speedWalkPath'' table is set to all of the roomIDs you'll encounter on the way, and as of 3.0, ''speedWalkWeight'' will return all of the room weights. Additionally returns the total cost (all weights added up) of the path after the boolean argument in 3.0.<br />
<br />
<br />
: See also: [[Manual:Lua_Functions#translateTable()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if we can go to room 155 from room 34 - if yes, go to it<br />
if getPath(34,155) then<br />
gotoRoom(155)<br />
else<br />
echo("\nCan't go there!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPlayerRoom==<br />
;getPlayerRoom()<br />
<br />
:Returns the current player location as set by [[#centerview|centerview()]].<br />
<br />
: See also: [[#centerview|centerview]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("We're currently in " .. getRoomName(getPlayerRoom()))<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.14<br />
<br />
==getRoomArea==<br />
;getRoomArea(roomID)<br />
<br />
:Returns the area ID of a given room ID. To get the area name, you can check the area ID against the data given by [[#getAreaTable | getAreaTable()]] function, or use the [[#getRoomAreaName |getRoomAreaName()]] function.<br />
<br />
{{note}} If the room ID does not exist, this function will raise an error.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Area ID of room #100 is: "..getRoomArea(100))<br />
<br />
display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))<br />
</syntaxhighlight><br />
<br />
==getRoomAreaName==<br />
;getRoomAreaName(areaID or areaName)<br />
<br />
:Returns the area name for a given area id; or the area id for a given area name.<br />
<br />
{{note}} Despite the name, this function will not return the area name for a given ''room'' id (or room name) directly. However, renaming or revising it would break existing scripts.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))<br />
</syntaxhighlight><br />
<br />
<br />
==getRoomChar==<br />
;getRoomChar(roomID)<br />
<br />
:Returns the single ASCII character that forms the ''symbol'' for the given room id.<br />
<br />
: '''Since Mudlet version 3.8 :''' this facility has been extended:<br />
: Returns the string (UTF-8) that forms the ''symbol'' for the given room id; this may have been set with either [[#setRoomChar|setRoomChar()]] or with the ''symbol'' (was ''letter'' in prior versions) context menu item for rooms in the 2D Map.<br />
<br />
==getRoomCoordinates==<br />
;x,y,z = getRoomCoordinates(roomID)<br />
<br />
:Returns the room coordinates of the given room ID.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local x,y,z = getRoomCoordinates(roomID)<br />
echo("Room Coordinates for "..roomID..":")<br />
echo("\n X:"..x)<br />
echo("\n Y:"..y)<br />
echo("\n Z:"..z)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- A quick function that will find all rooms on the same z-position in an area; this is useful if, say, you want to know what all the same rooms on the same "level" of an area is.<br />
function sortByZ(areaID, zval)<br />
local area = getAreaRooms(areaID)<br />
local t = {}<br />
for _, id in ipairs(area) do<br />
local _, _, z = getRoomCoordinates(id)<br />
if z == zval then<br />
table.insert(t, id)<br />
end<br />
end<br />
return t<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomEnv==<br />
;envID = getRoomEnv(roomID)<br />
<br />
:Returns the environment ID of a room. The mapper does not store environment names, so you'd need to keep track of which ID is what name yourself.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
funtion checkID(id)<br />
echo(strinf.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))<br />
end<br />
</syntaxhighlight><br />
<br />
== getRoomExits ==<br />
;getRoomExits (roomID)<br />
:Returns the currently known non-special exits for a room in an key-index form: ''exit = exitroomid''.<br />
<br />
: See also: [[#getSpecialExits|getSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
table {<br />
'northwest': 80<br />
'east': 78<br />
}<br />
</syntaxhighlight><br />
<br />
Here's a practical example that queries the rooms around you and searched for one of the water environments (the number would depend on how it was mapped):<br />
<br />
<syntaxhighlight lang="lua"><br />
local exits = getRoomExits(mycurrentroomid)<br />
for direction,num in pairs(exits) do<br />
local env_num = getRoomEnv(num)<br />
if env_num == 22 or env_num == 20 or env_num == 30 then<br />
print("There's water to the "..direction.."!")<br />
end<br />
end</syntaxhighlight><br />
<br />
==getRoomHashByID==<br />
;getRoomHashByID(roomID)<br />
<br />
:Returns a room hash that is associated with a given room ID in the mapper. This is primarily for MUDs that make use of hashes instead of room IDs. It may be used to share map data while not sharing map itself. ''nil'' is returned if no room is not found.<br />
<br />
: See also: [[#getRoomIDbyHash|getRoomIDbyHash()]]<br />
{{note}} Available since Mudlet 3.13.0<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
for id,name in pairs(getRooms()) do<br />
local h = getRoomUserData(id, "herbs")<br />
if h ~= "" then<br />
echo(string.format([[["%s"] = "%s",]], getRoomHashByID(id), h))<br />
echo("\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomIDbyHash==<br />
;roomID = getRoomIDbyHash(hash)<br />
<br />
:Returns a room ID that is associated with a given hash in the mapper. This is primarily for MUDs that make use of hashes instead of room IDs (like [http://avalon.mud.de/index.php?enter=1 Avalon.de] MUD). ''-1'' is returned if no room ID matches the hash.<br />
<br />
: See also: [[#getRoomHashByID|getRoomHashByID()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177<br />
local id = getRoomIDbyHash("5dfe55b0c8d769e865fd85ba63127fbc")<br />
if id == -1 then <br />
id = createRoomID()<br />
setRoomIDbyHash(id, "5dfe55b0c8d769e865fd85ba63127fbc")<br />
addRoom(id)<br />
setRoomCoordinates(id, 0, 0, -1)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomName==<br />
;getRoomName(roomID)<br />
<br />
:Returns the room name for a given room id.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("The name of the room id #455 is %s.", getRoomName(455))<br />
</syntaxhighlight><br />
<br />
==getRooms==<br />
;rooms = getRooms()<br />
<br />
:Returns the list of '''all''' rooms in the map in the whole map in roomid - room name format.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- simple, raw viewer for rooms in the world<br />
display(getRooms())<br />
<br />
-- iterate over all rooms in code<br />
for id,name in pairs(getRooms()) do<br />
print(id, name)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomsByPosition==<br />
;roomTable = getRoomsByPosition(areaID, x,y,z)<br />
<br />
:Returns an indexed table of all rooms at the given coordinates in the given area, or an empty one if there are none. This function can be useful for checking if a room exists at certain coordinates, or whenever you have rooms overlapping.<br />
<br />
{{note}} The returned table starts indexing from '''0''' and not the usual lua index of '''1''', which means that using '''#''' to count the size of the returned table will produce erroneous results - use [[Manual:Table_Functions#table.size|table.size()]] instead.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sample alias to determine a room nearby, given a relative direction from the current room<br />
<br />
local otherroom<br />
if matches[2] == "" then<br />
local w = matches[3]<br />
local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)<br />
local has = table.contains<br />
if has({"west", "left", "w", "l"}, w) then<br />
x = (x or ox) - 1; y = (y or oy); z = (z or oz)<br />
elseif has({"east", "right", "e", "r"}, w) then<br />
x = (x or ox) + 1; y = (y or oy); z = (z or oz)<br />
elseif has({"north", "top", "n", "t"}, w) then<br />
x = (x or ox); y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"south", "bottom", "s", "b"}, w) then<br />
x = (x or ox); y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"northwest", "topleft", "nw", "tl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"northeast", "topright", "ne", "tr"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"southeast", "bottomright", "se", "br"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"up", "u"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) + 1<br />
elseif has({"down", "d"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) - 1<br />
end<br />
<br />
local carea = getRoomArea(mmp.currentroom)<br />
if not carea then mmp.echo("Don't know what area are we in.") return end<br />
<br />
otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))<br />
<br />
if not otherroom then<br />
mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return<br />
else<br />
mmp.echo("The room "..w.." of us has an ID of "..otherroom)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomUserData==<br />
;getRoomUserData(roomID, key)<br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or "" if none is stored. Use [[#setRoomUserData|setRoomUserData()]] function for setting the user data.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserData(341, "visitcount"))<br />
</syntaxhighlight><br />
<br />
:;getRoomUserData(roomID, key, enableFullErrorReporting)<br />
<br />
::Returns the user data value (string) stored at a given room with a given key (string), or, if the boolean value ''enableFullErrorReporting'' is true, ''nil'' and an error message if the key is not present or the room does not exist; if ''enableFullErrorReporting'' is false an empty string is returned but then it is not possible to tell if that particular value is actually stored or not against the given key.<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<!-- I would like this block to be indented to match the Example header but the mark-up system seems to be broken and only includes the first line<br />
if the start of the code line begins: ":<lua>..."--><br />
<syntaxhighlight lang="lua">local vNum = 341<br />
result, errMsg = getRoomUserData(vNum, "visitcount", true)<br />
if result ~= nil then<br />
display(result)<br />
else<br />
echo("\nNo visitcount data for room: "..vNum.."; reason: "..errMsg.."\n")<br />
end</syntaxhighlight><br />
<br />
==getRoomUserDataKeys==<br />
;getRoomUserDataKeys(roomID)<br />
<br />
:Returns all the keys for user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserDataKeys(3441))<br />
--might result in:--<br />
{<br />
"description",<br />
"doorname_up",<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==getRoomWeight==<br />
;getRoomWeight(roomID)<br />
<br />
:Returns the weight of a room. By default, all new rooms have a weight of 1.<br />
: See also: [[#setRoomWeight|setRoomWeight()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Original weight of room 541: "..getRoomWeight(541))<br />
setRoomWeight(541, 3)<br />
display("New weight of room 541: "..getRoomWeight(541))<br />
</syntaxhighlight><br />
<br />
==getSpecialExits==<br />
;exits = getSpecialExits(roomID)<br />
<br />
:Returns a roomid - command table of all special exits in the room. If there are no special exits in the room, the table returned will be empty.<br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getSpecialExits(1337)<br />
<br />
-- results in:<br />
--[[<br />
table {<br />
12106: 'faiglom nexus'<br />
}<br />
]]<br />
</syntaxhighlight><br />
<br />
==getSpecialExitsSwap==<br />
;getSpecialExitsSwap(roomID)<br />
<br />
:Very similar to [[#getSpecialExits|getSpecialExits()]] function, but returns the rooms in the command - roomid style.<br />
<br />
==gotoRoom==<br />
;gotoRoom (roomID)<br />
:Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".<br />
<br />
In case this isn't working, and you are coding your own mapping script, [[Mapping_script#Making_your_own_mapping_script|see here]] how to implement additional functionality necessary.<br />
<br />
==hasExitLock==<br />
;status = hasExitLock(roomID, direction)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
-- check if the east exit of room 1201 is locked<br />
display(hasExitLock(1201, 4))<br />
display(hasExitLock(1201, "e"))<br />
display(hasExitLock(1201, "east"))<br />
</syntaxhighlight><br />
<br />
: See also: [[#lockExit|lockExit()]]<br />
<br />
==hasSpecialExitLock==<br />
;hasSpecialExitLock(from roomID, to roomID, moveCommand)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. ''moveCommand'' is the action to take to get through the gate.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command<br />
lockSpecialExit(17463, 7814, 'enter feather', true)<br />
<br />
-- see if it is locked: it will say 'true', it is<br />
display(hasSpecialExitLock(17463, 7814, 'enter feather'))<br />
</syntaxhighlight><br />
<br />
==highlightRoom==<br />
;highlightRoom( roomID, color1Red, color1Green, color1Blue, color2Red, color2Green, color2Blue, highlightRadius, color1Alpha, color2Alpha)<br />
<br />
:Highlights a room with the given color, which will override its environment color. If you use two different colors, then there'll be a shading from the center going outwards that changes into the other color. <br />
<br />
;Parameters<br />
* ''roomID''<br />
: ID of the room to be colored.<br />
* ''color1Red, color1Green, color1Blue''<br />
: RGB values of the first color.<br />
* ''color2Red, color2Green, color2Blue''<br />
: RGB values of the second color.<br />
* ''highlightRadius'' <br />
: The radius for the highlight circle - if you don't want rooms beside each other to overlap, use ''1'' as the radius. <br />
* ''color1Alpha'' and ''color2Alpha'' <br />
: Transparency values from 0 (completely transparent) to 255 (not transparent at all).<br />
<br />
: See also: [[#unHighlightRoom|unHighlightRoom()]]<br />
<br />
{{note}} Available since Mudlet 2.0.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- color room #351 red to blue<br />
local r,g,b = unpack(color_table.red)<br />
local br,bg,bb = unpack(color_table.blue)<br />
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)<br />
</syntaxhighlight><br />
<br />
==loadMap==<br />
;loadMap(file location)<br />
<br />
:Loads the map file from a given location. The map file must be in Mudlet's format - saved with [[#saveMap|saveMap()]] or, as of the Mudlet 3.0 may be a MMP XML map conforming to the structure used by I.R.E. for their download-able maps for their MUDs. <br />
<br />
:Returns a boolean for whenever the loading succeeded. Note that the mapper must be open, or this will fail.<br />
<br />
<syntaxhighlight lang="lua"><br />
loadMap("/home/user/Desktop/Mudlet Map.dat")<br />
</syntaxhighlight><br />
<br />
==lockExit==<br />
;lockExit(roomID, direction, lockIfTrue)<br />
<br />
:Locks a given exit from a room (which means that unless all exits in the incoming room are locked, it'll still be accessible). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
: See also: [[#hasExitLock|hasExitLock()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- lock the east exit of room 1201 so we never path through it<br />
lockExit(1201, 4, true)<br />
</syntaxhighlight><br />
<br />
==lockRoom==<br />
;lockRoom (roomID, lockIfTrue)<br />
<br />
:Locks a given room id from future speed walks (thus the mapper will never path through that room).<br />
: See also: [[#roomLocked | roomLocked()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockRoom(1, true) -- locks a room if from being walked through when speedwalking.<br />
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.<br />
</syntaxhighlight><br />
<br />
==lockSpecialExit==<br />
;lockSpecialExit (from roomID, to roomID, special exit command, lockIfTrue)<br />
<br />
:Locks a given special exit, leading from one specific room to another that uses a certain command from future speed walks (thus the mapper will never path through that special exit).<br />
: See also: [[#hasSpecialExitLock | hasSpecialExitLock()]], [[#lockExit | lockExit()]], [[#lockRoom | lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2<br />
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit<br />
</syntaxhighlight><br />
<br />
==mapSymbolFontInfo==<br />
;mapSymbolFontInfo()<br />
: See also: [[#setupMapSymbolFont|setupMapSymbolFont(...)]]<br />
<br />
;returns<br />
* either a table of information about the configuration of the font used for symbols in the (2D) map, the elements are:<br />
:* ''fontName'' - a string of the family name of the font specified<br />
:* ''onlyUseThisFont'' - a boolean indicating whether glyphs from just the ''fontName'' font are to be used or if there is not a ''glyph'' for the required ''grapheme'' (''character'') then a ''glyph'' from the most suitable different font will be substituted instead. Should this be ''true'' and the specified font does not have the required glyph then the replacement character (typically something like ''�'') could be used instead. Note that this may not affect the use of Color Emoji glyphs that are automatically used in some OSes but that behavior does vary across the range of operating systems that Mudlet can be run on.<br />
:* ''scalingFactor'' - a floating point number between 0.50 and 2.00 which modifies the size of the symbols somewhat though the extremes are likely to be unsatisfactory because some of the particular symbols may be too small (and be less visible at smaller zoom levels) or too large (and be clipped by the edges of the room rectangle or circle).<br />
* or ''nil'' and an error message on failure.<br />
<br />
::As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialized, by activating a map window).<br />
<br />
{{note}} pending, not yet available.<br />
<br />
==moveMapWidget==<br />
;moveMapWidget(Xpos, Ypos)<br />
:moves the map window to the given position.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
;Parameters<br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very top. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==openMapWidget==<br />
;openMapWidget()<br />
;openMapWidget(dockingArea)<br />
;openMapWidget(Xpos, Ypos, width, height)<br />
:opens a map window with given options.<br />
<br />
: See also: [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
;Parameters<br />
{{note}} If no parameter is given the map window will be opened with the saved layout or at the right docking position (similar to clicking the icon)<br />
* ''dockingArea:''<br />
: If only one parameter is given this parameter will be a string that contains one of the possible docking areas the map window will be created in (f" floating "t" top "b" bottom "r" right and "l" left)<br />
{{note}} If 4 parameters are given the map window will be created in floating state <br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''width:''<br />
: The width map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height map window, in pixels. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==resetRoomArea==<br />
;resetRoomArea (roomID)<br />
<br />
: Unassigns the room from its given area. While not assigned, its area ID will be -1. Note that since Mudlet 3.0 the "default area" which has the id of -1 may be selectable in the area selection widget on the mapper - although there is also an option to conceal this in the settings.<br />
<br />
: See also: [[#setRoomArea | setRoomArea()]], [[#getRoomArea | getRoomArea()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetRoomArea(3143)<br />
</syntaxhighlight><br />
<br />
==resizeMapWidget==<br />
;resizeMapWidget(width, height)<br />
:resizes a map window with given width, height.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]]<br />
<br />
;Parameters<br />
* ''width:''<br />
: The width of the map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height of the map window, in pixels. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==removeCustomLine==<br />
;removeCustomLine(roomID, direction) <br />
<br />
:Removes the custom exit line that's associated with a specific exit of a room.<br />
:See also: [[#addCustomLine|addCustomLine()]], [[#getCustomLines|getCustomLines()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- remove custom exit line that starts in room 315 going north<br />
removeCustomLine(315, "n")<br />
</syntaxhighlight><br />
<br />
==removeMapEvent==<br />
;removeMapEvent (event name)<br />
<br />
:Removes the given menu entry from a mappers right-click menu. You can add custom ones with [[#addMapEvent | addMapEvent()]].<br />
: See also: [[#addMapEvent | addMapEvent()]], [[#getMapEvents | getMapEvents()]], [[#removeMapMenu | removeMapMenu()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- add one to the general menu<br />
removeMapEvent("room a") -- removes the said menu<br />
</syntaxhighlight><br />
<br />
==removeMapMenu==<br />
;removeMapMenu(menu name)<br />
<br />
:Removes the given submenu from a mappers right-click menu. You can add custom ones with [[#addMapMenu | addMapMenu()]].<br />
: See also: [[#addMapMenu | addMapMenu()]], [[#getMapMenus | getMapMenus()]], [[#removeMapEvent | removeMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Test") -- add submenu to the general menu<br />
removeMapMenu("Test") -- removes that same menu again<br />
</syntaxhighlight><br />
<br />
==removeSpecialExit==<br />
;removeSpecialExit(roomID, command) <br />
<br />
:Removes the special exit which is accessed by ''command'' from the room with the given ''roomID''.<br />
:See also: [[#addSpecialExit|addSpecialExit()]], [[#clearSpecialExits|clearSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addSpecialExit(1, 2, "pull rope") -- add a special exit from room 1 to room 2<br />
removeSpecialExit(1, "pull rope") -- removes the exit again<br />
</syntaxhighlight><br />
<br />
==roomExists==<br />
;roomExists(roomID)<br />
<br />
:Returns a boolean true/false depending if the room with that ID exists (is created) or not.<br />
<br />
==roomLocked==<br />
;locked = roomLocked(roomID)<br />
<br />
:Returns true or false whenever a given room is locked.<br />
: See also: [[#lockRoom|lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))<br />
</syntaxhighlight><br />
<br />
==saveMap==<br />
;saveMap([location], [version])<br />
<br />
:Saves the map to a given location, and returns true on success. The location folder needs to be already created for save to work. You can also save the map in the Mapper settings tab.<br />
<br />
;Parameters<br />
* ''location''<br />
: (optional) save the map to the given location if provided, or the default one otherwise.<br />
* ''version''<br />
: (optional) map version as a number to use when saving (Mudlet 3.17+)<br />
<br />
: See also: [[#loadMap|loadMap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")<br />
if not savedok then<br />
echo("Couldn't save :(\n")<br />
else<br />
echo("Saved fine!\n")<br />
end<br />
<br />
-- save with a particular map version<br />
saveMap(20)<br />
</syntaxhighlight><br />
<br />
==searchAreaUserData==<br />
:Searches Areas' User Data in a manner exactly the same as [[#searchRoomUserData|searchRoomUserData()]] does in all Rooms' User Data, refer to that command for the specific details except to replace references to rooms and room ID numbers there with areas and areas ID numbers.<br />
<br />
==searchRoom== <br />
;searchRoom (room name / room number)<br />
<br />
:Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of ''roomid = roomname''.<br />
:If you pass it a number instead of a string, it'll act like [[#getRoomName|getRoomName()]] and return you the room name.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(searchRoom("master"))<br />
{<br />
[17463] = 'in the branches of the Master Ravenwood'<br />
[3652] = 'master bedroom'<br />
[10361] = 'Hall of Cultural Masterpieces'<br />
[6324] = 'Exhibit of the Techniques of the Master Artisans'<br />
[5340] = 'office of the Guildmaster'<br />
[2004] = 'office of the guildmaster'<br />
[14457] = 'the Master Gear'<br />
[1337] = 'before the Master Ravenwood Tree'<br />
}<br />
</syntaxhighlight><br />
<br />
If no rooms are found, then an empty table is returned.<br />
<br />
{{note}} Additional parameters are available since Mudlet 3.0:<br />
<br />
;searchRoom (room name, [case-sensitive [, exact-match]])<br />
<br />
;Additional Parameters<br />
* ''case-sensitive:''<br />
: If true forces a case-sensitive search to be done on with the supplied room name argument, if false case is not considered.<br />
* ''exact-match:''<br />
: If true forces an exact match rather than a sub-string match, with a case sensitivity as set by previous option.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- shows all rooms containing these words in any case: --<br />
display(searchRoom("North road",false,false))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road",<br />
[3146] = "Bend in the North Road",<br />
[3088] = "The North Road South of Taren Ferry",<br />
[6229] = "Grassy Field By North Road"<br />
}<br />
<br />
-- shows all rooms containing these words in ONLY this case: --<br />
display(searchRoom("North road",true,false))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3117] = "North road",<br />
}<br />
<br />
-- shows all rooms containing ONLY these words in any case: --<br />
lua searchRoom("North road",false,true)<br />
{<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road"<br />
}<br />
<br />
-- shows all rooms containing ONLY these words in ONLY this case: --<br />
lua searchRoom("North road",true,true)<br />
{<br />
[3115] = "North road",<br />
[3117] = "North road"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Technically, with both options (case-sensitive and exact-match) set to true, one could just return a list of numbers as we know precisely what the string will be, but it was kept the same for maximum flexibility in user scripts.<br />
<br />
==searchRoomUserData== <br />
:A command with three variants that search though all the rooms in sequence (so '''not as fast as a user built/maintained ''index'' system''') and find/reports on the room user data stored:<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;searchRoomUserData(key, value)<br />
<br />
:Reports a (sorted) list of all room ids with user data with the given "value" for the given (case sensitive) "key". Due to the lack of previous enforcement it is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.<br />
<br />
;searchRoomUserData(key)<br />
<br />
:Reports a (sorted) list of the unique values from all rooms with user data with the given (case sensitive) "key". Due to the lack of previous enforcement it is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.<br />
<br />
;searchRoomUserData()<br />
<br />
:Reports a (sorted) list of the unique keys from all rooms with user data with any (case sensitive) "key", available since Mudlet 3.0.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- if I had stored the details of "named doors" as part of the room user data --<br />
display(searchRoomUserData("doorname_up"))<br />
<br />
--[[ could result in a list:<br />
{<br />
"Eastgate",<br />
"Northgate",<br />
"boulderdoor",<br />
"chamberdoor",<br />
"dirt",<br />
"floorboards",<br />
"floortrap",<br />
"grate",<br />
"irongrate",<br />
"rockwall",<br />
"tomb",<br />
"trap",<br />
"trapdoor"<br />
}]]<br />
<br />
-- then taking one of these keys --<br />
display(searchRoomUserData("doorname_up","trapdoor"))<br />
<br />
--[[ might result in a list:<br />
{<br />
3441,<br />
6113,<br />
6115,<br />
8890<br />
}<br />
]]</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==setAreaName==<br />
;setAreaName(areaID or areaName, newName)<br />
<br />
:Names, or renames an existing area to the new name. The area must be created first with [[#addAreaName|addAreaName()]] and it must be unique.<br />
<br />
{{note}} areaName is available since Mudlet 3.0.<br />
<br />
:See also: [[#deleteArea|deleteArea()]], [[#addAreaName|addAreaName()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setAreaName(2, "My city")<br />
<br />
-- available since Mudlet 3.0<br />
setAreaName("My old city name", "My new city name")<br />
</syntaxhighlight><br />
<br />
==setAreaUserData==<br />
;setAreaUserData(areaID, key (as a string), value (as a string))<br />
<br />
:Stores information about an area under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. Returns a lua ''true'' value on success. You can have as many keys as you'd like, however a blank key will not be accepted and will produce a lua ''nil'' and an error message instead.<br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#getAreaUserData|getAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]]<br />
<br />
{{note}} Release (not Development) version 3.0 software made this function available, but was unable to load the prerequisite map formats 17 and 18 that can store map-level data - that had been fixed in Release 3.0.1 .<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store extra area details...<br />
setAreaUserData(34, "country", "Andor.")<br />
<br />
-- or a sound file to play in the background (with a script that checks a room's area when entered)...<br />
setAreaUserData(34, "backgroundSound", "/home/user/mudlet-data/soundFiles/birdsong.mp4")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setAreaUserData(101, "some table", yajl.to_string({ruler = "Queen Morgase Trakand", clan = "Lion Warden"}))<br />
display("The ruler's name is: "..yajl.to_value(getRoomUserData(34, "some table")).ruler)<br />
</syntaxhighlight><br />
<br />
==setCustomEnvColor==<br />
;setCustomEnvColor(environmentID, r,g,b,a)<br />
<br />
:Creates, or overrides an already created custom color definition for a given environment ID. Note that this will not work on the default environment colors - those are adjustable by the user in the preferences. You can however create your own environment and use a custom color definition for it.<br />
: See also: [[#getCustomEnvColorTable|getCustomEnvColorTable()]], [[#setRoomEnv|setRoomEnv()]]<br />
<br />
{{note}} Numbers 1-16 and 257-272 are reserved by Mudlet. 257-272 are the default colors the user can adjust in mapper settings, so feel free to use them if you'd like - but don't overwrite them with this function.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200<br />
local r,g,b = unpack(color_table.blue)<br />
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue<br />
</syntaxhighlight><br />
<br />
==setDoor==<br />
;setDoor(roomID, exitCommand, doorStatus)<br />
<br />
:Creates or deletes a door in a room. Doors are purely visual - they don't affect pathfinding. You can use the information to change to adjust your speedwalking path based on the door information in a room, though.<br />
<br />
:Doors CAN be set on stub exits ''- so that map makers can note if there is an obvious door to somewhere even if they do not (yet) know where it goes, perhaps because they do not yet have the key to open it!''<br />
<br />
:Returns ''true'' if the change could be made, ''false'' if the input was valid but ineffective (door status was not changed), and ''nil'' with a message string on invalid input (value type errors).<br />
<br />
: See also: [[#getDoors|getDoors()]]<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to create the door in.<br />
* ''exitCommand:''<br />
: The cardinal direction for the door is in - it can be one of the following: '''n''', '''e''', '''s''', '''w''', '''ne''', '''se''', '''sw''', '''ne'''. ''{Plans are afoot to add support for doors on the other normal exits: '''up''', '''down''', '''in''' and '''out''', and also on special exits - though more work will be needed for them to be shown in the mapper.}'' It is important to ONLY use these direction codes as others e.g. "UP" will be accepted - because a special exit could have ANY name/lua script - but it will not be associated with the particular normal exit - recent map auditing code about to go into the code base will REMOVE door and other room exit items for which the appropriate exit (or stub) itself is not present, so in this case, in the absence of a special exit called "UP" that example door will not persist and not show on the normal "up" exit when that is possible later on.<br />
<br />
* ''doorStatus:''<br />
: The door status as a number - '''0''' means no (or remove) door, '''1''' means open door (will draw a green square on exit), '''2''' means closed door (yellow square) and '''3''' means locked door (red square). <br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- make a door on the east exit of room 4234 that is currently open<br />
setDoor(4234, 'e', 1)<br />
<br />
-- remove a door from room 923 that points north<br />
setDoor(923, 'n', 0)<br />
</syntaxhighlight><br />
<br />
==setExit==<br />
;setExit(from roomID, to roomID, direction)<br />
<br />
:Creates a one-way exit from one room to another using a standard direction - which can be either one of ''n, ne, nw, e, w, s, se, sw, u, d, in, out'', the long version of a direction, or a number which represents a direction. If there was an exit stub in that direction already, then it will be automatically deleted for you.<br />
<br />
:Returns ''false'' if the exit creation didn't work.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^exit (\d+) (\d+) (\w+)$<br />
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north<br />
<br />
if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then<br />
echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))<br />
else<br />
echo("Failed to set the exit.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
This function can also delete exits from a room if you use it like so:<br />
<br />
<syntaxhighlight lang="lua">setExit(from roomID, -1, direction)</syntaxhighlight><br />
<br />
- which will delete an outgoing exit in the specified direction from a room.<br />
<br />
==setExitStub==<br />
;setExitStub(roomID, direction, set/unset)<br />
<br />
Creates or removes an exit stub from a room in a given directions. You can use exit stubs later on to connect rooms that you're sure of are together. Exit stubs are also shown visually on the map, so the mapper can easily tell which rooms need finishing.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: The room to place an exit stub in, as a number.<br />
* ''direction:''<br />
: The direction the exit stub should lead in - as ashort direction name ("nw"), long direction name ("northwest") or a number.<br />
* ''set/unset:''<br />
: A boolean to create or delete the exit stub.<br />
<br />
: See also: [[#getExitStubs|getExitStubs()]], [[#connectExitStub|connectExitStub()]]<br />
<br />
;Example<br />
Create an exit stub to the south from room 8:<br />
<syntaxhighlight lang="lua"><br />
setExitStub(8, "s", true)<br />
</syntaxhighlight><br />
<br />
How to delete all exit stubs in a room:<br />
<syntaxhighlight lang="lua"><br />
for i,v in pairs(getExitStubs(roomID)) do<br />
setExitStub(roomID, v,false)<br />
end<br />
</syntaxhighlight><br />
<br />
==setExitWeight==<br />
;setExitWeight(roomID, exitCommand, weight)<br />
<br />
:Gives an exit a weight, which makes it less likely to be chosen for pathfinding. All exits have a weight of 0 by default, which you can increase. Exit weights are set one-way on an exit - if you'd like the weight to be applied both ways, set it from the reverse room and direction as well.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to set the weight in.<br />
* ''exitCommand:''<br />
: The direction for the exit is in - it can be one of the following: '''n''', '''ne''', '''e''', '''se''', '''s''', '''sw''', '''w''', '''nw''', '''up''', '''down''', '''in''', '''out''', or, if it's a special exit, the special exit command - note that the strings for normal exits are case-sensitive and must currently be exactly as given here.<br />
* ''weight:''<br />
: Exit weight - by default, all exits have a weight of 0 meaning that the weight of the ''destination room'' is use when the route finding code is considering whether to use that exit; setting a value for an exit can increase or decrease the chance of that exit/destination room being used for a route by the route-finding code. For example, if the destination room has very high weight compared to it's neighbors but the exit has a low value then that exit and thus the room is more likely to be used than if the exit was not weighted.<br />
<br />
: See also: [[#getExitWeights|getExitWeights()]]<br />
<br />
==setGridMode==<br />
;setGridMode(areaID, true/false)<br />
<br />
:Enables grid/wilderness view mode for an area - this will cause the rooms to lose their visible exit connections, like you'd see on compressed ASCII maps, both in 2D and 3D view mode; for the 2D map the custom exit lines will also not be shown if this mode is enabled. <br />
:Returns true if the area exists, otherwise false.<br />
<br />
: See also: [[#getGridMode|getGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
</syntaxhighlight><br />
<br />
==setMapUserData==<br />
;setMapUserData(key (as a string), value (as a string))<br />
<br />
:Stores information about the map under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearMapUserData|clearMapUserData()]], [[#clearMapUserDataItem|clearMapUserDataItem()]], [[#getAllMapUserData|getAllMapUserData()]], [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- store general meta information about the map...<br />
setMapUserData("game_name", "Achaea Mudlet map")<br />
<br />
-- or who the author was<br />
setMapUserData("author", "Bob")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setMapUserData("some table", yajl.to_string({game = "mud.com", port = 23}))<br />
display("Available game info in the map: ")<br />
display(yajl.to_value(getMapUserData("some table")))<br />
</syntaxhighlight><br />
<br />
==setMapZoom==<br />
;setMapZoom(zoom)<br />
<br />
:Zooms the map in to a given zoom level. '''1''' is the closest you can get, and anything higher than that zooms the map out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMapZoom(10) -- zoom to a somewhat acceptable level, a bit big but easily visible connections<br />
</syntaxhighlight><br />
<br />
==setRoomArea==<br />
;setRoomArea(roomID, newAreaID or newAreaName)<br />
<br />
:Assigns the given room to a new or different area. If the area is displayed in the mapper this will have the room be visually moved into the area as well.<br />
<br />
: See also: [[#resetRoomArea|resetRoomArea()]]<br />
<br />
==setRoomChar==<br />
;setRoomChar(roomID, character)<br />
<br />
:Originally designed for an area in grid mode, takes a single ASCII character and draws it on the rectangular background of the room in the 2D map. In versions prior to Mudlet 3.8, the symbol can be cleared by using "_" as the character. In Mudlet version 3.8 and higher, the symbol may be cleared with either a space <code>" "</code> or an empty string <code>""</code>.<br />
<br />
;MUD-related symbols for your map<br />
* [https://github.com/toddfast/game-icons-net-font toddfast's font] - 3000+ scalable vector RPG icons from [https://game-icons.net game-icons.net], as well as a script to download the latest icons and generate a new font.<br />
* Pixel Kitchen's [https://www.fontspace.com/donjonikons-font-f30607 Donjonikon Font] - 10x10 fantasy and RPG-related icons.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomChar(431, "#")<br />
<br />
setRoomChar(123, "$")<br />
<br />
-- emoji's work fine too, and if you'd like it coloured, set the font to Nojo Emoji in settings<br />
setRoomChar(666, "👿")<br />
</syntaxhighlight><br />
<br />
:'''Since Mudlet version 3.8 :''' this facility has been extended:<br />
:* This function will now take a short string of any printable characters as a room ''symbol'', and they will be shrunk to fit them all in horizontally but if they become too small that ''symbol'' may not be shown if the zoom is such that the room symbol is too small to be legible.<br />
:* As "_" is now a valid character an existing symbol may be erased with either a space " " or an empty string "" although neither may be effective in some previous versions of Mudlet.<br />
:* Should the rooms be set to be drawn as circles this is now accommodated and the symbol will be resized to fit the reduce drawing area this will cause.<br />
:* The range of characters that are available are now dependent on the '''fonts''' present in the system and a setting on the "Mapper" tab in the preferences that control whether a specific font is to be used for all symbols (which is best if a font is included as part of a MUD server package, but has the issue that it may not be displayable if the user does not have that font or chooses a different one) or any font in the user's system may be used (which is the default, but may not display the ''glyph'' {the particular representation of a ''grapheme'' in a particular font} that the original map creator expected). Should it not be possible to display the wanted symbol in the map because one or more of the required glyphs are not available in either the specified or any font depending on the setting then the ''replacement character'' (Unicode ''code-point'' U+FFFD '�') will be shown instead. To allow such missing symbols to be handled the "Mapper" tab on the preferences dialogue has an option to display:<br />
::* an indicator to show whether the symbol can be made just from the selected font (green tick), from the fonts available in the system (yellow warning triangle) or not at all (red cross)<br />
::* all the symbols used on the map and how they will be displayed both only using the selected font and all fonts<br />
::* the sequence of code-points used to create the symbol which will be useful when used in conjunction with character selection utilities such as ''charmap.exe'' on Windows and ''gucharmap'' on unix-like system<br />
::* a count of the rooms using the particular symbol<br />
::* a list, limited in entries of the first rooms using that symbol<br />
:* The font that is chosen to be used as the primary (or only) one for the room symbols is stored in the Mudlet map data so that setting will be included if a binary map is shared to other Mudlet users or profiles on the same system.<br />
<br />
: See also: [[#getRoomChar|getRoomChar()]]<br />
<br />
==setRoomCoordinates==<br />
;setRoomCoordinates(roomID, x, y, z)<br />
<br />
:Sets the given room ID to be at the following coordinates visually on the map, where ''z'' is the up/down level. <br />
<br />
{{note}} 0,0,0 is the center of the map.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$<br />
-- this sets the current room to the supplied coordinates<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
:You can make them relative as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^src (\w+)$<br />
<br />
local x,y,z = getRoomCoordinates(previousRoomID)<br />
local dir = matches[2]<br />
<br />
if dir == "n" then<br />
y = y+1<br />
elseif dir == "ne" then<br />
y = y+1<br />
x = x+1<br />
elseif dir == "e" then<br />
x = x+1<br />
elseif dir == "se" then<br />
y = y-1<br />
x = x+1<br />
elseif dir == "s" then<br />
y = y-1<br />
elseif dir == "sw" then<br />
y = y-1<br />
x = x-1<br />
elseif dir == "w" then<br />
x = x-1<br />
elseif dir == "nw" then<br />
y = y+1<br />
x = x-1<br />
elseif dir == "u" or dir == "up" then<br />
z = z+1<br />
elseif dir == "down" then<br />
z = z-1<br />
end<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
==setRoomEnv==<br />
;setRoomEnv(roomID, newEnvID)<br />
<br />
:Sets the given room to a new environment ID. You don't have to use any functions to create it - can just set it right away.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34<br />
</syntaxhighlight><br />
<br />
==setRoomIDbyHash==<br />
;setRoomIDbyHash(roomID, hash)<br />
<br />
:Sets the hash to be associated with the given roomID. See also [[#getRoomIDbyHash|getRoomIDbyHash()]].<br />
<br />
==setRoomName==<br />
;setRoomName(roomID, newName)<br />
<br />
:Renames an existing room to a new name.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomName(534, "That evil room I shouldn't visit again.")<br />
lockRoom(534, true) -- and lock it just to be safe<br />
</syntaxhighlight><br />
<br />
==setRoomUserData==<br />
;setRoomUserData(roomID, key (as a string), value (as a string))<br />
<br />
:Stores information about a room under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store room descriptions...<br />
setRoomUserData(341, "description", "This is a plain-looking room.")<br />
<br />
-- or whenever it's outdoors or not...<br />
setRoomUserData(341, "ourdoors", "true")<br />
<br />
-- how how many times we visited that room<br />
local visited = getRoomUserData(341, "visitcount")<br />
visited = (tonumber(visited) or 0) + 1<br />
setRoomUserData(341, "visitcount", tostring(visited))<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setRoomUserData(341, "some table", yajl.to_string({name = "bub", age = 23}))<br />
display("The denizens name is: "..yajl.to_value(getRoomUserData(341, "some table")).name)<br />
</syntaxhighlight><br />
<br />
==setRoomWeight==<br />
;setRoomWeight(roomID, weight)<br />
<br />
:Sets a weight to the given roomID. By default, all rooms have a weight of 1 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.<br />
<br />
{{note}} The minimum allowed room weight is 1. <br />
<br />
:To completely avoid a room, make use of [[#lockRoom|lockRoom()]].<br />
<br />
: See also: [[#getRoomWeight|getRoomWeight()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomWeight(1532, 3) -- avoid using this room if possible, but don't completely ignore it<br />
</syntaxhighlight><br />
<br />
<br />
==setupMapSymbolFont==<br />
;setupMapSymbolFont(fontName[, onlyUseThisFont[, scalingFactor]])<br />
:configures the font used for symbols in the (2D) map.<br />
: See also: [[#mapSymbolFontInfo|mapSymbolFontInfo()]]<br />
<br />
;Parameters<br />
* ''fontName'' one of:<br />
:* - a string that is the family name of the font to use;<br />
:* - the empty string ''""'' to reset to the default {which is '''"Bitstream Vera Sans Mono"'''};<br />
:* - a Lua ''nil'' as a placeholder to not change this parameter but still allow a following one to be modified.<br />
* ''onlyUseThisFont'' (optional) one of:<br />
:* - a Lua boolean ''true'' to require Mudlet to use graphemes (''character'') '''only''' from the selected font. Should a requested grapheme not be included in the selected font then the font replacement character (�) might be used instead; note that under some circumstances it is possible that the OS (or Mudlet) provided color Emoji Font may still be used but that cannot be guaranteed across all OS platforms that Mudlet might be run on;<br />
:* - a Lua boolean ''false'' to allow Mudlet to get a different ''glyph'' for a particular ''grapheme'' from the most suitable other font found in the system should there not be a ''glyph'' for it in the requested font. This is the default unless previously changed by this function or by the corresponding checkbox in the Profile Preferences dialogue for the profile concerned;<br />
:* - a Lua ''nil'' as a placeholder to not change this parameter but still allow the following one to be modified.<br />
* ''scalingFactor'' (optional): a floating point value in the range ''0.5'' to ''2.0'' (default ''1.0'') that can be used to tweak the rectangular space that each different room symbol is scaled to fit inside; this might be useful should the range of characters used to make the room symbols be consistently under- or over-sized.<br />
<br />
;Returns<br />
* ''true'' on success<br />
* ''nil'' and an error message on failure. As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialised, by activating a map window).<br />
<br />
{{note}} pending, not yet available.<br />
<br />
==speedwalk==<br />
;speedwalk(dirString, backwards, delay, show)<br />
<br />
:A speedwalking function will work on cardinal+ordinal directions (n, ne, e, etc.) as well as u (for up), d (for down), in and out. It can be called to execute all directions directly after each other, without delay, or with a custom delay, depending on how fast your mud allows you to walk. It can also be called with a switch to make the function reverse the whole path and lead you backwards.<br />
<br />
:Call the function by doing: <code>speedwalk("YourDirectionsString", true/false, delaytime, true/false)</code><br />
<br />
:The delaytime parameter will set a delay between each move (set it to 0.5 if you want the script to move every half second, for instance). It is optional: If you don't indicate it, the script will send all direction commands right after each other. (If you want to indicate a delay, you -have- to explicitly indicate true or false for the reverse flag.)<br />
<br />
:The show parameter will determine if the commands sent by this function are shown or hidden. It is optional: If you don't give a value, the script will show all commands sent. (If you want to use this option, you -have- to explicitly indicate true or false for the reverse flag, as well as either some number for the delay or nil if you do not want a delay.)<br />
<br />
:The "YourDirectionsString" contains your list of directions and steps (e.g.: "2n, 3w, u, 5ne"). Numbers indicate the number of steps you want it to walk in the direction specified after it. The directions must be separated by anything other than a letter that can appear in a direction itself. (I.e. you can separate with a comma, spaces, the letter x, etc. and any such combinations, but you cannot separate by the letter "e", or write two directions right next to each other with nothing in-between, such as "wn". If you write a number before every direction, you don't need any further separator. E.g. it's perfectly acceptable to write "3w1ne2e".) The function is not case-sensitive.<br />
<br />
:If your Mud only has cardinal directions (n,e,s,w and possibly u,d) and you wish to be able to write directions right next to each other like "enu2s3wdu", you'll have to change the pattern slightly. Likewise, if your Mud has any other directions than n, ne, e, se, s, sw, w, nw, u, d, in, out, the function must be adapted to that.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
speedwalk("16d1se1u")<br />
-- Will walk 16 times down, once southeast, once up. All in immediate succession.<br />
<br />
speedwalk("2ne,3e,2n,e")<br />
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.<br />
<br />
speedwalk("IN N 3W 2U W", false, 0.5)<br />
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.<br />
<br />
speedwalk("5sw - 3s - 2n - w", true)<br />
-- Will walk backwards: east, twice south, thrice, north, five times northeast. All in immediate succession.<br />
<br />
speedwalk("3w, 2ne, w, u", true, 1.25)<br />
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.<br />
</syntaxhighlight><br />
<br />
{{note}} The probably most logical usage of this would be to put it in an alias. For example, have the pattern ''^/(.+)$'' execute: <code>speedwalk(matches[2], false, 0.7)</code><br />
And have ''^//(.+)$'' execute: <code>speedwalk(matches[2], true, 0.7)</code><br />
Or make aliases like: ''^banktohome$'' to execute <syntaxhighlight lang="lua" inline>speedwalk("2ne,e,ne,e,3u,in", true, 0.5)</syntaxhighlight><br />
<br />
{{note}} The show parameter for this function will be available in Mudlet versions after 3.12.<br />
<br />
==unHighlightRoom==<br />
;unHighlightRoom(roomID)<br />
<br />
:Unhighlights a room if it was previously highlighted and restores the rooms original environment color.<br />
: See also: [[#highlightRoom|highlightRoom()]]<br />
<br />
{{note}} Available since Mudlet 2.0 final release<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
unHighlightRoom(4534)<br />
</syntaxhighlight><br />
<br />
==updateMap==<br />
;updateMap()<br />
<br />
:Updates the mapper display (redraws it). Use this function if you've edited the map via script and would like the changes to show.<br />
<br />
: See also: [[#centerview|centerview()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete a some room<br />
deleteRoom(500)<br />
-- now make the map show that it's gone<br />
updateMap()<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Mapper_Functions&diff=15854Manual:Mapper Functions2020-11-10T13:25:35Z<p>RodeoS: /* addMapEvent */</p>
<hr />
<div>{{TOC right}}<br />
= Mapper Functions =<br />
These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be MUD-generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the MUD you're playing. For a collection of pre-made scripts and general mapper talk, visit the [http://forums.mudlet.org/viewforum.php?f=13 mapper section] of the forums.<br />
<br />
To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
==addAreaName==<br />
;areaID = addAreaName(areaName)<br />
<br />
:Adds a new area name and returns the new (positive) area ID for the new name. If the name already exists, older versions of Mudlet returned -1 though since 3.0 the code will return ''nil'' and an error message.<br />
: See also: [[#deleteArea|deleteArea()]], [[#addRoom|addRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local newId, err = addAreaName(string.random(10))<br />
<br />
if newId == nil or newId < 1 or err then<br />
echo("That area name could not be added - error is: ".. err.."\n")<br />
else<br />
cecho("<green>Created new area with the ID of "..newId..".\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==addCustomLine==<br />
;addCustomLine(roomID, id_to, direction, style, color, arrow)<br />
: See also: [[#getCustomLines|getCustomLines()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Adds a new/replaces an existing custom exit line to the 2D mapper for the room with the Id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to attach the custom line to.<br />
* ''id_to:''<br />
: EITHER: a room Id number, of a room on same area who's x and y coordinates are used as the other end of a SINGLE segment custom line (it does NOT imply that is what the exit it represent goes to, just the location of the end of the line);<br />
: OR: a table of sets of THREE (x,y and z) coordinates in that order, x and y can be decimals, z is an integer ('''and must be present and be the same for all points on the line''', though it is irrelevant to what is produced as the line is drawn on the same z-coordinate as the room that the line is attached to!)<br />
* ''direction:'' a string to associate the line with a valid exit direction, "n", "ne", "e", "se", "s", "sw", "w", "nw", "up", "down", "in" or "out" or a special exit (before Mudlet 3.17 this was case-sensitive and cardinal directions had to be uppercase).<br />
* ''style:'' a string, one of: "solid line", "dot line", "dash line", "dash dot line" or "dash dot dot line" exactly.<br />
* ''color:'' a table of three integers between 0 and 255 as the custom line color as the red, green and blue components in that order.<br />
* ''arrow:'' a boolean which if true will set the custom line to have an arrow on the end of the last segment.<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- create a line from roomid 1 to roomid 2<br />
addCustomLine(1, 2, "N", "dot line", {0, 255, 255}, true)<br />
<br />
addCustomLine(1, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
</syntaxhighlight><br />
<br />
A bigger example that'll create a new area and the room in it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local areaid = addAreaName("my first area")<br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
setRoomArea(newroomid, "my first area")<br />
setRoomCoordinates(newroomid, 0, 0, 0)<br />
<br />
addCustomLine(newroomid, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
<br />
centerview(newroomid)<br />
</syntaxhighlight><br />
<br />
Note: At the time of writing there is no Lua command to remove a custom exit line and, for Normal exits in the X-Y plane, revert to the standard straight line between the start room and the end room (or colored arrow for out of area exits) however this can be done from the GUI interface to the 2D mapper.<br />
<br />
==addMapEvent==<br />
;addMapEvent(uniquename, event name, parent, display name, arguments)<br />
<br />
:Adds a new entry to an existing mapper right-click entry. You can add one with addMapMenu. If there is no display name, it will default to the unique name (which otherwise isn't shown and is just used to differentiate this entry from others). ''event name'' is the Mudlet event that will be called when this is clicked on, and ''arguments'' will be passed to the handler function.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn") <br />
</syntaxhighlight><br />
The last line will make a label "Special Room!" under the "Favorites" menu that on clicking will send all the arguments.<br />
<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Room type") <br />
addMapEvent("markRoomsAsDeathTrap","onMapMarkSelectedRooms","Room type","Mark selected rooms as Death Trap","DeathTrap") <br />
addMapEvent("markRoomsAsOneRoom","onMapMarkSelectedRooms","Room type","Mark selected rooms as single-pass","single-pass")<br />
<br />
function onMapMarkSelectedRooms(event, MarkRoomType)<br />
local SelectedRooms=getMapSelection()["rooms"]<br />
for i, val in ipairs(SelectedRooms) do<br />
if MarkRoomType=="DeathTrap" then<br />
local r,g,b = unpack(color_table.black)--death trap<br />
setRoomEnv(val, 300)--death traps Env<br />
setCustomEnvColor(300, r,g,b,255) <br />
setRoomChar(val, "☠️")<br />
lockRoom(val, true)<br />
end<br />
if MarkRoomType=="single-pass" then<br />
local r,g,b = unpack(color_table.LightCoral)--single-pass<br />
setRoomEnv(val, 301)--one room Env<br />
setCustomEnvColor(301, r,g,b,255) <br />
setRoomChar(val, "🚹")<br />
end<br />
end<br />
end<br />
<br />
registerAnonymousEventHandler("onMapMarkSelectedRooms", "onMapMarkSelectedRooms")<br />
</syntaxhighlight><br />
This create menu and two submenu options: "Mark selected rooms as Death Trap" and "Mark selected rooms as single-pass"<br />
<br />
==addMapMenu==<br />
;addMapMenu(uniquename, parent, display name)<br />
<br />
:Adds a new submenu to the right-click menu that opens when you right-click on the mapper. You can then add more submenus to it, or add entries with [[#addMapEvent|addMapEvent()]].<br />
: See also: [[#addMapEvent|addMapEvent()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- This will create a menu named: Favorites.<br />
addMapMenu("Favorites")<br />
<br />
-- This will create a submenu with the unique id 'Favorites123' under 'Favorites' with the display name of 'More Favorites'.<br />
addMapMenu("Favorites1234343", "Favorites", "More Favorites") <br />
</syntaxhighlight><br />
<br />
==addRoom==<br />
;addRoom(roomID)<br />
<br />
:Creates a new room with the given ID, returns true if the room was successfully created. <br />
<br />
{{note}} If you're not using incremental room IDs but room IDs stitched together from other factors or in-game hashes for room IDs - and your room IDs are starting off at 250+million numbers, you need to look into incrementally creating Mudlets room IDs with [[#createRoomID|createRoomID()]] and associating your room IDs with Mudlets via [[#setRoomIDbyHash|setRoomIDbyHash()]] and [[#getRoomIDbyHash|getRoomIDbyHash()]]. The reason being is that Mudlet's A* pathfinding implementation from boost cannot deal with extremely large room IDs because the resulting matrices it creates for pathfinding are enormously huge.<br />
: See also: [[#createRoomID|createRoomID()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
</syntaxhighlight><br />
<br />
==addSpecialExit==<br />
;addSpecialExit(roomIDFrom, roomIDTo, moveCommand)<br />
<br />
:Creates a one-way from one room to another, that will use the given command for going through them.<br />
: See also: [[#clearSpecialExits|clearSpecialExits()]], [[#removeSpecialExit|removeSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- add a one-way special exit going from room 1 to room 2 using the 'pull rope' command<br />
addSpecialExit(1, 2, "pull rope")<br />
</syntaxhighlight><br />
<br />
Example in an alias:<br />
<syntaxhighlight lang="lua"><br />
-- sample alias pattern: ^spe (\d+) (.*?)$<br />
-- currentroom is your current room ID in this example<br />
addSpecialExit(currentroom,tonumber(matches[2]), matches[3])<br />
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])<br />
centerview(currentroom)<br />
</syntaxhighlight><br />
<br />
==centerview==<br />
;centerview (roomID)<br />
<br />
:Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.<br />
<br />
: See also: [[#getPlayerRoom|getPlayerRoom()]], [[#updateMap|updateMap()]]<br />
<br />
==clearAreaUserData==<br />
;clearAreaUserData(areaID)<br />
<br />
; Parameter<br />
* areaID - ID number for area to clear.<br />
<br />
:Clears all user data from a given area. Note that this will not touch the room user data.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#clearRoomUserData|clearRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearAreaUserData(34))<br />
-- I did have data in that area, so it returns:<br />
true<br />
<br />
display(clearAreaUserData(34))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==clearAreaUserDataItem==<br />
;clearAreaUserDataItem(areaID, key)<br />
<br />
:Removes the specific key and value from the user data from a given area.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#clearAreaUserData|clearAreaUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
true<br />
<br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserData==<br />
;clearMapUserData()<br />
<br />
:Clears all user data stored for the map itself. Note that this will not touch the area or room user data.<br />
<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserData|clearAreaUserData()]]<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearMapUserData())<br />
-- I did have user data stored for the map, so it returns:<br />
true<br />
<br />
display(clearMapUserData())<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserDataItem==<br />
;clearUserDataItem(mapID, key)<br />
<br />
:Removes the specific key and value from the user data from the map user data.<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearMapUserData|clearMapUserData()]], [[#clearAreaRoomUserData|clearAreaRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
last_modified = "1483228799"<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
true<br />
<br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==clearRoomUserData==<br />
;clearRoomUserData(roomID)<br />
<br />
:Clears all user data from a given room.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]:<br />
<br />
{{note}} Returns a boolean true if any data was removed from the specified room and false if there was nothing to erase since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearRoomUserData(3441))<br />
-- I did have data in that room, so it returns:<br />
true<br />
<br />
display(clearRoomUserData(3441))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearRoomUserDataItem==<br />
;clearRoomUserDataItem(roomID, key)<br />
<br />
:Removes the specific key and value from the user data from a given room.<br />
:Returns a boolean true if data was found against the give key in the user data for the given room and it is removed, will return false if exact key not present in the data. Returns nil if the room for the roomID not found.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
true<br />
<br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0+<br />
<br />
==clearSpecialExits==<br />
;clearSpecialExits(roomID) <br />
<br />
:Removes all special exits from a room.<br />
: See also: [[#addSpecialExit|addSpecialExit()]], [[#removeSpecialExit|removeSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
clearSpecialExits(1337)<br />
<br />
if #getSpecialExits(1337) == 0 then -- clearSpecialExits will never fail on a valid room ID, this is an example<br />
echo("All special exits successfully cleared from 1337.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==closeMapWidget==<br />
;closeMapWidget()<br />
:closes (hides) the map window (similar to clicking on the map icon)<br />
<br />
{{note}} available in Mudlet 4.7+<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
==connectExitStub==<br />
;connectExitStub(fromID, direction) or connectExitStub(fromID, toID, [direction])<br />
<br />
:Connects existing rooms with matching exit stubs. If you only give it a roomID and a direction, it'll work out which room should be linked to it that has an appropriate opposite exit stub and is located in the right direction. You can also just specify from and to room IDs, and it'll smartly use the right direction to link in. Lastly, you can specify all three arguments - fromID, toID and the direction (in that order) if you'd like to be explicit, or use [[#setExit|setExit()]] for the same effect.<br />
<br />
;Parameters<br />
* ''fromID:''<br />
: Room ID to set the exit stub in.<br />
* ''direction:''<br />
: You can either specify the direction to link the room in, and/or a specific room ID (see below). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
* ''toID:''<br />
: The room ID to link this room to. If you don't specify it, the mapper will work out which room should be logically linked.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try and connect all stubs that are in a room<br />
local stubs = getExitStubs(roomID)<br />
if stubs then<br />
for i,v in pairs(stubs) do<br />
connectExitStub(roomID, v)<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==createMapLabel==<br />
;labelID = createMapLabel(areaID, text, posx, posy, posz, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue, zoom, fontSize, showOnTop, noScaling)<br />
<br />
:Creates a text label on the map at given coordinates, with the given background and foreground colors. It can go above or below the rooms, scale with zoom or stay a static size. It returns a label ID that you can use later for deleting it.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
<br />
: See also: [[#getMapLabel|getMapLabel()]], [[#getMapLabels|getMapLabels()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID where to put the label.<br />
* ''text:''<br />
: The text to put into the label. To get a multiline text label add a '\n' between the lines.<br />
* ''posx, posy, posz:''<br />
: Position of the label in room coordinates.<br />
* ''fgRed, fgGreen fgBlue:''<br />
: Foreground color or text color of the label.<br />
* ''bgRed, bgGreen bgBlue:''<br />
: Background color of the label.<br />
* ''zoom:''<br />
: Zoom factor of the label if noScaling is false. Higher zoom will give higher resolution of the text and smaller size of the label. Default is 30.0.<br />
* ''fontSize:''<br />
: Size of the font of the text. Default is 50.<br />
* ''showOnTop:''<br />
: If true the label will be drawn on top of the rooms and if it is false the label will be drawn as a background.<br />
* ''noScaling:''<br />
: If true the label will have the same size when you zoom in and out in the mapper. If it is false the label will scale when you zoom the mapper. <br />
<br />
: See also: [[#deleteMapLabel|deleteMapLabel]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- the first 50 is some area id, the next three 0,0,0 are coordinates - middle of the area<br />
-- 255,0,0 would be the foreground in RGB, 23,0,0 would be the background RGB<br />
-- zoom is only relevant when when you're using a label of a static size, so we use 0<br />
-- and we use a font size of 20 for our label, which is a small medium compared to the map<br />
local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)<br />
<br />
-- to create a multi line text label we add '\n' between lines<br />
-- the position is placed somewhat to the northeast of the center of the map<br />
-- this label will be scaled as you zoom the map.<br />
local labelid = createMapLabel( 50, "1. Row One\n2. Row 2", .5,5.5,0, 255,0,0, 23,0,0, 30,50, true,false)<br />
<br />
</syntaxhighlight><br />
<br />
==createMapImageLabel==<br />
;labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop)<br />
<br />
:Creates an image label on the map at the given coordinates, with the given dimensions and zoom. You might find the default room and image size correlation to be too big - try reducing the width and height of the image then, while also zooming in the same amount.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
: See also: [[#deleteMapLabel|deleteMapLabel]]<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
-- 138 is our pretend area ID<br />
-- next, inside [[]]'s, is the exact location of our image<br />
-- 0,0,0 are the x,y,z coordinates - so this will place it in the middle of the map<br />
-- 482 is the width of the image - we divide it by 100 to scale it down, and then we'll zoom it by 100 - making the image take up about 4 rooms in width then<br />
-- 555 is the original height of the image<br />
-- 100 is how much we zoom it by, 1 would be no zoom<br />
-- and lastly, false to make it go below our rooms<br />
createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false)<br />
</syntaxhighlight><br />
<br />
==createMapper==<br />
;createMapper([name of userwindow], x, y, width, height)<br />
<br />
:Creates a miniconsole window for the mapper to render in, the with the given dimensions. You can only create one mapper at a time, and it is not currently possible to have a label on or under the mapper - otherwise, clicks won't register.<br />
<br />
{{note}}<br />
userwindow argument only available in 4.6.1+<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
createMapper(0,0,300,300) -- creates a 300x300 mapper in the top-left corner of Mudlet<br />
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- another example:<br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
<br />
{{Note}} If this command is ''not'' used then clicking on the Main Toolbar's '''Map''' button will create a dock-able widget (that can be floated free to anywhere on the Desktop, it can be resized and does not have to even reside on the same monitor should there be multiple screens in your system). Further clicks on the '''Map''' button will toggle between showing and hiding the map whether it was created using the ''createMapper'' function or as a dock-able widget.<br />
<br />
==createRoomID==<br />
;usableId = createRoomID([minimumStartingRoomId])<br />
<br />
:Returns the lowest possible room ID you can use for creating a new room. If there are gaps in room IDs your map uses it, this function will go through the gaps first before creating higher IDs. <br />
<br />
;Parameters<br />
* ''minimumStartingRoomId'' (optional):<br />
: If provided, specifies a roomID to start searching for an empty one at, instead of 1. Useful if you'd like to ensure certain areas have specific room number ranges, for example. If you you're working with a huge map, provide the last used room ID to this function for an available roomID to be found a lot quicker.<br />
<br />
{{note}} ''minimumStartingRoomId'' is available since Mudlet 3.0.<br />
<br />
: See also: [[#addRoom|addRoom()]]<br />
<br />
==deleteArea==<br />
;deleteArea(areaID or areaName)<br />
<br />
:Deletes the given area and all rooms in it. Returns ''true'' on success or ''nil'' + ''error message'' otherwise.<br />
: See also: [[#addAreaName|addAreaName()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to delete.<br />
* ''areaName:''<br />
: Area name to delete (available since Mudlet 3.0).<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete by areaID<br />
deleteArea(23)<br />
-- or since Mudlet 3.0, by area name<br />
deleteArea("Big city")<br />
</syntaxhighlight><br />
<br />
==deleteMapLabel==<br />
;deleteMapLabel(areaID, labelID)<br />
<br />
:Deletes a map label from a specfic area.<br />
: See also: [[#createMapLabel|createMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteMapLabel(50, 1)<br />
</syntaxhighlight><br />
<br />
==deleteRoom==<br />
;deleteRoom(roomID)<br />
<br />
:Deletes an individual room, and unlinks all exits leading to and from it.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteRoom(335)<br />
</syntaxhighlight><br />
<br />
==exportAreaImage==<br />
;exportAreaImage(areaID)<br />
<br />
:Exports the area as an image into your profile's directory.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- save the area with ID 1 as a map<br />
exportAreaImage(1)<br />
</syntaxhighlight><br />
<br />
{{note}} This command is currently inoperable in current 3.0+ versions of Mudlet.<br />
<br />
==getAllAreaUserData==<br />
;dataTable = getAllAreaUserData(areaID)<br />
<br />
:Returns all the user data items stored in the given area ID; will return an empty table if there is no data stored or nil if there is no such area with that ID.<br />
<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
--might result in:--<br />
{<br />
country = "Andor",<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0.<br />
<br />
==getAllMapUserData==<br />
;dataTable = getAllMapUserData()<br />
<br />
:Returns all the user data items stored at the map level; will return an empty table if there is no data stored.<br />
<br />
: See also: [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
--might result in:--<br />
{<br />
description = [[This map is about so and so game]],<br />
author = "Bob",<br />
["last updated"] = "December 5, 2020"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0+<br />
<br />
==getAllRoomEntrances==<br />
;exitsTable = getAllRoomEntrances(roomID)<br />
<br />
:Returns an indexed list of normal and special exits leading into this room. In case of two-way exits, this'll report exactly the same rooms as [[#getRoomExits|getRoomExits()]], but this function has the ability to pick up one-way exits coming into the room as well.<br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- print the list of rooms that have exits leading into room 512<br />
for _, roomid in ipairs(getAllRoomEntrances(512)) do <br />
print(roomid)<br />
end<br />
</syntaxhighlight><br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
==getAllRoomUserData==<br />
;dataTable = getAllRoomUserData(roomID)<br />
<br />
:Returns all the user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
: See also: [[#getRoomUserDataKeys|getRoomUserDataKeys()]] - for a related command that only returns the data keys.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
--might result in:--<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0.<br />
<br />
==getAreaExits==<br />
;roomTable = getAreaExits(areaID, showExits)<br />
<br />
: Returns a table (indexed or key-value) of the rooms in the given area that have exits leading out to other areas - that is, border rooms.<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to list the exits for.<br />
* ''showExits:''<br />
: Boolean argument, if true then the exits that lead out to another area will be listed for each room.<br />
<br />
: See also: [[#setExit|setExit()]], [[#getRoomExits|getRoomExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- list all border rooms for area 44:<br />
getAreaExits(44)<br />
<br />
-- returns:<br />
--[[<br />
{<br />
7091,<br />
10659,<br />
11112,<br />
11122,<br />
11133,<br />
11400,<br />
12483,<br />
24012<br />
}<br />
]]<br />
<br />
-- list all border rooms for area 44, and the exits within them that go out to other areas:<br />
getAreaExits(44, true)<br />
--[[<br />
{<br />
[12483] = {<br />
north = 27278<br />
},<br />
[11122] = {<br />
["enter grate"] = 14551<br />
},<br />
[11112] = {<br />
["enter grate"] = 14829<br />
},<br />
[24012] = {<br />
north = 22413<br />
},<br />
[11400] = {<br />
south = 10577<br />
},<br />
[11133] = {<br />
["enter grate"] = 15610<br />
},<br />
[7091] = {<br />
down = 4411<br />
},<br />
[10659] = {<br />
["enter grate"] = 15510<br />
}<br />
}<br />
]]<br />
</syntaxhighlight><br />
<br />
==getAreaRooms==<br />
;getAreaRooms(area id)<br />
<br />
:Returns an indexed table with all rooms IDs for a given area ID (room IDs are values), or ''nil'' if no such area exists. <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- using the sample findAreaID() function defined in the getAreaTable() example, <br />
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID<br />
function echoRoomList(areaname)<br />
local id, msg = findAreaID(areaname)<br />
if id then<br />
local roomlist, endresult = getAreaRooms(id), {}<br />
<br />
-- obtain a room list for each of the room IDs we got<br />
for _, id in pairs(roomlist) do<br />
endresult[id] = getRoomName(id)<br />
end<br />
<br />
-- now display something half-decent looking<br />
cecho(string.format(<br />
"List of all rooms in %s (%d):\n", msg, table.size(endresult)))<br />
<br />
for roomid, roomname in pairs(endresult) do<br />
cecho(string.format(<br />
"%6s: %s\n", roomid, roomname))<br />
end<br />
elseif not id and msg then<br />
echo("ID not found; " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTable==<br />
;areaTable = getAreaTable()<br />
<br />
:Returns a key(area name)-value(area id) table with all known areas and their IDs. Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
: See also: [[#getAreaTableSwap|getAreaTableSwap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example function that returns the area ID for a given area<br />
<br />
function findAreaID(areaname)<br />
local list = getAreaTable()<br />
<br />
-- iterate over the list of areas, matching them with substring match. <br />
-- if we get match a single area, then return it's ID, otherwise return<br />
-- 'false' and a message that there are than one are matches<br />
local returnid, fullareaname<br />
for area, id in pairs(list) do<br />
if area:find(areaname, 1, true) then<br />
if returnid then return false, "more than one area matches" end<br />
returnid = id; fullareaname = area<br />
end<br />
end<br />
<br />
return returnid, fullareaname<br />
end<br />
<br />
-- sample use:<br />
local id, msg = findAreaID("blahblah")<br />
if id then<br />
echo("Found a matching ID: " .. id)<br />
elseif not id and msg then<br />
echo("ID not found: " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTableSwap==<br />
;areaTable = getAreaTableSwap()<br />
<br />
:Returns a key(area id)-value(area name) table with all known areas and their IDs. Unlike getAreaTable which won't show you all areas with the same name by different IDs, this function will. Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
==getAreaUserData==<br />
;dataValue = getAreaUserData(areaID, key)<br />
<br />
:Returns a specific data item stored against the given key for the given area ID number. This is very like the corresponding Room User Data command but intended for per area rather than for per room data (for storage of data relating to the whole map see the corresponding Map User Data commands.) <br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or a Lua ''nil'' and an error message if the key is not present in the Area User Data for the given Area ID. Use [[#setAreaUserData|setAreaUserData()]] function for storing the user data.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAreaUserData(34, "country"))<br />
-- might produce --<br />
"Andor"<br />
</syntaxhighlight><br />
<br />
{{note}} <br />
<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
==getCustomEnvColorTable==<br />
;envcolors = getCustomEnvColorTable()<br />
<br />
:Returns a table with customized environments, where the key is the environment ID and the value is a indexed table of rgb values.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
{<br />
envid1 = {r,g,b},<br />
envid2 = {r,g,b}<br />
}<br />
</syntaxhighlight><br />
<br />
==getCustomLines==<br />
;lineTable = getCustomLines(roomID)<br />
: See also: [[#addCustomLine|addCustomLine()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Returns a table including all the details of the custom exit lines, if any, for the room with the id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to return the custom line details of.<br />
<br />
{{note}} <br />
Available since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display getCustomLines(1)<br />
{<br />
["climb Rope"] = {<br />
attributes = {<br />
color = {<br />
b = 0,<br />
g = 128,<br />
r = 128<br />
},<br />
style = "dash dot dot line",<br />
arrow = false<br />
},<br />
points = {<br />
{<br />
y = 9.5,<br />
x = 4.5<br />
},<br />
{<br />
y = 9.5,<br />
x = 6<br />
},<br />
[0] = {<br />
y = 5.5,<br />
x = 4.5<br />
}<br />
}<br />
},<br />
N = {<br />
attributes = {<br />
color = {<br />
b = 255,<br />
g = 255,<br />
r = 0<br />
},<br />
style = "dot line",<br />
arrow = true<br />
},<br />
points = {<br />
[0] = {<br />
y = 27,<br />
x = -3<br />
}<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
==getDoors==<br />
;doors = getDoors(roomID)<br />
<br />
:Returns a key-value table with the cardinal direction as the key and the door value as a number. If there are no doors in a room, it returns an empty table.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to check for doors in.<br />
<br />
: See also: [[#setDoor|setDoor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- an example that displays possible doors in room 2334<br />
local doors = getDoors(2334)<br />
<br />
if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end<br />
<br />
local door_status = {"open", "closed", "locked"}<br />
<br />
for direction, door in pairs(doors) do<br />
cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")<br />
end<br />
</syntaxhighlight><br />
<br />
==getExitStubs==<br />
;stubs = getExitStubs(roomid)<br />
<br />
:Returns an indexed table (starting at 0) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#connectExitStub|connectExitStub()]], [[#getExitStubs1|getExitStubs1()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(stubs[i]) end<br />
</syntaxhighlight><br />
<br />
{{note}} Previously would throw a lua error on non-existent room - now returns nil plus error message (as does other run-time errors) - previously would return just a nil on NO exit stubs but now returns a notification error message as well, to aide disambiguation of the nil value.<br />
<br />
==getExitStubs1==<br />
;stubs = getExitStubs1(roomid)<br />
<br />
:Returns an indexed table (starting at 1) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping. As this function starts indexing from 1 as it is default in Lua, you can use ipairs() to iterate over the results.<br />
<br />
; See also: [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
for k,v in ipairs(getExitStubs1(6)) do print(k,v) end<br />
</syntaxhighlight><br />
<br />
==getExitWeights==<br />
;weights = getExitWeights(roomid)<br />
<br />
:Returns a key-value table of the exit weights that a room has, with the direction or special exit as a key and the value as the exit weight. If a weight for a direction wasn't yet set, it won't be listed.<br />
<br />
;Parameters<br />
* ''roomid:''<br />
: Room ID to view the exit weights in.<br />
<br />
: See also: [[#setExitWeight|setExitWeight()]]<br />
<br />
==getGridMode==<br />
;TrueOrFalse = getGridMode(areaID)<br />
<br />
:Use this to see, if a specific area has grid/wilderness view mode set. This way, you can also calculate from a script, how many grid areas a map has got in total.<br />
<br />
{{note}} <br />
Available since Mudlet 3.11<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID (number) to view the grid mode of.<br />
<br />
: See also: [[#setGridMode|setGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getGridMode(55)<br />
-- will return: false<br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
getGridMode(55)<br />
-- will return: true<br />
</syntaxhighlight><br />
<br />
==getMapEvents==<br />
; mapevents = getMapEvents()<br />
<br />
: Returns a list of map events currently registered. Each event is a dictionary with the keys ''uniquename'', ''parent'', ''event name'', ''display name'', and ''arguments'', which correspond to the arguments of ''addMapEvent()''.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#addMapEvent|addMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")<br />
<br />
local mapEvents = getMapEvents()<br />
for _, event in ipairs(mapEvents) do<br />
echo(string.format("MapEvent '%s' is bound to event '%s' with these args: '%s'", event["uniquename"], event["event name"], table.concat(event["arguments"], ",")))<br />
end<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.3<br />
<br />
==getMapLabel==<br />
;labelinfo = getMapLabels(areaID, labelID)<br />
<br />
:Returns a key-value table describing that particular label in an area. Keys it contains are the ''X'', ''Y'', ''Z'' coordinates, ''Height'' and ''Width'', and the ''Text'' it contains. If the label is an image label, then ''Text'' will be set to the ''no text'' string.<br />
<br />
: See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabels|getMapLabels()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lua getMapLabels(1658987)<br />
table {<br />
1: 'no text'<br />
0: 'test'<br />
}<br />
<br />
lua getMapLabel(1658987, 0)<br />
table {<br />
'Y': -2<br />
'X': -8<br />
'Z': 11<br />
'Height': 3.9669418334961<br />
'Text': 'test'<br />
'Width': 8.6776866912842<br />
}<br />
<br />
lua getMapLabel(1658987, 1)<br />
table {<br />
'Y': 8<br />
'X': -15<br />
'Z': 11<br />
'Height': 7.2520666122437<br />
'Text': 'no text'<br />
'Width': 11.21900844574<br />
}<br />
<br />
<br />
</syntaxhighlight><br />
<br />
==getMapLabels==<br />
;arealabels = getMapLabels(areaID)<br />
<br />
:Returns an indexed table (that starts indexing from 0) of all of the labels in the area, plus their label text. You can use the label id to [[#deleteMapLabel|deleteMapLabel()]] it.<br />
:If there are no labels in the area at all, will instead return the area number.<br />
<br />
: See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabel|getMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapLabels(43))<br />
table {<br />
0: ''<br />
1: 'Waterways'<br />
}<br />
<br />
deleteMapLabel(43, 0)<br />
display(getMapLabels(43))<br />
table {<br />
1: 'Waterways'<br />
}<br />
</syntaxhighlight><br />
<br />
==getMapSelection==<br />
; getMapSelection()<br />
<br />
:Returns a table containing details of the current mouse selection in the 2D mapper.<br />
<br />
:Reports on one or more rooms being selected (i.e. they are highlighted in orange).<br />
<br />
:The contents of the table will vary depending on what is currently selected. If the selection is of map rooms then there will be keys of ''center'' and ''rooms'': the former will indicates the center room (the one with the yellow cross-hairs) if there is more than one room selected or the only room if there is only one selected (there will not be cross-hairs in that case); the latter will contain a list of the one or more rooms.<br />
<br />
; Example - several rooms selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5011,<br />
5012,<br />
5013,<br />
5014,<br />
5018,<br />
5019,<br />
5020<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - one room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5013<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - no or something other than a room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
}<br />
</syntaxhighlight><br />
<br />
{{Note}} Available in Mudlet 3.17+<br />
<br />
==getMapUserData==<br />
;getMapUserData( key )<br />
<br />
;Parameters<br />
* ''key:''<br />
: string used as a key to select the data stored in the map as a whole.<br />
<br />
:Returns the user data item (string); will return a nil+error message if there is no data with such a key in the map data.<br />
<br />
: See also: [[#getAllMapUserData|getAllMapUserData()]], [[#setMapUserData|setMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapUserData("last updated"))<br />
--might result in:--<br />
"December 5, 2020"<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.0<br />
<br />
==getPath==<br />
;getPath(roomID from, roomID to)<br />
<br />
:Returns a boolean true/false if a path between two room IDs is possible. If it is, the global ''speedWalkDir'' table is set to all of the directions that have to be taken to get there, and the global ''speedWalkPath'' table is set to all of the roomIDs you'll encounter on the way, and as of 3.0, ''speedWalkWeight'' will return all of the room weights. Additionally returns the total cost (all weights added up) of the path after the boolean argument in 3.0.<br />
<br />
<br />
: See also: [[Manual:Lua_Functions#translateTable()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if we can go to room 155 from room 34 - if yes, go to it<br />
if getPath(34,155) then<br />
gotoRoom(155)<br />
else<br />
echo("\nCan't go there!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPlayerRoom==<br />
;getPlayerRoom()<br />
<br />
:Returns the current player location as set by [[#centerview|centerview()]].<br />
<br />
: See also: [[#centerview|centerview]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("We're currently in " .. getRoomName(getPlayerRoom()))<br />
</syntaxhighlight><br />
<br />
{{note}} Available in Mudlet 3.14<br />
<br />
==getRoomArea==<br />
;getRoomArea(roomID)<br />
<br />
:Returns the area ID of a given room ID. To get the area name, you can check the area ID against the data given by [[#getAreaTable | getAreaTable()]] function, or use the [[#getRoomAreaName |getRoomAreaName()]] function.<br />
<br />
{{note}} If the room ID does not exist, this function will raise an error.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Area ID of room #100 is: "..getRoomArea(100))<br />
<br />
display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))<br />
</syntaxhighlight><br />
<br />
==getRoomAreaName==<br />
;getRoomAreaName(areaID or areaName)<br />
<br />
:Returns the area name for a given area id; or the area id for a given area name.<br />
<br />
{{note}} Despite the name, this function will not return the area name for a given ''room'' id (or room name) directly. However, renaming or revising it would break existing scripts.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))<br />
</syntaxhighlight><br />
<br />
<br />
==getRoomChar==<br />
;getRoomChar(roomID)<br />
<br />
:Returns the single ASCII character that forms the ''symbol'' for the given room id.<br />
<br />
: '''Since Mudlet version 3.8 :''' this facility has been extended:<br />
: Returns the string (UTF-8) that forms the ''symbol'' for the given room id; this may have been set with either [[#setRoomChar|setRoomChar()]] or with the ''symbol'' (was ''letter'' in prior versions) context menu item for rooms in the 2D Map.<br />
<br />
==getRoomCoordinates==<br />
;x,y,z = getRoomCoordinates(roomID)<br />
<br />
:Returns the room coordinates of the given room ID.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local x,y,z = getRoomCoordinates(roomID)<br />
echo("Room Coordinates for "..roomID..":")<br />
echo("\n X:"..x)<br />
echo("\n Y:"..y)<br />
echo("\n Z:"..z)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- A quick function that will find all rooms on the same z-position in an area; this is useful if, say, you want to know what all the same rooms on the same "level" of an area is.<br />
function sortByZ(areaID, zval)<br />
local area = getAreaRooms(areaID)<br />
local t = {}<br />
for _, id in ipairs(area) do<br />
local _, _, z = getRoomCoordinates(id)<br />
if z == zval then<br />
table.insert(t, id)<br />
end<br />
end<br />
return t<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomEnv==<br />
;envID = getRoomEnv(roomID)<br />
<br />
:Returns the environment ID of a room. The mapper does not store environment names, so you'd need to keep track of which ID is what name yourself.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
funtion checkID(id)<br />
echo(strinf.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))<br />
end<br />
</syntaxhighlight><br />
<br />
== getRoomExits ==<br />
;getRoomExits (roomID)<br />
:Returns the currently known non-special exits for a room in an key-index form: ''exit = exitroomid''.<br />
<br />
: See also: [[#getSpecialExits|getSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
table {<br />
'northwest': 80<br />
'east': 78<br />
}<br />
</syntaxhighlight><br />
<br />
Here's a practical example that queries the rooms around you and searched for one of the water environments (the number would depend on how it was mapped):<br />
<br />
<syntaxhighlight lang="lua"><br />
local exits = getRoomExits(mycurrentroomid)<br />
for direction,num in pairs(exits) do<br />
local env_num = getRoomEnv(num)<br />
if env_num == 22 or env_num == 20 or env_num == 30 then<br />
print("There's water to the "..direction.."!")<br />
end<br />
end</syntaxhighlight><br />
<br />
==getRoomHashByID==<br />
;getRoomHashByID(roomID)<br />
<br />
:Returns a room hash that is associated with a given room ID in the mapper. This is primarily for MUDs that make use of hashes instead of room IDs. It may be used to share map data while not sharing map itself. ''nil'' is returned if no room is not found.<br />
<br />
: See also: [[#getRoomIDbyHash|getRoomIDbyHash()]]<br />
{{note}} Available since Mudlet 3.13.0<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
for id,name in pairs(getRooms()) do<br />
local h = getRoomUserData(id, "herbs")<br />
if h ~= "" then<br />
echo(string.format([[["%s"] = "%s",]], getRoomHashByID(id), h))<br />
echo("\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomIDbyHash==<br />
;roomID = getRoomIDbyHash(hash)<br />
<br />
:Returns a room ID that is associated with a given hash in the mapper. This is primarily for MUDs that make use of hashes instead of room IDs (like [http://avalon.mud.de/index.php?enter=1 Avalon.de] MUD). ''-1'' is returned if no room ID matches the hash.<br />
<br />
: See also: [[#getRoomHashByID|getRoomHashByID()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177<br />
local id = getRoomIDbyHash("5dfe55b0c8d769e865fd85ba63127fbc")<br />
if id == -1 then <br />
id = createRoomID()<br />
setRoomIDbyHash(id, "5dfe55b0c8d769e865fd85ba63127fbc")<br />
addRoom(id)<br />
setRoomCoordinates(id, 0, 0, -1)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomName==<br />
;getRoomName(roomID)<br />
<br />
:Returns the room name for a given room id.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("The name of the room id #455 is %s.", getRoomName(455))<br />
</syntaxhighlight><br />
<br />
==getRooms==<br />
;rooms = getRooms()<br />
<br />
:Returns the list of '''all''' rooms in the map in the whole map in roomid - room name format.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- simple, raw viewer for rooms in the world<br />
display(getRooms())<br />
<br />
-- iterate over all rooms in code<br />
for id,name in pairs(getRooms()) do<br />
print(id, name)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomsByPosition==<br />
;roomTable = getRoomsByPosition(areaID, x,y,z)<br />
<br />
:Returns an indexed table of all rooms at the given coordinates in the given area, or an empty one if there are none. This function can be useful for checking if a room exists at certain coordinates, or whenever you have rooms overlapping.<br />
<br />
{{note}} The returned table starts indexing from '''0''' and not the usual lua index of '''1''', which means that using '''#''' to count the size of the returned table will produce erroneous results - use [[Manual:Table_Functions#table.size|table.size()]] instead.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sample alias to determine a room nearby, given a relative direction from the current room<br />
<br />
local otherroom<br />
if matches[2] == "" then<br />
local w = matches[3]<br />
local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)<br />
local has = table.contains<br />
if has({"west", "left", "w", "l"}, w) then<br />
x = (x or ox) - 1; y = (y or oy); z = (z or oz)<br />
elseif has({"east", "right", "e", "r"}, w) then<br />
x = (x or ox) + 1; y = (y or oy); z = (z or oz)<br />
elseif has({"north", "top", "n", "t"}, w) then<br />
x = (x or ox); y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"south", "bottom", "s", "b"}, w) then<br />
x = (x or ox); y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"northwest", "topleft", "nw", "tl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"northeast", "topright", "ne", "tr"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"southeast", "bottomright", "se", "br"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"up", "u"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) + 1<br />
elseif has({"down", "d"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) - 1<br />
end<br />
<br />
local carea = getRoomArea(mmp.currentroom)<br />
if not carea then mmp.echo("Don't know what area are we in.") return end<br />
<br />
otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))<br />
<br />
if not otherroom then<br />
mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return<br />
else<br />
mmp.echo("The room "..w.." of us has an ID of "..otherroom)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomUserData==<br />
;getRoomUserData(roomID, key)<br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or "" if none is stored. Use [[#setRoomUserData|setRoomUserData()]] function for setting the user data.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserData(341, "visitcount"))<br />
</syntaxhighlight><br />
<br />
:;getRoomUserData(roomID, key, enableFullErrorReporting)<br />
<br />
::Returns the user data value (string) stored at a given room with a given key (string), or, if the boolean value ''enableFullErrorReporting'' is true, ''nil'' and an error message if the key is not present or the room does not exist; if ''enableFullErrorReporting'' is false an empty string is returned but then it is not possible to tell if that particular value is actually stored or not against the given key.<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<!-- I would like this block to be indented to match the Example header but the mark-up system seems to be broken and only includes the first line<br />
if the start of the code line begins: ":<lua>..."--><br />
<syntaxhighlight lang="lua">local vNum = 341<br />
result, errMsg = getRoomUserData(vNum, "visitcount", true)<br />
if result ~= nil then<br />
display(result)<br />
else<br />
echo("\nNo visitcount data for room: "..vNum.."; reason: "..errMsg.."\n")<br />
end</syntaxhighlight><br />
<br />
==getRoomUserDataKeys==<br />
;getRoomUserDataKeys(roomID)<br />
<br />
:Returns all the keys for user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserDataKeys(3441))<br />
--might result in:--<br />
{<br />
"description",<br />
"doorname_up",<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==getRoomWeight==<br />
;getRoomWeight(roomID)<br />
<br />
:Returns the weight of a room. By default, all new rooms have a weight of 1.<br />
: See also: [[#setRoomWeight|setRoomWeight()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Original weight of room 541: "..getRoomWeight(541))<br />
setRoomWeight(541, 3)<br />
display("New weight of room 541: "..getRoomWeight(541))<br />
</syntaxhighlight><br />
<br />
==getSpecialExits==<br />
;exits = getSpecialExits(roomID)<br />
<br />
:Returns a roomid - command table of all special exits in the room. If there are no special exits in the room, the table returned will be empty.<br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getSpecialExits(1337)<br />
<br />
-- results in:<br />
--[[<br />
table {<br />
12106: 'faiglom nexus'<br />
}<br />
]]<br />
</syntaxhighlight><br />
<br />
==getSpecialExitsSwap==<br />
;getSpecialExitsSwap(roomID)<br />
<br />
:Very similar to [[#getSpecialExits|getSpecialExits()]] function, but returns the rooms in the command - roomid style.<br />
<br />
==gotoRoom==<br />
;gotoRoom (roomID)<br />
:Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".<br />
<br />
In case this isn't working, and you are coding your own mapping script, [[Mapping_script#Making_your_own_mapping_script|see here]] how to implement additional functionality necessary.<br />
<br />
==hasExitLock==<br />
;status = hasExitLock(roomID, direction)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
-- check if the east exit of room 1201 is locked<br />
display(hasExitLock(1201, 4))<br />
display(hasExitLock(1201, "e"))<br />
display(hasExitLock(1201, "east"))<br />
</syntaxhighlight><br />
<br />
: See also: [[#lockExit|lockExit()]]<br />
<br />
==hasSpecialExitLock==<br />
;hasSpecialExitLock(from roomID, to roomID, moveCommand)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. ''moveCommand'' is the action to take to get through the gate.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command<br />
lockSpecialExit(17463, 7814, 'enter feather', true)<br />
<br />
-- see if it is locked: it will say 'true', it is<br />
display(hasSpecialExitLock(17463, 7814, 'enter feather'))<br />
</syntaxhighlight><br />
<br />
==highlightRoom==<br />
;highlightRoom( roomID, color1Red, color1Green, color1Blue, color2Red, color2Green, color2Blue, highlightRadius, color1Alpha, color2Alpha)<br />
<br />
:Highlights a room with the given color, which will override its environment color. If you use two different colors, then there'll be a shading from the center going outwards that changes into the other color. <br />
<br />
;Parameters<br />
* ''roomID''<br />
: ID of the room to be colored.<br />
* ''color1Red, color1Green, color1Blue''<br />
: RGB values of the first color.<br />
* ''color2Red, color2Green, color2Blue''<br />
: RGB values of the second color.<br />
* ''highlightRadius'' <br />
: The radius for the highlight circle - if you don't want rooms beside each other to overlap, use ''1'' as the radius. <br />
* ''color1Alpha'' and ''color2Alpha'' <br />
: Transparency values from 0 (completely transparent) to 255 (not transparent at all).<br />
<br />
: See also: [[#unHighlightRoom|unHighlightRoom()]]<br />
<br />
{{note}} Available since Mudlet 2.0.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- color room #351 red to blue<br />
local r,g,b = unpack(color_table.red)<br />
local br,bg,bb = unpack(color_table.blue)<br />
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)<br />
</syntaxhighlight><br />
<br />
==loadMap==<br />
;loadMap(file location)<br />
<br />
:Loads the map file from a given location. The map file must be in Mudlet's format - saved with [[#saveMap|saveMap()]] or, as of the Mudlet 3.0 may be a MMP XML map conforming to the structure used by I.R.E. for their download-able maps for their MUDs. <br />
<br />
:Returns a boolean for whenever the loading succeeded. Note that the mapper must be open, or this will fail.<br />
<br />
<syntaxhighlight lang="lua"><br />
loadMap("/home/user/Desktop/Mudlet Map.dat")<br />
</syntaxhighlight><br />
<br />
==lockExit==<br />
;lockExit(roomID, direction, lockIfTrue)<br />
<br />
:Locks a given exit from a room (which means that unless all exits in the incoming room are locked, it'll still be accessible). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
: See also: [[#hasExitLock|hasExitLock()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- lock the east exit of room 1201 so we never path through it<br />
lockExit(1201, 4, true)<br />
</syntaxhighlight><br />
<br />
==lockRoom==<br />
;lockRoom (roomID, lockIfTrue)<br />
<br />
:Locks a given room id from future speed walks (thus the mapper will never path through that room).<br />
: See also: [[#roomLocked | roomLocked()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockRoom(1, true) -- locks a room if from being walked through when speedwalking.<br />
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.<br />
</syntaxhighlight><br />
<br />
==lockSpecialExit==<br />
;lockSpecialExit (from roomID, to roomID, special exit command, lockIfTrue)<br />
<br />
:Locks a given special exit, leading from one specific room to another that uses a certain command from future speed walks (thus the mapper will never path through that special exit).<br />
: See also: [[#hasSpecialExitLock | hasSpecialExitLock()]], [[#lockExit | lockExit()]], [[#lockRoom | lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2<br />
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit<br />
</syntaxhighlight><br />
<br />
==mapSymbolFontInfo==<br />
;mapSymbolFontInfo()<br />
: See also: [[#setupMapSymbolFont|setupMapSymbolFont(...)]]<br />
<br />
;returns<br />
* either a table of information about the configuration of the font used for symbols in the (2D) map, the elements are:<br />
:* ''fontName'' - a string of the family name of the font specified<br />
:* ''onlyUseThisFont'' - a boolean indicating whether glyphs from just the ''fontName'' font are to be used or if there is not a ''glyph'' for the required ''grapheme'' (''character'') then a ''glyph'' from the most suitable different font will be substituted instead. Should this be ''true'' and the specified font does not have the required glyph then the replacement character (typically something like ''�'') could be used instead. Note that this may not affect the use of Color Emoji glyphs that are automatically used in some OSes but that behavior does vary across the range of operating systems that Mudlet can be run on.<br />
:* ''scalingFactor'' - a floating point number between 0.50 and 2.00 which modifies the size of the symbols somewhat though the extremes are likely to be unsatisfactory because some of the particular symbols may be too small (and be less visible at smaller zoom levels) or too large (and be clipped by the edges of the room rectangle or circle).<br />
* or ''nil'' and an error message on failure.<br />
<br />
::As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialized, by activating a map window).<br />
<br />
{{note}} pending, not yet available.<br />
<br />
==moveMapWidget==<br />
;moveMapWidget(Xpos, Ypos)<br />
:moves the map window to the given position.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
;Parameters<br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very top. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==openMapWidget==<br />
;openMapWidget()<br />
;openMapWidget(dockingArea)<br />
;openMapWidget(Xpos, Ypos, width, height)<br />
:opens a map window with given options.<br />
<br />
: See also: [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
;Parameters<br />
{{note}} If no parameter is given the map window will be opened with the saved layout or at the right docking position (similar to clicking the icon)<br />
* ''dockingArea:''<br />
: If only one parameter is given this parameter will be a string that contains one of the possible docking areas the map window will be created in (f" floating "t" top "b" bottom "r" right and "l" left)<br />
{{note}} If 4 parameters are given the map window will be created in floating state <br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''width:''<br />
: The width map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height map window, in pixels. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==resetRoomArea==<br />
;resetRoomArea (roomID)<br />
<br />
: Unassigns the room from its given area. While not assigned, its area ID will be -1. Note that since Mudlet 3.0 the "default area" which has the id of -1 may be selectable in the area selection widget on the mapper - although there is also an option to conceal this in the settings.<br />
<br />
: See also: [[#setRoomArea | setRoomArea()]], [[#getRoomArea | getRoomArea()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetRoomArea(3143)<br />
</syntaxhighlight><br />
<br />
==resizeMapWidget==<br />
;resizeMapWidget(width, height)<br />
:resizes a map window with given width, height.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]]<br />
<br />
;Parameters<br />
* ''width:''<br />
: The width of the map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height of the map window, in pixels. Passed as an integer number.<br />
<br />
{{note}} available in Mudlet 4.7+<br />
<br />
==removeCustomLine==<br />
;removeCustomLine(roomID, direction) <br />
<br />
:Removes the custom exit line that's associated with a specific exit of a room.<br />
:See also: [[#addCustomLine|addCustomLine()]], [[#getCustomLines|getCustomLines()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- remove custom exit line that starts in room 315 going north<br />
removeCustomLine(315, "n")<br />
</syntaxhighlight><br />
<br />
==removeMapEvent==<br />
;removeMapEvent (event name)<br />
<br />
:Removes the given menu entry from a mappers right-click menu. You can add custom ones with [[#addMapEvent | addMapEvent()]].<br />
: See also: [[#addMapEvent | addMapEvent()]], [[#getMapEvents | getMapEvents()]], [[#removeMapMenu | removeMapMenu()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- add one to the general menu<br />
removeMapEvent("room a") -- removes the said menu<br />
</syntaxhighlight><br />
<br />
==removeMapMenu==<br />
;removeMapMenu(menu name)<br />
<br />
:Removes the given submenu from a mappers right-click menu. You can add custom ones with [[#addMapMenu | addMapMenu()]].<br />
: See also: [[#addMapMenu | addMapMenu()]], [[#getMapMenus | getMapMenus()]], [[#removeMapEvent | removeMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Test") -- add submenu to the general menu<br />
removeMapMenu("Test") -- removes that same menu again<br />
</syntaxhighlight><br />
<br />
==removeSpecialExit==<br />
;removeSpecialExit(roomID, command) <br />
<br />
:Removes the special exit which is accessed by ''command'' from the room with the given ''roomID''.<br />
:See also: [[#addSpecialExit|addSpecialExit()]], [[#clearSpecialExits|clearSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addSpecialExit(1, 2, "pull rope") -- add a special exit from room 1 to room 2<br />
removeSpecialExit(1, "pull rope") -- removes the exit again<br />
</syntaxhighlight><br />
<br />
==roomExists==<br />
;roomExists(roomID)<br />
<br />
:Returns a boolean true/false depending if the room with that ID exists (is created) or not.<br />
<br />
==roomLocked==<br />
;locked = roomLocked(roomID)<br />
<br />
:Returns true or false whenever a given room is locked.<br />
: See also: [[#lockRoom|lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))<br />
</syntaxhighlight><br />
<br />
==saveMap==<br />
;saveMap([location], [version])<br />
<br />
:Saves the map to a given location, and returns true on success. The location folder needs to be already created for save to work. You can also save the map in the Mapper settings tab.<br />
<br />
;Parameters<br />
* ''location''<br />
: (optional) save the map to the given location if provided, or the default one otherwise.<br />
* ''version''<br />
: (optional) map version as a number to use when saving (Mudlet 3.17+)<br />
<br />
: See also: [[#loadMap|loadMap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")<br />
if not savedok then<br />
echo("Couldn't save :(\n")<br />
else<br />
echo("Saved fine!\n")<br />
end<br />
<br />
-- save with a particular map version<br />
saveMap(20)<br />
</syntaxhighlight><br />
<br />
==searchAreaUserData==<br />
:Searches Areas' User Data in a manner exactly the same as [[#searchRoomUserData|searchRoomUserData()]] does in all Rooms' User Data, refer to that command for the specific details except to replace references to rooms and room ID numbers there with areas and areas ID numbers.<br />
<br />
==searchRoom== <br />
;searchRoom (room name / room number)<br />
<br />
:Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of ''roomid = roomname''.<br />
:If you pass it a number instead of a string, it'll act like [[#getRoomName|getRoomName()]] and return you the room name.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(searchRoom("master"))<br />
{<br />
[17463] = 'in the branches of the Master Ravenwood'<br />
[3652] = 'master bedroom'<br />
[10361] = 'Hall of Cultural Masterpieces'<br />
[6324] = 'Exhibit of the Techniques of the Master Artisans'<br />
[5340] = 'office of the Guildmaster'<br />
[2004] = 'office of the guildmaster'<br />
[14457] = 'the Master Gear'<br />
[1337] = 'before the Master Ravenwood Tree'<br />
}<br />
</syntaxhighlight><br />
<br />
If no rooms are found, then an empty table is returned.<br />
<br />
{{note}} Additional parameters are available since Mudlet 3.0:<br />
<br />
;searchRoom (room name, [case-sensitive [, exact-match]])<br />
<br />
;Additional Parameters<br />
* ''case-sensitive:''<br />
: If true forces a case-sensitive search to be done on with the supplied room name argument, if false case is not considered.<br />
* ''exact-match:''<br />
: If true forces an exact match rather than a sub-string match, with a case sensitivity as set by previous option.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- shows all rooms containing these words in any case: --<br />
display(searchRoom("North road",false,false))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road",<br />
[3146] = "Bend in the North Road",<br />
[3088] = "The North Road South of Taren Ferry",<br />
[6229] = "Grassy Field By North Road"<br />
}<br />
<br />
-- shows all rooms containing these words in ONLY this case: --<br />
display(searchRoom("North road",true,false))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3117] = "North road",<br />
}<br />
<br />
-- shows all rooms containing ONLY these words in any case: --<br />
lua searchRoom("North road",false,true)<br />
{<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road"<br />
}<br />
<br />
-- shows all rooms containing ONLY these words in ONLY this case: --<br />
lua searchRoom("North road",true,true)<br />
{<br />
[3115] = "North road",<br />
[3117] = "North road"<br />
}<br />
</syntaxhighlight><br />
<br />
{{note}} Technically, with both options (case-sensitive and exact-match) set to true, one could just return a list of numbers as we know precisely what the string will be, but it was kept the same for maximum flexibility in user scripts.<br />
<br />
==searchRoomUserData== <br />
:A command with three variants that search though all the rooms in sequence (so '''not as fast as a user built/maintained ''index'' system''') and find/reports on the room user data stored:<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;searchRoomUserData(key, value)<br />
<br />
:Reports a (sorted) list of all room ids with user data with the given "value" for the given (case sensitive) "key". Due to the lack of previous enforcement it is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.<br />
<br />
;searchRoomUserData(key)<br />
<br />
:Reports a (sorted) list of the unique values from all rooms with user data with the given (case sensitive) "key". Due to the lack of previous enforcement it is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.<br />
<br />
;searchRoomUserData()<br />
<br />
:Reports a (sorted) list of the unique keys from all rooms with user data with any (case sensitive) "key", available since Mudlet 3.0.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- if I had stored the details of "named doors" as part of the room user data --<br />
display(searchRoomUserData("doorname_up"))<br />
<br />
--[[ could result in a list:<br />
{<br />
"Eastgate",<br />
"Northgate",<br />
"boulderdoor",<br />
"chamberdoor",<br />
"dirt",<br />
"floorboards",<br />
"floortrap",<br />
"grate",<br />
"irongrate",<br />
"rockwall",<br />
"tomb",<br />
"trap",<br />
"trapdoor"<br />
}]]<br />
<br />
-- then taking one of these keys --<br />
display(searchRoomUserData("doorname_up","trapdoor"))<br />
<br />
--[[ might result in a list:<br />
{<br />
3441,<br />
6113,<br />
6115,<br />
8890<br />
}<br />
]]</syntaxhighlight><br />
<br />
{{note}} Available since Mudlet 3.0.<br />
<br />
==setAreaName==<br />
;setAreaName(areaID or areaName, newName)<br />
<br />
:Names, or renames an existing area to the new name. The area must be created first with [[#addAreaName|addAreaName()]] and it must be unique.<br />
<br />
{{note}} areaName is available since Mudlet 3.0.<br />
<br />
:See also: [[#deleteArea|deleteArea()]], [[#addAreaName|addAreaName()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setAreaName(2, "My city")<br />
<br />
-- available since Mudlet 3.0<br />
setAreaName("My old city name", "My new city name")<br />
</syntaxhighlight><br />
<br />
==setAreaUserData==<br />
;setAreaUserData(areaID, key (as a string), value (as a string))<br />
<br />
:Stores information about an area under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. Returns a lua ''true'' value on success. You can have as many keys as you'd like, however a blank key will not be accepted and will produce a lua ''nil'' and an error message instead.<br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#getAreaUserData|getAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]]<br />
<br />
{{note}} Release (not Development) version 3.0 software made this function available, but was unable to load the prerequisite map formats 17 and 18 that can store map-level data - that had been fixed in Release 3.0.1 .<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store extra area details...<br />
setAreaUserData(34, "country", "Andor.")<br />
<br />
-- or a sound file to play in the background (with a script that checks a room's area when entered)...<br />
setAreaUserData(34, "backgroundSound", "/home/user/mudlet-data/soundFiles/birdsong.mp4")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setAreaUserData(101, "some table", yajl.to_string({ruler = "Queen Morgase Trakand", clan = "Lion Warden"}))<br />
display("The ruler's name is: "..yajl.to_value(getRoomUserData(34, "some table")).ruler)<br />
</syntaxhighlight><br />
<br />
==setCustomEnvColor==<br />
;setCustomEnvColor(environmentID, r,g,b,a)<br />
<br />
:Creates, or overrides an already created custom color definition for a given environment ID. Note that this will not work on the default environment colors - those are adjustable by the user in the preferences. You can however create your own environment and use a custom color definition for it.<br />
: See also: [[#getCustomEnvColorTable|getCustomEnvColorTable()]], [[#setRoomEnv|setRoomEnv()]]<br />
<br />
{{note}} Numbers 1-16 and 257-272 are reserved by Mudlet. 257-272 are the default colors the user can adjust in mapper settings, so feel free to use them if you'd like - but don't overwrite them with this function.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200<br />
local r,g,b = unpack(color_table.blue)<br />
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue<br />
</syntaxhighlight><br />
<br />
==setDoor==<br />
;setDoor(roomID, exitCommand, doorStatus)<br />
<br />
:Creates or deletes a door in a room. Doors are purely visual - they don't affect pathfinding. You can use the information to change to adjust your speedwalking path based on the door information in a room, though.<br />
<br />
:Doors CAN be set on stub exits ''- so that map makers can note if there is an obvious door to somewhere even if they do not (yet) know where it goes, perhaps because they do not yet have the key to open it!''<br />
<br />
:Returns ''true'' if the change could be made, ''false'' if the input was valid but ineffective (door status was not changed), and ''nil'' with a message string on invalid input (value type errors).<br />
<br />
: See also: [[#getDoors|getDoors()]]<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to create the door in.<br />
* ''exitCommand:''<br />
: The cardinal direction for the door is in - it can be one of the following: '''n''', '''e''', '''s''', '''w''', '''ne''', '''se''', '''sw''', '''ne'''. ''{Plans are afoot to add support for doors on the other normal exits: '''up''', '''down''', '''in''' and '''out''', and also on special exits - though more work will be needed for them to be shown in the mapper.}'' It is important to ONLY use these direction codes as others e.g. "UP" will be accepted - because a special exit could have ANY name/lua script - but it will not be associated with the particular normal exit - recent map auditing code about to go into the code base will REMOVE door and other room exit items for which the appropriate exit (or stub) itself is not present, so in this case, in the absence of a special exit called "UP" that example door will not persist and not show on the normal "up" exit when that is possible later on.<br />
<br />
* ''doorStatus:''<br />
: The door status as a number - '''0''' means no (or remove) door, '''1''' means open door (will draw a green square on exit), '''2''' means closed door (yellow square) and '''3''' means locked door (red square). <br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- make a door on the east exit of room 4234 that is currently open<br />
setDoor(4234, 'e', 1)<br />
<br />
-- remove a door from room 923 that points north<br />
setDoor(923, 'n', 0)<br />
</syntaxhighlight><br />
<br />
==setExit==<br />
;setExit(from roomID, to roomID, direction)<br />
<br />
:Creates a one-way exit from one room to another using a standard direction - which can be either one of ''n, ne, nw, e, w, s, se, sw, u, d, in, out'', the long version of a direction, or a number which represents a direction. If there was an exit stub in that direction already, then it will be automatically deleted for you.<br />
<br />
:Returns ''false'' if the exit creation didn't work.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^exit (\d+) (\d+) (\w+)$<br />
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north<br />
<br />
if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then<br />
echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))<br />
else<br />
echo("Failed to set the exit.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
This function can also delete exits from a room if you use it like so:<br />
<br />
<syntaxhighlight lang="lua">setExit(from roomID, -1, direction)</syntaxhighlight><br />
<br />
- which will delete an outgoing exit in the specified direction from a room.<br />
<br />
==setExitStub==<br />
;setExitStub(roomID, direction, set/unset)<br />
<br />
Creates or removes an exit stub from a room in a given directions. You can use exit stubs later on to connect rooms that you're sure of are together. Exit stubs are also shown visually on the map, so the mapper can easily tell which rooms need finishing.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: The room to place an exit stub in, as a number.<br />
* ''direction:''<br />
: The direction the exit stub should lead in - as ashort direction name ("nw"), long direction name ("northwest") or a number.<br />
* ''set/unset:''<br />
: A boolean to create or delete the exit stub.<br />
<br />
: See also: [[#getExitStubs|getExitStubs()]], [[#connectExitStub|connectExitStub()]]<br />
<br />
;Example<br />
Create an exit stub to the south from room 8:<br />
<syntaxhighlight lang="lua"><br />
setExitStub(8, "s", true)<br />
</syntaxhighlight><br />
<br />
How to delete all exit stubs in a room:<br />
<syntaxhighlight lang="lua"><br />
for i,v in pairs(getExitStubs(roomID)) do<br />
setExitStub(roomID, v,false)<br />
end<br />
</syntaxhighlight><br />
<br />
==setExitWeight==<br />
;setExitWeight(roomID, exitCommand, weight)<br />
<br />
:Gives an exit a weight, which makes it less likely to be chosen for pathfinding. All exits have a weight of 0 by default, which you can increase. Exit weights are set one-way on an exit - if you'd like the weight to be applied both ways, set it from the reverse room and direction as well.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to set the weight in.<br />
* ''exitCommand:''<br />
: The direction for the exit is in - it can be one of the following: '''n''', '''ne''', '''e''', '''se''', '''s''', '''sw''', '''w''', '''nw''', '''up''', '''down''', '''in''', '''out''', or, if it's a special exit, the special exit command - note that the strings for normal exits are case-sensitive and must currently be exactly as given here.<br />
* ''weight:''<br />
: Exit weight - by default, all exits have a weight of 0 meaning that the weight of the ''destination room'' is use when the route finding code is considering whether to use that exit; setting a value for an exit can increase or decrease the chance of that exit/destination room being used for a route by the route-finding code. For example, if the destination room has very high weight compared to it's neighbors but the exit has a low value then that exit and thus the room is more likely to be used than if the exit was not weighted.<br />
<br />
: See also: [[#getExitWeights|getExitWeights()]]<br />
<br />
==setGridMode==<br />
;setGridMode(areaID, true/false)<br />
<br />
:Enables grid/wilderness view mode for an area - this will cause the rooms to lose their visible exit connections, like you'd see on compressed ASCII maps, both in 2D and 3D view mode; for the 2D map the custom exit lines will also not be shown if this mode is enabled. <br />
:Returns true if the area exists, otherwise false.<br />
<br />
: See also: [[#getGridMode|getGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
</syntaxhighlight><br />
<br />
==setMapUserData==<br />
;setMapUserData(key (as a string), value (as a string))<br />
<br />
:Stores information about the map under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearMapUserData|clearMapUserData()]], [[#clearMapUserDataItem|clearMapUserDataItem()]], [[#getAllMapUserData|getAllMapUserData()]], [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- store general meta information about the map...<br />
setMapUserData("game_name", "Achaea Mudlet map")<br />
<br />
-- or who the author was<br />
setMapUserData("author", "Bob")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setMapUserData("some table", yajl.to_string({game = "mud.com", port = 23}))<br />
display("Available game info in the map: ")<br />
display(yajl.to_value(getMapUserData("some table")))<br />
</syntaxhighlight><br />
<br />
==setMapZoom==<br />
;setMapZoom(zoom)<br />
<br />
:Zooms the map in to a given zoom level. '''1''' is the closest you can get, and anything higher than that zooms the map out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMapZoom(10) -- zoom to a somewhat acceptable level, a bit big but easily visible connections<br />
</syntaxhighlight><br />
<br />
==setRoomArea==<br />
;setRoomArea(roomID, newAreaID or newAreaName)<br />
<br />
:Assigns the given room to a new or different area. If the area is displayed in the mapper this will have the room be visually moved into the area as well.<br />
<br />
: See also: [[#resetRoomArea|resetRoomArea()]]<br />
<br />
==setRoomChar==<br />
;setRoomChar(roomID, character)<br />
<br />
:Originally designed for an area in grid mode, takes a single ASCII character and draws it on the rectangular background of the room in the 2D map. In versions prior to Mudlet 3.8, the symbol can be cleared by using "_" as the character. In Mudlet version 3.8 and higher, the symbol may be cleared with either a space <code>" "</code> or an empty string <code>""</code>.<br />
<br />
;MUD-related symbols for your map<br />
* [https://github.com/toddfast/game-icons-net-font toddfast's font] - 3000+ scalable vector RPG icons from [https://game-icons.net game-icons.net], as well as a script to download the latest icons and generate a new font.<br />
* Pixel Kitchen's [https://www.fontspace.com/donjonikons-font-f30607 Donjonikon Font] - 10x10 fantasy and RPG-related icons.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomChar(431, "#")<br />
<br />
setRoomChar(123, "$")<br />
<br />
-- emoji's work fine too, and if you'd like it coloured, set the font to Nojo Emoji in settings<br />
setRoomChar(666, "👿")<br />
</syntaxhighlight><br />
<br />
:'''Since Mudlet version 3.8 :''' this facility has been extended:<br />
:* This function will now take a short string of any printable characters as a room ''symbol'', and they will be shrunk to fit them all in horizontally but if they become too small that ''symbol'' may not be shown if the zoom is such that the room symbol is too small to be legible.<br />
:* As "_" is now a valid character an existing symbol may be erased with either a space " " or an empty string "" although neither may be effective in some previous versions of Mudlet.<br />
:* Should the rooms be set to be drawn as circles this is now accommodated and the symbol will be resized to fit the reduce drawing area this will cause.<br />
:* The range of characters that are available are now dependent on the '''fonts''' present in the system and a setting on the "Mapper" tab in the preferences that control whether a specific font is to be used for all symbols (which is best if a font is included as part of a MUD server package, but has the issue that it may not be displayable if the user does not have that font or chooses a different one) or any font in the user's system may be used (which is the default, but may not display the ''glyph'' {the particular representation of a ''grapheme'' in a particular font} that the original map creator expected). Should it not be possible to display the wanted symbol in the map because one or more of the required glyphs are not available in either the specified or any font depending on the setting then the ''replacement character'' (Unicode ''code-point'' U+FFFD '�') will be shown instead. To allow such missing symbols to be handled the "Mapper" tab on the preferences dialogue has an option to display:<br />
::* an indicator to show whether the symbol can be made just from the selected font (green tick), from the fonts available in the system (yellow warning triangle) or not at all (red cross)<br />
::* all the symbols used on the map and how they will be displayed both only using the selected font and all fonts<br />
::* the sequence of code-points used to create the symbol which will be useful when used in conjunction with character selection utilities such as ''charmap.exe'' on Windows and ''gucharmap'' on unix-like system<br />
::* a count of the rooms using the particular symbol<br />
::* a list, limited in entries of the first rooms using that symbol<br />
:* The font that is chosen to be used as the primary (or only) one for the room symbols is stored in the Mudlet map data so that setting will be included if a binary map is shared to other Mudlet users or profiles on the same system.<br />
<br />
: See also: [[#getRoomChar|getRoomChar()]]<br />
<br />
==setRoomCoordinates==<br />
;setRoomCoordinates(roomID, x, y, z)<br />
<br />
:Sets the given room ID to be at the following coordinates visually on the map, where ''z'' is the up/down level. <br />
<br />
{{note}} 0,0,0 is the center of the map.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$<br />
-- this sets the current room to the supplied coordinates<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
:You can make them relative as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^src (\w+)$<br />
<br />
local x,y,z = getRoomCoordinates(previousRoomID)<br />
local dir = matches[2]<br />
<br />
if dir == "n" then<br />
y = y+1<br />
elseif dir == "ne" then<br />
y = y+1<br />
x = x+1<br />
elseif dir == "e" then<br />
x = x+1<br />
elseif dir == "se" then<br />
y = y-1<br />
x = x+1<br />
elseif dir == "s" then<br />
y = y-1<br />
elseif dir == "sw" then<br />
y = y-1<br />
x = x-1<br />
elseif dir == "w" then<br />
x = x-1<br />
elseif dir == "nw" then<br />
y = y+1<br />
x = x-1<br />
elseif dir == "u" or dir == "up" then<br />
z = z+1<br />
elseif dir == "down" then<br />
z = z-1<br />
end<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
==setRoomEnv==<br />
;setRoomEnv(roomID, newEnvID)<br />
<br />
:Sets the given room to a new environment ID. You don't have to use any functions to create it - can just set it right away.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34<br />
</syntaxhighlight><br />
<br />
==setRoomIDbyHash==<br />
;setRoomIDbyHash(roomID, hash)<br />
<br />
:Sets the hash to be associated with the given roomID. See also [[#getRoomIDbyHash|getRoomIDbyHash()]].<br />
<br />
==setRoomName==<br />
;setRoomName(roomID, newName)<br />
<br />
:Renames an existing room to a new name.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomName(534, "That evil room I shouldn't visit again.")<br />
lockRoom(534, true) -- and lock it just to be safe<br />
</syntaxhighlight><br />
<br />
==setRoomUserData==<br />
;setRoomUserData(roomID, key (as a string), value (as a string))<br />
<br />
:Stores information about a room under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store room descriptions...<br />
setRoomUserData(341, "description", "This is a plain-looking room.")<br />
<br />
-- or whenever it's outdoors or not...<br />
setRoomUserData(341, "ourdoors", "true")<br />
<br />
-- how how many times we visited that room<br />
local visited = getRoomUserData(341, "visitcount")<br />
visited = (tonumber(visited) or 0) + 1<br />
setRoomUserData(341, "visitcount", tostring(visited))<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setRoomUserData(341, "some table", yajl.to_string({name = "bub", age = 23}))<br />
display("The denizens name is: "..yajl.to_value(getRoomUserData(341, "some table")).name)<br />
</syntaxhighlight><br />
<br />
==setRoomWeight==<br />
;setRoomWeight(roomID, weight)<br />
<br />
:Sets a weight to the given roomID. By default, all rooms have a weight of 1 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.<br />
<br />
{{note}} The minimum allowed room weight is 1. <br />
<br />
:To completely avoid a room, make use of [[#lockRoom|lockRoom()]].<br />
<br />
: See also: [[#getRoomWeight|getRoomWeight()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomWeight(1532, 3) -- avoid using this room if possible, but don't completely ignore it<br />
</syntaxhighlight><br />
<br />
<br />
==setupMapSymbolFont==<br />
;setupMapSymbolFont(fontName[, onlyUseThisFont[, scalingFactor]])<br />
:configures the font used for symbols in the (2D) map.<br />
: See also: [[#mapSymbolFontInfo|mapSymbolFontInfo()]]<br />
<br />
;Parameters<br />
* ''fontName'' one of:<br />
:* - a string that is the family name of the font to use;<br />
:* - the empty string ''""'' to reset to the default {which is '''"Bitstream Vera Sans Mono"'''};<br />
:* - a Lua ''nil'' as a placeholder to not change this parameter but still allow a following one to be modified.<br />
* ''onlyUseThisFont'' (optional) one of:<br />
:* - a Lua boolean ''true'' to require Mudlet to use graphemes (''character'') '''only''' from the selected font. Should a requested grapheme not be included in the selected font then the font replacement character (�) might be used instead; note that under some circumstances it is possible that the OS (or Mudlet) provided color Emoji Font may still be used but that cannot be guaranteed across all OS platforms that Mudlet might be run on;<br />
:* - a Lua boolean ''false'' to allow Mudlet to get a different ''glyph'' for a particular ''grapheme'' from the most suitable other font found in the system should there not be a ''glyph'' for it in the requested font. This is the default unless previously changed by this function or by the corresponding checkbox in the Profile Preferences dialogue for the profile concerned;<br />
:* - a Lua ''nil'' as a placeholder to not change this parameter but still allow the following one to be modified.<br />
* ''scalingFactor'' (optional): a floating point value in the range ''0.5'' to ''2.0'' (default ''1.0'') that can be used to tweak the rectangular space that each different room symbol is scaled to fit inside; this might be useful should the range of characters used to make the room symbols be consistently under- or over-sized.<br />
<br />
;Returns<br />
* ''true'' on success<br />
* ''nil'' and an error message on failure. As the symbol font details are stored in the (binary) map file rather than the profile then this function will not work until a map is loaded (or initialised, by activating a map window).<br />
<br />
{{note}} pending, not yet available.<br />
<br />
==speedwalk==<br />
;speedwalk(dirString, backwards, delay, show)<br />
<br />
:A speedwalking function will work on cardinal+ordinal directions (n, ne, e, etc.) as well as u (for up), d (for down), in and out. It can be called to execute all directions directly after each other, without delay, or with a custom delay, depending on how fast your mud allows you to walk. It can also be called with a switch to make the function reverse the whole path and lead you backwards.<br />
<br />
:Call the function by doing: <code>speedwalk("YourDirectionsString", true/false, delaytime, true/false)</code><br />
<br />
:The delaytime parameter will set a delay between each move (set it to 0.5 if you want the script to move every half second, for instance). It is optional: If you don't indicate it, the script will send all direction commands right after each other. (If you want to indicate a delay, you -have- to explicitly indicate true or false for the reverse flag.)<br />
<br />
:The show parameter will determine if the commands sent by this function are shown or hidden. It is optional: If you don't give a value, the script will show all commands sent. (If you want to use this option, you -have- to explicitly indicate true or false for the reverse flag, as well as either some number for the delay or nil if you do not want a delay.)<br />
<br />
:The "YourDirectionsString" contains your list of directions and steps (e.g.: "2n, 3w, u, 5ne"). Numbers indicate the number of steps you want it to walk in the direction specified after it. The directions must be separated by anything other than a letter that can appear in a direction itself. (I.e. you can separate with a comma, spaces, the letter x, etc. and any such combinations, but you cannot separate by the letter "e", or write two directions right next to each other with nothing in-between, such as "wn". If you write a number before every direction, you don't need any further separator. E.g. it's perfectly acceptable to write "3w1ne2e".) The function is not case-sensitive.<br />
<br />
:If your Mud only has cardinal directions (n,e,s,w and possibly u,d) and you wish to be able to write directions right next to each other like "enu2s3wdu", you'll have to change the pattern slightly. Likewise, if your Mud has any other directions than n, ne, e, se, s, sw, w, nw, u, d, in, out, the function must be adapted to that.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
speedwalk("16d1se1u")<br />
-- Will walk 16 times down, once southeast, once up. All in immediate succession.<br />
<br />
speedwalk("2ne,3e,2n,e")<br />
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.<br />
<br />
speedwalk("IN N 3W 2U W", false, 0.5)<br />
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.<br />
<br />
speedwalk("5sw - 3s - 2n - w", true)<br />
-- Will walk backwards: east, twice south, thrice, north, five times northeast. All in immediate succession.<br />
<br />
speedwalk("3w, 2ne, w, u", true, 1.25)<br />
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.<br />
</syntaxhighlight><br />
<br />
{{note}} The probably most logical usage of this would be to put it in an alias. For example, have the pattern ''^/(.+)$'' execute: <code>speedwalk(matches[2], false, 0.7)</code><br />
And have ''^//(.+)$'' execute: <code>speedwalk(matches[2], true, 0.7)</code><br />
Or make aliases like: ''^banktohome$'' to execute <syntaxhighlight lang="lua" inline>speedwalk("2ne,e,ne,e,3u,in", true, 0.5)</syntaxhighlight><br />
<br />
{{note}} The show parameter for this function will be available in Mudlet versions after 3.12.<br />
<br />
==unHighlightRoom==<br />
;unHighlightRoom(roomID)<br />
<br />
:Unhighlights a room if it was previously highlighted and restores the rooms original environment color.<br />
: See also: [[#highlightRoom|highlightRoom()]]<br />
<br />
{{note}} Available since Mudlet 2.0 final release<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
unHighlightRoom(4534)<br />
</syntaxhighlight><br />
<br />
==updateMap==<br />
;updateMap()<br />
<br />
:Updates the mapper display (redraws it). Use this function if you've edited the map via script and would like the changes to show.<br />
<br />
: See also: [[#centerview|centerview()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete a some room<br />
deleteRoom(500)<br />
-- now make the map show that it's gone<br />
updateMap()<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6905Manual:Introduction/ru2020-06-15T21:47:20Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
; [[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
; [[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
; [[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]<br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
=== Синтаксические ошибки это же Божьи коровки ===<br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/10/ru&diff=6904Translations:Manual:Introduction/10/ru2020-06-15T21:47:20Z<p>RodeoS: </p>
<hr />
<div>; [[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6903Manual:Introduction/ru2020-06-15T21:46:55Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
; [[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
; [[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]<br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
=== Синтаксические ошибки это же Божьи коровки ===<br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/7/ru&diff=6902Translations:Manual:Introduction/7/ru2020-06-15T21:46:55Z<p>RodeoS: </p>
<hr />
<div>; [[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6901Manual:Introduction/ru2020-06-15T21:46:38Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
; [[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]<br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
=== Синтаксические ошибки это же Божьи коровки ===<br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/9/ru&diff=6900Translations:Manual:Introduction/9/ru2020-06-15T21:46:38Z<p>RodeoS: </p>
<hr />
<div>; [[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6899Manual:Introduction/ru2020-06-15T21:45:11Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]<br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
=== Синтаксические ошибки это же Божьи коровки ===<br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/74/ru&diff=6898Translations:Manual:Introduction/74/ru2020-06-15T21:45:11Z<p>RodeoS: </p>
<hr />
<div>=== Синтаксические ошибки это же Божьи коровки ===</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6897Manual:Introduction/ru2020-06-15T21:45:01Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]<br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/14/ru&diff=6896Translations:Manual:Introduction/14/ru2020-06-15T21:45:01Z<p>RodeoS: </p>
<hr />
<div>Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6895Manual:Introduction/ru2020-06-15T21:44:24Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/8/ru&diff=6894Translations:Manual:Introduction/8/ru2020-06-15T21:44:23Z<p>RodeoS: </p>
<hr />
<div>; [[#Timers|Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6893Manual:Introduction/ru2020-06-15T21:40:39Z<p>RodeoS: Created page with "Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который о..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/93/ru&diff=6892Translations:Manual:Introduction/93/ru2020-06-15T21:40:39Z<p>RodeoS: Created page with "Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который о..."</p>
<hr />
<div>Новички будет полезно использовать подсветку триггеров Mudlet, чтобы выделить текст, на который он срабатывает, чтобы отладить триггеры и шаблоны. Нажмите на опцию «Подсветить(highlight)» и выберите цвет шрифта и цвет фона, которыми вы хотели бы выделить текст на который триггер срабатывает. Когда триггер сработает, он автоматически выделит строку которая его активировала в окне MUDа. Это наиболее распространенная форма триггеров в Mud, так как это быстрый способ выделить слова, которые в данный момент важны. Вам не нужно ничего знать о сценариях, регулярных выражениях и т. п., чтобы использовать подсветку триггеров. Просто введите слово, которое вы хотите выделить, выберите соответствующие цвета, сохраните триггер и активируйте его.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6891Manual:Introduction/ru2020-06-15T21:38:23Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/92/ru&diff=6890Translations:Manual:Introduction/92/ru2020-06-15T21:38:22Z<p>RodeoS: </p>
<hr />
<div>Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимете замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6889Manual:Introduction/ru2020-06-15T21:38:05Z<p>RodeoS: Created page with "Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветв..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимите замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/92/ru&diff=6888Translations:Manual:Introduction/92/ru2020-06-15T21:38:05Z<p>RodeoS: Created page with "Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветв..."</p>
<hr />
<div>Вы также можете поместить триггеры в группу, затем заблокировать группу триггеров или всю ветвь триггеров. Если вы сделаете это, все триггеры в этой группе или ответвлении будут заблокированы до тех пор, пока вы не снимите замок снова. Блокировка начинается от корня дерева до конца. Как только блокировка будет выполнена, триггерный механизм пропустит заблокированную ветвь. Блокировка и разблокировка ветвей - одно из наиболее распространённых действий, о которых вам необходимо позаботиться во время игры. Например, вы можете включить триггеры защиты при вступлении в бой, а затем отключить их, или же вы включаете триггеры сбора урожая только тогда, когда собираетесь собирать урожай.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6887Manual:Introduction/ru2020-06-15T21:37:06Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/91/ru&diff=6886Translations:Manual:Introduction/91/ru2020-06-15T21:37:06Z<p>RodeoS: </p>
<hr />
<div>Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замкА.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6885Manual:Introduction/ru2020-06-15T21:36:44Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замка. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/91/ru&diff=6884Translations:Manual:Introduction/91/ru2020-06-15T21:36:44Z<p>RodeoS: </p>
<hr />
<div>Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого навесного замОчка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замка.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6883Manual:Introduction/ru2020-06-15T21:36:20Z<p>RodeoS: Created page with "Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автом..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого висячего замочка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замка. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/91/ru&diff=6882Translations:Manual:Introduction/91/ru2020-06-15T21:36:20Z<p>RodeoS: Created page with "Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автом..."</p>
<hr />
<div>Поскольку триггер активен, каждый раз, когда в выводе MUD появляется слово "кролик", триггер автоматически выдает команду "убить кролика". Она будет повторяться до тех пор, пока триггер остается активным. Когда вы хотите прекратить охоту на кроликов, вы можете просто выбрать триггер "кролик", а затем нажать на иконку закрытого висячего замочка, чтобы деактивировать его. Флажок исчезнет, и триггер перестанет срабатывать до тех пор, пока вы не включите его снова с помощью значка закрытого висячего замка.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6881Manual:Introduction/ru2020-06-15T21:35:32Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/90/ru&diff=6880Translations:Manual:Introduction/90/ru2020-06-15T21:35:32Z<p>RodeoS: </p>
<hr />
<div># Вы вводите "кролик" в поле ввода за заголовком "1"(первая строка), чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/209/ru&diff=6879Translations:Manual:Introduction/209/ru2020-06-15T21:34:51Z<p>RodeoS: Created page with "center"</p>
<hr />
<div>[[File:Trigger intro.png|1000px|center]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6878Manual:Introduction/ru2020-06-15T21:34:48Z<p>RodeoS: Created page with "# Вы вводите "кролик" в поле ввода за заголовком "0", чтобы добавить это слово в список строк, котор..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# Вы вводите "кролик" в поле ввода за заголовком "0", чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/90/ru&diff=6877Translations:Manual:Introduction/90/ru2020-06-15T21:34:47Z<p>RodeoS: Created page with "# Вы вводите "кролик" в поле ввода за заголовком "0", чтобы добавить это слово в список строк, котор..."</p>
<hr />
<div># Вы вводите "кролик" в поле ввода за заголовком "0", чтобы добавить это слово в список строк, которые запустят этот триггер. Убедитесь, что в выпадающем списке рядом написано "подстрока(substring)". <br />
# Теперь вы набираете "убить кролика" в поле под названием Команда(Command). Это будет команда, которую триггер будет посылать в вашу игру всякий раз, когда он сработает. <br />
# Наконец, нажмите на иконку сохранения, чтобы сохранить триггер и активировать его. При этом перед именем триггера (в дереве триггеров слева) ставится флажок синего цвета. Теперь триггер активирован.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6876Manual:Introduction/ru2020-06-15T21:31:51Z<p>RodeoS: Created page with "Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!)."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/89/ru&diff=6875Translations:Manual:Introduction/89/ru2020-06-15T21:31:51Z<p>RodeoS: Created page with "Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!)."</p>
<hr />
<div>Простой пример: Всякий раз, когда вы видите кролика, вы хотите напасть на него (подлец!).</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6874Manual:Introduction/ru2020-06-15T21:31:37Z<p>RodeoS: Created page with "Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действ..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/88/ru&diff=6873Translations:Manual:Introduction/88/ru2020-06-15T21:31:37Z<p>RodeoS: Created page with "Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действ..."</p>
<hr />
<div>Способ работы триггера прост: вы задаете какой-то текст, для которого вы хотите какого-то действия. Это называется шаблоном триггера. Когда триггер "видит" этот текст в выводе MUD, он запустит команды, которые вы указали.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6872Manual:Introduction/ru2020-06-15T21:31:26Z<p>RodeoS: Created page with "Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быст..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/87/ru&diff=6871Translations:Manual:Introduction/87/ru2020-06-15T21:31:25Z<p>RodeoS: Created page with "Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быст..."</p>
<hr />
<div>Триггеры - это функция автоматизации, предоставляемая всеми MUD клиентами. Они помогают вам быстрее реагировать на конкретную ситуацию и, как правило, делают вещи более удобными для вас, так как вам нужно меньше вводить команды вручную, так как ваши триггеры часто будут делать эту тяжелую работу за вас. Это поможет вам больше сосредоточиться на важных аспектах игры и уменьшить стресс.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6870Manual:Introduction/ru2020-06-15T21:31:15Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
== Триггеры ==<br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6869Manual:Introduction/ru2020-06-15T21:30:56Z<p>RodeoS: Created page with "Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/85/ru&diff=6868Translations:Manual:Introduction/85/ru2020-06-15T21:30:56Z<p>RodeoS: Created page with "Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые..."</p>
<hr />
<div>Пока все - эта страница со временем будет улучшена с помощью распространенных методик, которые можно использовать для быстрой диагностики ошибок и т. д. если вы что-то знаете об этом, не стесняйтесь добавить это сюда!</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6867Manual:Introduction/ru2020-06-15T21:30:34Z<p>RodeoS: Created page with "Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на с..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.<br />
<br />
That's it for now - this page in time will be improved with common techniques you can use to diagnose errors quickly, etc... if you know anything about this, feel free to add it here!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/84/ru&diff=6866Translations:Manual:Introduction/84/ru2020-06-15T21:30:34Z<p>RodeoS: Created page with "Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на с..."</p>
<hr />
<div>Следующая красная строка - фактическая ошибка: в строке 2 (она отключена на единицу - так что на самом деле в строке 1), ''eecho'' is a '''nil value'''. В Lua (nil value) нулевое значение означает, что его не существует. Отсюда следует, что eecho на самом деле не существует! Поменяйте его на ''echo'', запустите его снова, и будет вам счастье.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6865Manual:Introduction/ru2020-06-15T21:29:55Z<p>RodeoS: Created page with "Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в M..."</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.<br />
<br />
Next red line is the actual error: it's saying that on line 2 (it's off by one - so actually line 1), ''eecho'' is a '''nil value'''. In Lua, nil means doesn't exist. Hence what it's telling you is that eecho does not actually exist! Change it to ''echo'', run it again, and there will be happiness.<br />
<br />
That's it for now - this page in time will be improved with common techniques you can use to diagnose errors quickly, etc... if you know anything about this, feel free to add it here!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/83/ru&diff=6864Translations:Manual:Introduction/83/ru2020-06-15T21:29:55Z<p>RodeoS: Created page with "Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в M..."</p>
<hr />
<div>Давайте проанализируем сообщение, которое нам показывают. ''object:<Some random alias>'' означает, что имя в Mudlet, которое вы дали вещи, у которой возникла проблема, это ''Какой-то случайный псевдоним', который на самом деле является нашим псевдонимом. ''функция'' скажет вам ''псевдоним'', ''триггер'', ''скрипт'' или что-то ещё - это поможет вам найти проблемный элемент, о котором идет речь.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/82/ru&diff=6863Translations:Manual:Introduction/82/ru2020-06-15T21:29:31Z<p>RodeoS: Created page with "center"</p>
<hr />
<div>[[File:Runtime error.png|1000px|center]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6862Manual:Introduction/ru2020-06-15T21:29:27Z<p>RodeoS: Created page with "Открыв его, вы увидите это:"</p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Открыв его, вы увидите это:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Let's analyse the message that's shown to us. ''object:<Some random alias>'' means that the Mudlet name you gave to the thing that had a problem is ''Some random alias'' - which is, indeed, our alias. ''function'' will tell you ''Alias'', ''Trigger'', ''Script'' or something else - this helps you locate the problematic item in question.<br />
<br />
Next red line is the actual error: it's saying that on line 2 (it's off by one - so actually line 1), ''eecho'' is a '''nil value'''. In Lua, nil means doesn't exist. Hence what it's telling you is that eecho does not actually exist! Change it to ''echo'', run it again, and there will be happiness.<br />
<br />
That's it for now - this page in time will be improved with common techniques you can use to diagnose errors quickly, etc... if you know anything about this, feel free to add it here!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/81/ru&diff=6861Translations:Manual:Introduction/81/ru2020-06-15T21:29:27Z<p>RodeoS: Created page with "Открыв его, вы увидите это:"</p>
<hr />
<div>Открыв его, вы увидите это:</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6860Manual:Introduction/ru2020-06-15T21:29:10Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Opening it up will show this:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Let's analyse the message that's shown to us. ''object:<Some random alias>'' means that the Mudlet name you gave to the thing that had a problem is ''Some random alias'' - which is, indeed, our alias. ''function'' will tell you ''Alias'', ''Trigger'', ''Script'' or something else - this helps you locate the problematic item in question.<br />
<br />
Next red line is the actual error: it's saying that on line 2 (it's off by one - so actually line 1), ''eecho'' is a '''nil value'''. In Lua, nil means doesn't exist. Hence what it's telling you is that eecho does not actually exist! Change it to ''echo'', run it again, and there will be happiness.<br />
<br />
That's it for now - this page in time will be improved with common techniques you can use to diagnose errors quickly, etc... if you know anything about this, feel free to add it here!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoShttps://wiki.mudlet.org/index.php?title=Translations:Manual:Introduction/80/ru&diff=6859Translations:Manual:Introduction/80/ru2020-06-15T21:29:10Z<p>RodeoS: </p>
<hr />
<div>Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете завалены спамом, когда совершаете ошибку в куске кода, что случается очень часто.</div>RodeoShttps://wiki.mudlet.org/index.php?title=Manual:Introduction/ru&diff=6858Manual:Introduction/ru2020-06-15T21:28:37Z<p>RodeoS: </p>
<hr />
<div><languages/><br />
{{TOC right}}<br />
= Автоматизация и правила игры =<br />
<br />
Фактически говоря, можно создать ИИ (искусственный интеллект), который делает все, что вы можете сделать в игре. Даже более того, программа сможет превзойти тебя почти в каждой рутинной операции. Сложность создания такой программы зависит от задач, которые ей предстоит выполнить: сбор бабла очень легко, проходя через подземелье и прокачки персонажа быть в меру легким и социально взаимодействовать с другими реальными людьми, будучи зверски трудно (см. A.L.I.C.E.). В конце концов, вы учите Mudlet обрабатывать информацию и действовать так, как вы считаете лучше всего подходит. Потому что код настолько мощный, он может дать вам конкурентное преимущество в том, что некоторые люди считают несправедливыми или даже обман. На момент написания этой статьи (2 ноября 2008), такая автоматизация может быть лучше всего наблюдена в коммерческих массивно-многопользовательских онлайновых ролевых игр (MMORPG), известно как золото-сельское хозяйство или прокачка. Основная идея заключается в создании системы, которая позволит поднять своего персонажа до максимального уровня и собирать игровую валюту в процессе, оба из которых могут быть эффективно обменять на реальные деньги. Распространение вышеуказанных аспектов может иметь гораздо более далеко идущие последствия, чем просто несправедливость, таких как инфляция, потеря равновесия с точки зрения игровой механики или, в конечном итоге, полный крах экономики в игре. Дополнительные сведения см. в статье "простая Экономика на реальные деньги торговли в онлайн-играх" от Июня-это сок из Сеульского Национального университета. По этим и разным другим причинам администраторы и владельцы соответствующих виртуальных миров могут запретить использование средств автоматизации. Несоблюдение может привести к приостановке или удаление персонажа пользователя или учетной записи для будущих отказу в обслуживании.<br />
<br />
В том числе поддержка скриптов в Mudlet, мы фактически даем Вам возможность создания и использования инструментальных средств ИИ, однако, мы не одобряем или поощряем использование этих систем, если это запрещено в вашей игре. Имейте в виду, что путем обмана можно уменьшить качество угры для других игроков и себя.<br />
<br />
= Функции автоматизации Mudlet =<br />
<br />
Mudlet предлагает широкий спектр стандартных функций для автоматизации или иным образом улучшить ваш игровой опыт. Они включают, но не ограничиваются:<br />
<br />
; [[#Аliases|Псевдонимы]] <br />
: пользовательский ввод текста, который преобразуется в другой, как правило, более длинный чем введенный в Mudlet. <br />
: например набрав "'вз"' текст преобразуется в "'взять золото с земли;положить золото в мешок" и будет отправлен в игру"'.<br />
<br />
; [[#Keybindings|Сочетания клавиш]] <br />
: также известные как "горячие клавиши", позволяют выполнение определенных пользовательских команд нажатием определенной комбинации клавиш <br />
:например нажмите '''CTRL+H''' чтобы отправить "сказать Привет Василий!" в MUD или сыграть '''Марсельезу'''<br />
<br />
[[#Triggers|Триггеры]] <br />
: выполняют определяемые пользователем команды при получении конкретной строки из MUD, <br />
: например, MUD отправляет: "Вы видите, что здесь стоит Вася", а Mudlet автоматически посылает "пнуть Вася" в MUD.<br />
<br />
; [ [#Timers| Таймеры]]<br />
: отсрочка выполнения команды или выполнение ее по истечении заданного периода времени.<br />
: например, бросить рукавицу в Эрика-подождать 3 секунды-воскликнуть Давайте закончим это здесь!<br />
<br />
[[#Variables|Переменные]] <br />
: позволяют пользователю хранить текст или числа для легкого и удобного использования внутри скриптов.<br />
<br />
[[#Events|События]] <br />
: позволяет пользователю создавать триггеры для определенных событий, например, когда Mudlet подключился к MUD, или даже определенных пользователем событий для создания комплексной или сложной обработки.<br />
<br />
Чтобы начать программировать в Mudlet, '''[http://www.mudlet.org/media/ посмотрите три скринкаста]''' которые объясняют основные моменты - это поможет вам изучить основы. <br />
<br />
Продолжайте читать для введения в функции Mudlet:<br />
<br />
<br />
<br />
<span id="aliases"></span><br />
= Псевдонимы =<br />
<br />
<div class="mw-translate-fuzzy"><br />
Псевдонимы - самый простой способ автоматизировать игровой процесс - вы можете использовать псевдонимы, чтобы сократить количество набираемого вами текста. Более подробная информация здесь: [[Manual:Alias Engine|Руководство:Механизм псевдонимов]]]<br />
</div><br />
<br />
<br />
<br />
== Пример - Самогон'О'Matic 6000 ==<br />
<br />
Вы прогуливаетесь по эпическому подземелью Нечестивого Файррагона Вестерсанда, собирая корни, чтобы заварить зелье и тем самым восстановить рост волос на лысой голове фермера Бенедикта. Как только вы видите корень, вы должны:<br />
<br />
<pre><br />
открыть мешок с инструментами<br />
получить серп проклятия из мешка с инструментами<br />
обрезать корень <br />
<ждать 5 секунд><br />
очистить серп проклятия от смертельной корневой кислоты<br />
положить серп проклятия в мешок с инструментами<br />
закрыть мешок с инструментами<br />
открыть волшебный мешок для хранения<br />
взять корень<br />
положить корень в волшебный мешок для хранения<br />
закрыть волшебный мешок для хранения<br />
</pre><br />
<br />
И как только вы закончите, сделайте то же самое еще девять раз... три раза в день!<br />
<br />
Альтернативой будет создание "псевдонима", который будет делать все это с помощью одной команды - например, "quest". Чтобы это произошло, читайте дальше! Вот краткий обзор на то, что должно получится в итоге: <br />
<br />
[[File:Quest alias.png|center]]<br />
<br />
<br />
<br />
== Создание псевдонима ==<br />
<br />
Для начала нажмите на кнопку ''Псевдонимы(Aliases)'' в Mudlet, а затем на кнопку ''Добавить''. Это создаст пустой псевдоним, который мы сейчас заполним.<br />
<br />
Поле ''Имя псевдонима'' не является обязательным - оно в основном используется для списка псевдонимов, который вы видите слева, как простой способ отличить все псевдонимы. Пока, что вы можете просто назвать наш псевдоним "тест". Поле ''Шаблон(Pattern)'' - это то место, куда вы помещаете регулярное выражение-шаблон для описания команды, которую вы введете, чтобы ваш новый псевдоним сработал. Допустим, мы хотим, чтобы наш новый псевдоним посылал команду "сказать Привет" всякий раз, когда мы набираем "сп". Шаблон регулярного выражения будет '''^сп$''. Затем в поле "Команда(Commands)" мы ставим "сказать Привет". После сохранения и активации нового псевдонима "test", всякий раз, когда вы набираете "сп" Mudlet будет посылать не "сп", а "сказать Привет". Мы называем этот процесс подмены разворачиванием псевдонима.<br />
<br />
Mudlet использует механизм регулярных выражений Perl. Регексы - это особый способ сопоставления слов. Новичкам достаточно подумать о них как об общем способе указания самих слов и их расположения в строке. Для основных псевдонимов достаточно знать, что символ ^ символизирует начало строки, а символ $ символизирует конец строки. Если вы хотите сделать псевдоним "во", который посылает команду "взять оружие", вам не нужно заботиться о размещении или подборе шаблона в целом. Все, что вам нужно сделать, это поместить '''^во$''' в поле под названием "Шаблон(Pattern)" и ввести '''взять оружие''' в поле под названием "Команда(Command)". Затем нужно сохранить новый псевдоним, нажав на иконку "Сохранить" в верхнем среднем углу. Символ "Сохранить" исчезнет и освободит место для маленькой синей галочки. Если этот флажок установлен, то псевдоним активен. Если синее поле пустое, псевдоним деактивируется и не будет работать, пока вы не нажмёте на значок "активировать" (иконка закрытого навесного замОчка). Теперь все готово к работе. Введите "во" в командной строке и нажмите клавишу ввода. Mudlet отправит "взять оружие" в MUD. Псевдонимы - это, в основном, функция, позволяющая немного сократить набор текста (так же, как и горячие клавиши, которые будут подробно описаны в следующем разделе руководства). Более подробное описание использования псевдонимов будет дано позже в руководстве.<br />
<br />
<br />
<br />
=== Создание псевдонима для цели ===<br />
<br />
Чтобы сделать псевдоним, который запомнит вашу цель - упростит использование ваших навыков и уменьшит сложность ввода цели в любое время, сделайте следующее:<br />
<br />
В поле '' 'Шаблон(Pattern)' '' разместите следующее:<br />
<br />
^ц (.+)$<br />
<br />
Это будет соответствовать всем командам, которые вы набираете в формате '''ц <любой текст>'' - это будет соответствовать ''ц крыса'', ''ц Т'харн'', ''ц человек'' и так далее.<br />
<br />
Далее вставляем это в большое поле ввода:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = matchs[2]<br />
cecho ("<light_slate_blue>Моя цель сейчас: <red>".. target.. "\n")<br />
</syntaxhighlight><br />
<br />
[[File:Basic_targetting.png|center]]<br />
<br />
Вы также можете создать псевдоним с необязательной целью:<br />
<br />
^ц(?: (.+))?$<br />
<br />
Теперь целью, если она указывается, будет ''matches[2]''. С помощью этого кода можно проверить, была ли указана цель:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("колдовать заклинание на "..(matches[2] or target))<br />
</syntaxhighlight><br />
<br />
<br />
Вот и все - всякий раз, когда вы используете этот псевдоним, ваша цель будет запоминаться в переменной ''target''.<br />
<br />
Далее, вы бы хотели использовать эту переменную - так сделайте еще один псевдоним, который сформирует атаку для вас! Вот пример:<br />
<br />
Шаблон(Pattern):<br />
<br />
^ацп$<br />
<br />
Код:<br />
<br />
<syntaxhighlight lang="lua"><br />
send("пнуть "..target)<br />
</syntaxhighlight><br />
<br />
Результатом выполнения этого псевдонима станет пинок по цели, когда вы наберете ''ацп''. Не стесняйтесь подстраивать слово-"триггер"(Шаблон) и команду так как необходимо вам.<br />
<br />
[[File:Basic attack alias.png|center]]<br />
<br />
<br />
<br />
<span id="variables"></span><br />
== Переменные ==<br />
<br />
Переменные представляют собой контейнеры для данных. В Lua они могут хранить цифры или слова. Вы можете использовать переменные для хранения важной информации, например, сколько золота у вас есть, или чтобы они запоминали что-то для вас.<br />
<br />
Синтаксис для того, чтобы переменная запомнила число, следующий - напишите или скопируйте в редакторе Скрипты(Script) в новом скрипте:<br />
<syntaxhighlight lang="lua">variable = 1234</syntaxhighlight><br />
<br />
Или чтобы переменная запомнила какой-нибудь текст:<br />
<syntaxhighlight lang="lua">my_name = "Bob"</syntaxhighlight><br />
<br />
It'll then appear in the Variables view, like so:<br />
<br />
[[File:Variables_view.png|border|center|800px|]]<br />
<br />
{{note|The variables view doesn't autoupdate, but it can be refreshed by clicking the Variables button.}}<br />
<br />
Вы также можете легко проводить базовые математические вычисления, например:<br />
<br />
Чтобы соединить строки вместе, можно использовать символы".." :<br />
<syntaxhighlight lang="lua">my_full_name = "Bob" .. " the Builder"</syntaxhighlight><br />
<br />
Не забывайте использовать пробел, когда вы соединяете две переменные вместе:<br />
<syntaxhighlight lang="lua"><br />
имя = "Вася"<br />
фамилия = "Пупкин"<br />
<br />
-- неправильно: получится "ВасяПупкин"<br />
full_name = firstname .. lastname<br />
<br />
-- правильно: получится "Вася Пупкин"<br />
full_name = firstname .. " " .. lastname<br />
</syntaxhighlight><br />
<br />
Вы также можете редактировать и удалять переменные из окна списка переменных. Будьте осторожны при изменении или удалении существующих переменных, сделанных сторонними скриптами - вы можете их сломать. Если это произойдет, при повторном открытии профилей переменные будут возвращены в рабочее состояние.<br />
<br />
Хотя вы можете создавать переменные в окне "Переменные", помните, что они не будут сохраняться при выключении клиента Mudlet - если вы хотите, чтобы они были более постоянными, создавайте скрипты с переменными вместо них.<br />
<br />
<br />
<br />
= Отправка команд в MUD =<br />
<br />
Для отправки команды в MUD можно использовать функцию send(). Данные внутри кавычек отправляются в MUD.<br />
<br />
Например, следующий код посылает команду съесть хлеб:<br />
<syntaxhighlight lang="lua">send("есть хлеб")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в команду send, вам нужно префиксовать и суффиксовать их двумя точками вне кавычек, вот так:<br />
<syntaxhighlight lang="lua">send("Меня зовут ".. full_name .. ".. А как тебя зовут?")</syntaxhighlight><br />
<br />
Если ваши команды заканчиваются переменной, вам не нужны две точки после нее:<br />
<syntaxhighlight lang="lua">send("Привет, меня зовут ".. character")</syntaxhighlight><br />
<br />
Если вы хотите включить двойные кавычки, используйте двойной набор квадратных скобок вот так:<br />
<syntaxhighlight lang="lua">send([[скажите "Привет, я тут новенький!"]])</syntaxhighlight><br />
<br />
При вставке переменной вы используете ]] и [[ соответственно:<br />
<syntaxhighlight lang="lua">send([[пнуть ]]..жертва)</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько направлений(SpeedWalk), используйте [[Manual:Mapper_Functions#speedwalk|speedwalk()]]:<br />
<syntaxhighlight lang="lua">speedwalk("n;e;s;w;")</syntaxhighlight><br />
<br />
Чтобы отправить сразу несколько действий, используйте [[Manual:Networking_Functions#sendAll|sendAll()]]:<br />
<syntaxhighlight lang="lua">sendAll("атаковать, "колдовать магическую стрелу")</syntaxhighlight><br />
<br />
= Отображение текста на экране =<br />
<br />
Для эхоповтора (показать текст самому себе без отправки его в MUD) можно использовать функцию echo () или insertText (). Например, в следующем коде будет показано "Время обедать!" на вашем экране:<br />
<br />
<syntaxhighlight lang="lua">echo("Время обедать!")</syntaxhighlight><br />
<br />
Если вы хотите включить переменные в эхо, вы конкатенуете (складываете) значение вашей переменной в текст:<br />
<syntaxhighlight lang="lua"><br />
my_gold = 5<br />
echo("У меня ".. my_gold.. " кусочков золота!\n")<br />
</syntaxhighlight><br />
<br />
Если вы хотите чтобы последующий текст показывался уже на другой строке - вставьте ''\n'':<br />
<br />
<syntaxhighlight lang="lua"><br />
echo("this echo\nis on\nthree lines!")<br />
<br />
-- вывод на экран будет следующим:<br />
this echo<br />
is on<br />
three lines!<br />
</syntaxhighlight><br />
<br />
<br />
<br />
= Проверка ошибок в вашем коде =<br />
<br />
Несомненно, вы будете делать ошибки, когда будете кодить! В конце концов, вы всего лишь человек. Есть два типа ошибок, которые вы можете сделать в целом: когда слова, которые вы ввели, не имеют никакого смысла, или они имеют смысл, но они не делают то, что вы на самом деле думали и намереваетесь сделать-или другие обстоятельства мешают исполнению в этот момент времени.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Синтаксические ошибки это же божьи коровки ===<br />
</div><br />
<br />
Когда вы вводите что-то, что не имеет смысла для Lua, это называется синтаксической [http://en.wikipedia.org/wiki/Syntax_error ошибкой]. Mudlet это поймет и покажет вам маленькую божью коровку, а также '''скажет вам, в какой строке ошибка'''. Вот пример:<br />
<br />
[[File:Syntax error.png|1000px|center]]<br />
<br />
В функции ''echo()'' на третьей строке отсутствует закрывающаяся скобка - каждая скобка в Lua, которая не зелёная, должна быть закрыта. Mudlet показал вам символ божьей коровки на псевдониме, чтобы показать, что у псевдонима есть проблема. Он также показал вам, что ( скобка должна быть закрыта на 3-й строке. Чтобы это исправить, добавьте '')'', сохраните изменения, и все будет хорошо.<br />
<br />
<br />
<br />
== Ошибки выполнения, также известные как "Консоль ошибок" ==<br />
<br />
Другой тип ошибки-это когда то, что вы ввели, имеет смысл для Lua, когда вы ввели его, но когда пришло время для того, чтобы код был действительно запущен, происходит что-то не так. Например, вы сказали Lua '''eecho ("hey!")'''-это допустимо, вы ввели его правильно, но есть одна проблема-eecho не существует. Поэтому, когда вы запускаете псевдоним, ничего не происходит. Почему?<br />
<br />
Mudlet помещает все проблемы, которые происходят при выполнении ([http://en.wikipedia.org/wiki/Runtime_error#Application_errors_.E2.80.94_exceptions runtime errors]) в Консоль Ошибок. По умолчанию она скрыта, откройте её '''нажав на кнопку ошибки(errors), которую вы видите в нижнем левом углу'''. Именно здесь ошибка протоколируется - а не в главном окне, так что вы не будете заражены спамом, когда совершаете ошибку в куске кода, что случается очень часто.<br />
<br />
Opening it up will show this:<br />
<br />
[[File:Runtime error.png|1000px|center]]<br />
<br />
Let's analyse the message that's shown to us. ''object:<Some random alias>'' means that the Mudlet name you gave to the thing that had a problem is ''Some random alias'' - which is, indeed, our alias. ''function'' will tell you ''Alias'', ''Trigger'', ''Script'' or something else - this helps you locate the problematic item in question.<br />
<br />
Next red line is the actual error: it's saying that on line 2 (it's off by one - so actually line 1), ''eecho'' is a '''nil value'''. In Lua, nil means doesn't exist. Hence what it's telling you is that eecho does not actually exist! Change it to ''echo'', run it again, and there will be happiness.<br />
<br />
That's it for now - this page in time will be improved with common techniques you can use to diagnose errors quickly, etc... if you know anything about this, feel free to add it here!<br />
<br />
<br />
<br />
<span id="triggers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Триггеры ==<br />
</div><br />
<br />
Triggers are an automation feature offered in all MUD clients. They help you respond quicker a particular situation and generally make things more convenient for you since you need to do less manual work as your triggers will do the hard work for you often times. This helps you concentrate more on the important aspects of the game and lessen stress. <br />
<br />
The way a trigger works is simple: You define some text that you want to trigger some action. This is called the trigger pattern. When the trigger "sees" this text in the MUD output, it’ll run the commands you’ve told it to. <br />
<br />
Simple example: Whenever you see a bunny, you want to attack it (meanie!). <br />
<br />
# You type "bunny" in the data field titled "1" to add this word to the list of texts this trigger fires on. Make sure the dropdown next to it says "substring". <br />
# Now you type "kill bunny" in the field called "Command". This will be the command that the trigger will send to your game whenever the trigger fires. <br />
# Finally click "Save Item" to save your new trigger and also click "Activate". By doing this, the blue checkbox icon in front of the trigger name (in the trigger tree on the left side) gets checked. The trigger is now activated.<br />
<br />
[[File:Trigger intro.png|1000px|center]]<br />
<br />
As the trigger is active, each time the word "bunny" will appear in the MUD output, your trigger will issue the command "kill bunny" automatically. It will repeat this as long as the trigger stays active. When you want to stop hunting bunnies, you can simply select the bunny trigger and then click on the padlock icon to deactivate the trigger. The check mark will vanish and the trigger will stop firing until you re-enable it again via the padlock icon. <br />
<br />
You can also put triggers in a group, then lock a group of triggers or an entire trigger branch. If you do that, all triggers in this group or branch will be locked until you remove the lock again. The locking starts from the root of the tree down to the end. As soon as a lock is met the trigger engine will skip the locked branch. Locking and unlocking branches is one of the most common actions you have to take care of when playing. For example, you can turn on your defensive triggers when engaging into a battle and you turn them off afterwards, or you turn on your harvesting triggers only when you are going to harvest.<br />
<br />
Beginners should use Mudlet's automated highlight triggers in the beginning to highlight the text that has been triggered on to get the hang of the different trigger and pattern types. Click on the "highlight trigger" option and pick a foreground and a background color that you like to highlight your trigger with. When the trigger matches it automatically highlights its pattern. This is the most used form of triggers in mudding as it is a quick way of highlighting words that are important to you at the moment. You don’t have to know anything about scripting, regular expressions etc. to use highlight triggers. Just type in the word you like to be highlighted, select appropriate colors, save the new trigger and activate it.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление одного неизвестного слова ===<br />
</div><br />
<br />
You can also set up a trigger to gather the weapons, gold or whatever skeletons could carry around with them. Since we do not know what the loot is exactly just yet, we will need to set up a trigger to match the line, identify the loot and take whatever it is that was dropped. <br />
<br />
Examples for messages received could be:<br />
<br />
The skeleton drops ring.<br />
The skeleton drops gold.<br />
The skeleton drops scimitar.<br />
The skeleton drops wooden key.<br />
<br />
"The skeleton drops " (including the last space character) is the generic segment of the line, but the loot itself varies. Thus, we need to tell the client to take whatever the skeleton dropped. We do this by setting up a so-called regular expression:<br />
<br />
# In the data field titled "1" write the following '''perl regex''' type pattern: <syntaxhighlight lang="lua">^The skeleton drops (.+)\.$</syntaxhighlight><br />
# Make sure to change the dropdown menu for this line to "perl regex" as well<br />
# In the big script box below write the following lua code: <syntaxhighlight lang="lua">send("take " .. matches[2])</syntaxhighlight><br />
<br />
[[File:Trigger intro 2.png|1000px|center]]<br />
<br />
The regular expression (.+) matches any characters that the client receives between "The skeleton drops " (NB: notice the blank/space character at the end) and the full-stop symbol that ends the sentence. Know that the variable matches[2] simply transfers the first matched text fitting the search criteria into the output. For this example, it will be the dropped loot we now will take automatically. This text may actually contain more than one word, like in the fourth example shown above. <br />
<br />
In case you may wonder, matches[1] contains the entire line in whitch the matched text was found, whereas matches[2] contains only the first capture group. More on this in section two of the manual. The symbols ^ and $ indicate the start and end of a whole line.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление много неизвестных слов ===<br />
</div><br />
<br />
Now, we don't want to take only loot from skeletons but from many different sources.<br />
<br />
Примерами могут быть:<br />
<br />
The skeleton drops ring.<br />
The giant drops gold.<br />
The king drops scimitar.<br />
The box drops wooden key.<br />
<br />
So let’s make a trigger that would gather the loot from anybody:<br />
<br />
# In data field "1" write: <syntaxhighlight lang="lua">^(.+) drops (.+)\.$</syntaxhighlight><br />
# Select '''perl regex''' type pattern again<br />
# Below write the lua code: <syntaxhighlight lang="lua">send("take " .. matches[3])</syntaxhighlight><br />
<br />
[[File:Trigger intro 3.png|1000px|center]]<br />
<br />
In this case, any time somebody, or something, "drops" something or someone else, the client will pick it up. Note that we used matches[3] instead of matches[2] this time, in order to pick up the second match. If we used matches[2], we’d end up picking up the skeleton’s corpse.<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Сопоставление известных вариантов ===<br />
</div><br />
<br />
If you’re playing a MUD in English, you’ll notice that these triggers probably won’t work due to English syntax. Compare:<br />
<br />
Скелет падает кольцо.<br />
Скелет падает кольцо.<br />
<br />
Chances are that you’ll see the later case a little more often. If we used our old regex, the trigger would produce something like this.<br />
<br />
TRIGGERED LINE: The skeleton drops a ring.<br />
OUR REACTION: take a ring<br />
<br />
However most MUDs can’t handle determiners in user-input, such as articles (i.e. a, an, the) or quantifiers (e.g. five, some, each). In effect, our triggered reaction won't suffice. Instead we would need to react with just "take ring" again.<br />
<br />
To correctly handle lines like this, we could either create multiple triggers matching every possible article, which could become very cumbersome. Instead we make one regular expression filtering out all these words and phrases:<br />
<br />
# Write a new '''perl regex''' type pattern: <syntaxhighlight lang="lua">(.+) drops (a|an|the|some|a couple of|a few|) (.+)\.$</syntaxhighlight><br />
# With this script: <syntaxhighlight lang="lua">send("take " .. matches[4])</syntaxhighlight><br />
<br />
[[File:Trigger intro 4.png|1000px|center]]<br />
<br />
Once again, note that this time we are using the third matched group through matches[4] now. <br />
<br />
{{note}}<br />
Certain other languages, with a morphology richer than that of English, might require a somewhat different approach. If you’re stuck, and your MUD-administrators don’t prohibit the use of triggers, try asking on the corresponding world’s forums.<br />
<br />
For more information, see the chapter Regular Expressions.<br />
<br />
== Basic Regex Characters ==<br />
<br />
You already know <code>(.+)</code> which will match to any and all characters that follow until the end of line or another specific text that you may put in your regex. How about if you only want to match to certain type of characters?<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение номеров из триггеров ====<br />
</div><br />
<br />
Wildcards from triggers are stored in the matches[] table. The first wildcard goes into matches[2], second into matches[3], and so on, for however many wildcards do you have in your trigger.<br />
<br />
For example, you’d like to say out loud how much gold did you pick up from a slain monster. The message that you get when you pick up the gold is the following:<br />
<br />
Вы подбираете 16 золотых.<br />
<br />
Триггер, соответствующий этой схеме может быть:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^You pick up (\d+) gold\.$</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">echo("I got " .. tonumber(matches[2]) .. " gold!")</syntaxhighlight><br />
<br />
In your code, the variable matches[2] will contain the amount of gold you picked up - in this case, 16. Now you say out loud how much gold you did loot. Notice also that (\d+) will only recognize numbers but not letters or a space character.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
==== Извлечение слов из триггеров ====<br />
</div><br />
<br />
Here’s a more advanced example by Heiko, which makes you talk like Yoda:<br />
<br />
# Perl Regex: <syntaxhighlight lang="lua">^say (\w+) *(\w*) .*?(.*)</syntaxhighlight><br />
# Script: <syntaxhighlight lang="lua">send( "say "..matches[4].." "..matches[2].." "..matches[3] )</syntaxhighlight><br />
<br />
The trigger will recognize that you say something, and save in seperate groups the first word, the second word and then the rest of you text. Here the \w wildcards will match any numbers or letters but no non-alphanumeric characters. It then shows you say the rest of the text first, then the first word and finally the second word. Notice this will only affect the text displayed for yourself, but if you want to also adjust the text you are sending to other players, please see the [[#Aliases|chapter about aliases]].<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Выделение слов ===<br />
</div><br />
<br />
To highlight something in the MUD output, make a trigger and use the "highlight trigger" option to highlight the matched trigger pattern.<br />
<br />
Optionally, you can also make use of the [[Special:MyLanguage/Manual:Lua_Functions#bg|bg()]] and [[Special:MyLanguage/Manual:Lua_Functions#fg|fg()]] functions in scripting to highlight.<br />
<br />
<br />
<span id="keybindings"></span><br />
<br />
= Keybindings =<br />
<br />
Keybindings (also known as hotkeys or macros), are in many respects very similar to aliases. However, instead of typing in what you want to be done (maybe including additional parameters) and pressing Enter, you simply hit a single key (or combination of keys) to let Mudlet do the work.<br />
<br />
Example - You don’t drink tea, you sip it!<br />
You’re participating in an in-game tea sipping contest. The winner is the first person to sip an Earl Grey, should the quiz-master make a vague reference to a series of tubes, or a Ceylon Mint, if he begins talking about the specific theory of relativity. In order to give us a competitive advantage, we will define two keybindings:<br />
<br />
HOTKEY: F1<br />
command on button down: sip earl gray<br />
<br />
HOTKEY: F2<br />
command on button down: sip ceylon mint<br />
Now you just have to listen, or rather read, carefully and hit either F1 or F2 to claim that prize.<br />
<br />
Another practical use for keybindings would be creating a so-called "targeting system", which is especially useful for grinding down armies of pumpkin-men in MUDs without auto-attack. See the Variables chapter for further details.<br />
<br />
Example instructions on how to make a keybinding (for a set of settings for binding the keypad):<br />
<br />
# Click the '''Keys''' button: [[File:Keys button.jpg]] <br />
# If you wish to group them together, click the '''Add Group''' button<br />
# Then name your group, ''Keypad'' for instance<br />
# With the group selected now click the '''Add Item''' button<br />
# Name it, let's say ''North'', in the '''Name:''' widget<br />
# If you only need a single command, like ''north'' for our example, place it into the '''Command:''' widget, otherwise skip to step 9<br />
# Click the '''Grab New Key''' button<br />
# Click the '''button sequence''' you want to use for your keybinding, ''keypad 8'' for north<br />
# Now if you need additional code to execute when you click your keybinding, or want more complicated code, place it into the giant code box.<br />
# Click the '''Save Item''' button if done or '''New Item''' button if not.<br />
# Click the '''Activate''' button when finished to make sure they work.<br />
<br />
Here is a link to the resulting keybinding XML file on the forums: [http://forums.mudlet.org/viewtopic.php?f=6&t=2163]<br />
<br />
<br />
<br />
<br />
<span id="timers"></span><br />
<br />
<div class="mw-translate-fuzzy"><br />
== Таймеры ==<br />
</div><br />
<br />
Timers, as the name suggests, can be used to execute a specific command at a certain time, after a certain time or once every so often. They can be used by clicking in the "timer" editor, or direcly in your script.<br />
<br />
To use a simple timer that does something after a period, write like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
tempTimer(seconds, [[code]])<br />
</syntaxhighlight><br />
<br />
Seconds needs to be a number, the time until the timer starts. Code can be any commands which you want executed then.<br />
<br />
{{note}} Seconds can be a decimal, so 0.5 for half a second, or 1 for a full second will both work as expected.<br />
<br />
Here's a finished example which you can copy and put in your code directly:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, [[ echo("hello!\n") ]])<br />
</syntaxhighlight><br />
<br />
You can combine both normal and timed commands, for example as code in an alias or keybinding:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this code will let you go north immediately, then go east after 2 seconds <br />
send("n")<br />
tempTimer(2, [[ send("e") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} All timers which are made at the same time, will start counting from this common point in time, not relative to each other - so if you want to make one timer go off 1 second after another, '''don't do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- incorrect:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(1, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
Both of these timers will go off at once, because both started together, right away! Instead, '''do this''':<br />
<br />
<syntaxhighlight lang="lua"><br />
-- correct:<br />
tempTimer(1, [[ echo("hello!\n") ]])<br />
tempTimer(2, [[ echo("how are you?\n") ]])<br />
</syntaxhighlight><br />
<br />
{{note}} If you do not want to put all your timed code in <nowiki>[[ brackets ]]</nowiki> there is another way of writing the same example. (This is available since Mudlet 3.5)<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this timer will greet you exactly 2 seconds after it was made<br />
tempTimer(2, function() echo("hello!\n") end)<br />
</syntaxhighlight><br />
<br />
That's it for the basics of scriptable timers in Mudlet. Want to know more? Here is a '''[[Special:MyLanguage/Manual:Technical Manual#Timer Engine|full description of timers in Mudlet]]'''.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Кнопки ==<br />
</div><br />
<br />
You can use Mudlet to create simple buttons on your screen without much coding at all - you can attach button bars to the top, left or right side of the screen. Each of these locations can contain an infinite number of button bars that are shown when active or hidden when inactive. You can also create drop-down menus or or two-state buttons - ones that you can click on and they stay pressed down.<br />
<br />
To get started with buttons, '''make a group''' (buttons have to be in a group to show) and add buttons inside them. Active buttons or groups to make them be visible. Here's an example - by making a new group and a button inside it, and activating both, we got a button to spawn:<br />
<br />
[[File:Buttons Start.png|1000px|center|]]<br />
<br />
Buttons show '''in the order they appear in''' - so if you'd like one button to be above another, just drag it visually in the editor!<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Меню ===<br />
</div><br />
<br />
An important use case for buttons is to have various menus which contain a number of checkbox buttons or sub menus in order to quickly set various scripting configuration or other options in your scripts. To start a menu of buttons, create another group inside your toolbar group and add individual buttons inside it, like so:<br />
<br />
[[File:Buttons Menu.png|center|]]<br />
<br />
To change the side of Mudlet that the buttons use, change the '''Dock area <side>''' option and save. You can also make buttons align themselves top to bottom or left to right with the '''Orientation <horizontal or vertical>''' option.<br />
<br />
[[File:Changing button group position.png|center|]]<br />
<br />
<br />
<br />
== Making buttons do stuff ==<br />
<br />
Buttons are half as useful only being there. You can also make them do commands for you for when you press them! To make a button do your command, or alias, or anything - type it into the ''Command on Button Down'' field. Pressing the button will do that command then:<br />
<br />
[[File:Button command.png|center|]]<br />
<br />
You can also make a button do two things, toggling between each. To do that, '''enable the ''Push Down Button''''' option, and type the command you'd like your button to do when it's released in the ''Command on Button Up'' field. <br />
<br />
[[File:Alternating button.png|center|]]<br />
<br />
{{note}}<br />
If you'd like to include & in the button name, put double && - a single & will act as a mnemonic to underline the shortcut letter.<br />
<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
=== Окраска & настройка кнопок ===<br />
</div><br />
<br />
To change how your buttons look, you put descriptions into the ''CSS Style Sheet'' field, in the format of '''<a word describing something>: <how it should look>;'''. For example, if you'd like to make the button be red, put ''background-color: red;'' into the CSS box:<br />
<br />
[[File:Red button.png|center|]]<br />
<br />
A full list of names you can use to customize your buttons view is [http://qt-project.org/doc/qt-4.8/stylesheet-reference.html#list-of-properties available here]. Take note of how that page has the descriptions inside {} brackets - you don't need them, only paste what's inside them in Mudlet.<br />
<br />
Applying some skills, we can make our buttons look much more aesthetic:<br />
<br />
[[File:Sexy Buttons.png|center|]]<br />
<br />
This was the code used, feel free to start your buttons off with it:<br />
<br />
<syntaxhighlight lang="lua"><br />
color: white; background-color: orange; font-size: 12px;<br />
padding: 6px;<br />
border-radius: 5px;<br />
</syntaxhighlight><br />
<br />
<br />
<br />
== Managed layouts ==<br />
<br />
To get your buttons to align into rows or columns (that depends on their orientation), add a number to the ''Number of columns or rows'' field. Here's an example with two columns on the left:<br />
<br />
[[File:Two row alignment.png|center|]]<br />
<br />
Here's another example with three columns on the left:<br />
<br />
[[File:Three column alignment.png|center|]]<br />
<br />
{{note}}<br />
You can change how your buttons are aligned within rows by clicking on the button group - it will cycle through different possible configurations for you.<br />
<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Встроенные aлиасы ==<br />
</div><br />
<br />
The following aliases are available by default in new Mudlet profiles.<br />
<br />
{| class="wikitable"<br />
|-<br />
! Alias !! Description !! Examples<br />
|-<br />
| lua || Run Lua code from the input line. || lua print("hello")<br>lua 2+2<br>lua clearWindow()<br />
|-<br />
| `echo || Simulate text from the game to test your triggers.<br>You can use $ for a new line. || `echo You see a rabbit cross the road.<br>`echo line1$line2<br />
|-<br />
| : || Send a command to all open profiles. ||:hello<br>:follow alice<br>:e<br />
|}<br />
<br />
If an alias on the list isn't working for you - try copying it from a new profile, since existing profiles will not get new aliases as they're introduced to Mudlet.<br />
<br />
<div class="mw-translate-fuzzy"><br />
== Разные примеры ==<br />
</div><br />
<br />
Вот еще несколько разных примеров.<br />
<br />
'''Mud syntax''': ''get coins from corpse'' and also ''get coins from corpse 3''.<br />
'''Alias Pattern''': '''^gcc(?:\s(\d+))?$''' (can accept simply ''gcc'' and also ''gcc 3'' for example).<br />
<syntaxhighlight lang="lua"><br />
send("get coins from corpse " .. (matches[2] or "") )<br />
</syntaxhighlight><br />
<br />
'''Mud syntax''': ''unlock northwest with steel key''<br />
'''Alias Pattern''': '''^un (\w+) (.*)$'''<br />
<syntaxhighlight lang="lua"><br />
send("unlock " .. matches[2] .. " with " .. matches[3] )<br />
</syntaxhighlight><br />
<br />
See also: [[Special:MyLanguage/Manual:Technical Manual|Mudlet Technical Manual]]<br />
<br />
[[Category:Mudlet Manual]]</div>RodeoS