### Wurst 'Hello World' Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/wurstbeginner.md Demonstrates a basic WurstScript program. It includes package declaration, comments, an init block, and the print function to display 'Hello World' in-game. This is the first code snippet typically encountered when starting with WurstScript. ```wurst package Hello /* Hello and welcome to Wurst! This is just a demo package. You can modify it to tests things out and then later delete it and create your own, new packages. Enjoy WurstScript? Consider starring our repo https://github.com/wurstscript/WurstScript */ init print("Hello World") ``` -------------------------------- ### Spell Creation Example in WurstScript Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/wurstbeginner.md An example demonstrating the creation of a spell in WurstScript. It utilizes various imported modules for timers, group operations, event handling, and data management with HashMaps. The spell applies damage and a buff to units in range. ```wurst package Conflagration import ConflagrationObjects import ClosureTimers import ClosureForGroups import HashMap import ClosureEvents let buffId = BUFF_OBJ.abilId let buffMap = new HashMap() init EventListener.onPointCast(SPELL_ID) (caster, tpos) -> flashEffect(SPELL_EFFECT_PATH, tpos) doAfter(SPELL_EFFECT_DURATION) -> forUnitsInRange(tpos, SPELL_RADIUS) u -> if u.hasAbility(buffId) caster.damageTarget(u, BONUS_DAMAGE) flashEffect(BONUS_EFFECT_PATH, tpos) caster.damageTarget(u, BASE_DAMAGE) u.addAbility(buffId) if buffMap.has(u) destroy buffMap.get(u) let cb = doAfter(BUFF_DURATION) -> if buffMap.has(u) buffMap.remove(u) u.removeAbility(buffId) buffMap.put(u, cb) ``` -------------------------------- ### Hello World Example in WurstScript Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Provides a basic 'Hello World' program in WurstScript, demonstrating package structure, the import mechanism for using external code (like the Printing package), and the execution of an init block when the map starts. ```wurst package HelloWurst // to use resources from other packages we have to import them at the top import Printing // the init block of each package is called when the map starts init // calling the print function from the Printing package print("Hello Wurst!") ``` -------------------------------- ### WurstScript Lambda and Closure Examples Source: https://context7.com/wurstscript/wurstscript.github.io/llms.txt Demonstrates the usage of lambdas and closures in WurstScript for functional programming. Includes examples of type inference, explicit parameters, capturing outer variables, multi-line lambdas, and lambda block syntax. Requires 'LinkedList' and 'ClosureTimers' imports. ```wurst package LambdaExamples import LinkedList import ClosureTimers interface Predicate function test(T t) returns boolean interface Transformer function transform(T t) returns R function filter(LinkedList list, Predicate pred) returns LinkedList let result = new LinkedList for elem in list if pred.test(elem) result.add(elem) return result init let numbers = asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // Lambda with type inference let evens = filter(numbers, x -> x mod 2 == 0) // Lambda with explicit parameter let greaterThan5 = filter(numbers, (int x) -> x > 5) // Closures capture outer variables let threshold = 7 let aboveThreshold = filter(numbers, x -> x > threshold) // Multi-line lambda with begin-end doAfter(5.) -> let u = GetTriggerUnit() u.kill() flashEffect(Abilities.frostNovaTarget, u.getPos()) // Lambda block syntax (cleaner for last argument) forUnitsInRange(vec2(0, 0), 500.) u -> if u.isAlive() and u.isEnemy(Player(0)) u.kill() ``` -------------------------------- ### WurstScript Lambda Type Examples Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Provides examples of WurstScript lambda expressions and their corresponding function types. It shows the syntax for defining the parameter types and return type of a lambda, such as `() -> integer` or `(real) -> real`. ```wurst () -> 1 // type: () -> integer (real r) -> 2 * r // type: (real) -> real (int x, string s) -> s + I2S(x) // type: (int, string) -> string ``` -------------------------------- ### WurstScript ScrollTo with Queueing (Go Back Example) Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/demo/index.html Provides an example of using the queue option to scroll back to the top (position 0) with a specified duration. This demonstrates sequential animation execution. ```javascript $(...).scrollTo(0, 800, {queue:true}); ``` -------------------------------- ### WurstScript Inheritance Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Provides an example of class inheritance in WurstScript. A 'FireballMissile' class extends 'Missile', demonstrating how to call the superclass constructor using 'super()' and override methods with the 'override' annotation. ```wurst class Missile construct(string fx, real x, real y) // ... function onCollide(unit u) // a fireball missile is a special kind of missile class FireballMissile extends Missile // we construct it using a fireball fx construct(real x, real y) super("Abilities\Weapons\RedDragonBreath\RedDragonMissile.mdl", x, y) // a fireball does some special things when it collides // with a unit, so we override the onCollide method override function onCollide(unit u) // create a big explosion here ;) ``` -------------------------------- ### Manage Unit Buff Timers with HashMap Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/wurstbeginner.md This code initializes and utilizes a HashMap to store and manage active buff timers for individual units. It allows for checking existing buffs, clearing them, and starting new timers to control buff durations. This is crucial for preventing multiple instances of the same buff on a unit and managing their lifecycles. ```WurstScript let buffMap = new HashMap(); // Example of usage within a buff application function: function applyBuff(unit u, real duration) { if (buffMap.hasKey(u)) { let existingTimer = buffMap.get(u); existingTimer.destroy(); // Destroy existing timer if buff is reapplied } let timer = doAfter(duration, () => { // Logic to remove buff effects when timer ends buffMap.remove(u); }); buffMap.put(u, timer); } ``` -------------------------------- ### Wurst Init Block Execution at Map Start Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Demonstrates the basic syntax for an 'init' block within a Wurst package. Operations within this block execute at map start, after global variables are initialized. Errors in init blocks halt map initialization. ```wurst package MyPackage init print("this is the initblock") ``` -------------------------------- ### Jurst Code Example 1: Similar to vJass Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_tutorials/legacymaps.md Demonstrates Jurst syntax that closely resembles vJass, including library declarations and trigger initialization. This code compiles within the Wurst environment. ```wurst library LooksLikeVjass initializer ini private function ini takes nothing returns nothing local trigger t = CreateTrigger() t = null endfunction endlibrary ``` -------------------------------- ### Wurst Code Example: Static Print (Illustrates Limitation) Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_tutorials/jhcr.md Demonstrates a Wurst code snippet with a static print statement in an 'init' block. This example highlights that package initializers are not re-run after a hot code reload, meaning the 'Hello' message will not appear again upon reload. ```wurst init print("Hello") ``` -------------------------------- ### Install with Bower Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Installs the jquery.scrollTo plugin using the Bower package manager. Ensure Bower is installed and configured in your project. ```bash bower install jquery.scrollTo ``` -------------------------------- ### WurstScript HashList Basic Usage Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/data/hashlist.md Demonstrates the basic usage of the generic HashList in WurstScript. It shows how to create a HashList, add elements, check for element containment using 'hash()', and retrieve elements using 'get()'. ```WurstScript @Test function testList() let list = new HashList list.add(1, 2, 3, 4, 5) // Contains check list.hash(5).assertTrue() // Get let entry = list.get(2) ``` -------------------------------- ### Bitset Usage Example in WurstScript Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/data/bitset.md This WurstScript code demonstrates how to use a bitset to manage a set of boolean options within a class. It shows how to add, remove, and check for the presence of options represented by an enum. ```wurst public enum Option VISIBLE TARGETIMAGE PHYSICALSPELL UNIVERSALSPELL UNIQUECAST public class ChannelAbilityPreset extends AbilityDefinitionIllidanChannel private bitset optionSet = bitset(0) function presetOption(Option opt, boolean flag) let pow = opt castTo int if optionSet.contains(pow) if not flag optionSet = optionSet.remove(pow) else if flag optionSet = optionSet.add(pow) presetOptions(lvl -> optionSet.val) function hasOption(Option option) returns boolean return optionSet.contains(option castTo int) ``` -------------------------------- ### Basic Assertion Example in Wurst Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/_wurst/wurstunit.md Demonstrates a less informative way to assert equality between two integers. This method provides minimal debug output upon failure. ```wurst // Not ideal assertTrue(someInt == someOtherInt) ``` -------------------------------- ### Global DialogBox with Spellcast Display Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/util/dialogbox.md Shows how to declare a global DialogBox and display it when a specific spell is cast. This example assumes the DialogBox is initialized and buttons are added elsewhere. ```wurst DialogBox goldBox init doAfter(0.1) -> goldBox = new DialogBox("Extra starting gold?") // add buttons dBox.addButton("Yes") -> ... EventListener.onCast(SPELL_ID) (caster) -> GOLD_BOX.display(caster, true) ``` -------------------------------- ### Install with npm Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Installs the jquery.scrollTo plugin using the npm package manager. This command is run in your project's terminal. ```bash npm install jquery.scrollto ``` -------------------------------- ### Using Generic Set with Concrete Type Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Demonstrates how to instantiate and use the generic 'Set' interface with a concrete type, 'Missile' in this example, showcasing type-safe collection management. ```wurst // create a set of missiles Set missiles = new SetImpl(); // add a missile m missiles.add(m); ``` -------------------------------- ### WurstScript Static Elements Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Demonstrates static variables and functions in WurstScript using the 'static' keyword. Static members belong to the class itself, not instances, and can be accessed directly using the class name. ```wurst class Terrain static var someVal = 12. static int array someArr static function getZ(real x, real y) returns real ... function foo() let z = Terrain.getZ(0, 0) // call with $Classname$.$StaticFunctionName$() let r = Terrain.someVal // Same with members let s = Terrain.someArr[0] ``` -------------------------------- ### WurstScript Generics Examples Source: https://context7.com/wurstscript/wurstscript.github.io/llms.txt Illustrates the use of generics in WurstScript for creating reusable data structures and functions. Covers generic classes, interfaces, functions, and extension functions. Demonstrates type safety and flexibility with different types. ```wurst package GenericExamples // Generic class class Pair A first B second construct(A first, B second) this.first = first this.second = second function swap() returns Pair return new Pair(second, first) // Generic interface interface Container function add(T element) function get(int index) returns T function size() returns int // Generic function function findFirst(LinkedList list, Predicate pred) returns T for elem in list if pred.test(elem) return elem return null // Generic extension function function LinkedList.any(Predicate pred) returns boolean for elem in this if pred.test(elem) return true return false init let pair = new Pair("Gold", 100) print(pair.first + ": " + pair.second.toString()) let swapped = pair.swap() // swapped is Pair let units = new LinkedList let hasEnemy = units.any(u -> u.isEnemy(Player(0))) ``` -------------------------------- ### Typecasting for Primitive/Handle Generic Binding Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Provides example functions 'unitToIndex' and 'unitFromIndex' to facilitate binding generic type parameters to primitive or handle types, which require explicit conversion functions. ```wurst function unitToIndex(unit u) returns int return u.getHandleId() function unitFromIndex(int index) returns unit data.saveFogState(0,ConvertFogState(index)) return data.loadUnit(0) ``` -------------------------------- ### WurstScript Class Constructor Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Defines a WurstScript class 'Pair' with a constructor to initialize two integer members. The constructor is called using the 'new' keyword. It also includes a method to add the two integers. ```wurst class Pair int a int b construct(int pA, int pB) a = pA b = pB function add() returns int return a + b function test() let pair = new Pair(2, 4) let sum = p.add() print(sum) ``` -------------------------------- ### Wurstscript: Unit Test for Arithmetic Operation Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_news/bestofthewurst4.md An example of a simple arithmetic unit test in Wurstscript. It calculates a value, defines an expected result, and asserts their equality using `assertEquals`. ```wurst @Test function example() let actual = (10 .squared()) * 6 let expected = 600 actual.assertEquals(expected) ``` -------------------------------- ### WurstScript IterableMap Iteration Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/data/hashmap.md Shows how to use the `IterableMap` in WurstScript to iterate over its key-value pairs. It demonstrates adding entries and then using a for-each loop to access each key and its corresponding value, printing them to the console. ```wurst let iterMap = new IterableMap iterMap.put(0, 3) iterMap.put(1, 2) iterMap.put(2, 1) iterMap.put(3, 0) for key in iterMap let val = iterMap.get(key) Log.info("key: " + key.toString() + " val: " + val.toString()) ``` -------------------------------- ### WurstScript 'ondestroy' Block Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Shows the 'ondestroy' block in WurstScript, which is executed before a class instance is destroyed. This is useful for cleanup operations, such as removing a unit reference. ```wurst class UnitWrapper unit u ... ondestroy u.remove() ``` -------------------------------- ### Wurst Class Definition and Object Instantiation Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Provides an example of defining a 'Caster' class in Wurst, including its variables, constructor, a method to cast a spell, and an 'ondestroy' function. It also shows how to instantiate, use, and destroy objects of this class. ```wurst let dummyCaster = new Caster(200.0, 400.0) dummyCaster.castFlameStrike(500.0, 30.0) destroy dummyCaster ``` ```wurst class Caster // opening the class-block. "Caster" is the name of the class unit u // class variables can be defined anywhere inside a class construct(real x, real y) u = createUnit(...) function castFlameStrike(real x, real y) u.issueOrder(...) ondestroy u.kill() ``` -------------------------------- ### Install jquery.matchHeight.js using script tag Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-match-height/README.md To use jquery.matchHeight.js, first include the jQuery library, followed by the jquery.matchHeight.js script in your HTML file. This makes the plugin's functionality available for use. ```html ``` -------------------------------- ### WurstScript HashSet Usage Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/data/hashlist.md Illustrates the usage of HashSet in WurstScript, highlighting its property of storing only unique elements. The example shows how to create a HashSet, add elements (including duplicates), check the size, and retrieve elements. ```WurstScript @Test function testList() let hset = new HashSet hset.add(1, 2, 2, 4, 4) // Size check hset.size().assertEquals(3) // Get hset.get(2).assertEquals(4) ``` -------------------------------- ### WurstScript Automated Unit Tests with Assertions Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md This snippet demonstrates how to write automated unit tests in WurstScript using the `@Test` annotation and the `Wurstunit` package for assertions. It shows examples of successful and failed tests, illustrating the expected output format. ```wurst package Test import Wurstunit @Test public function a() 12 .assertEquals(3 * 4) @Test public function b() 12 .assertEquals(5 + 8) ``` -------------------------------- ### Create Hero Unit Definition with Wurstscript Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/objediting/units.md Defines a hero unit in Warcraft III using Wurstscript's HeroDefinition. Hero IDs must start with an uppercase letter. This example demonstrates setting hero-specific attributes like icon, model, abilities, and starting stats. ```wurst let ESC_STRONG_ID = compiletime(HERO_ID_GEN.next()) @compiletime function gen() new HeroDefinition(ESC_STRONG_ID, UnitIds.paladin) ..setIconGameInterface(Icons.bTNFootman) ..setIconScoreScreen("") ..setModelFile(Units.theCaptain1) ..setCollisionSize(0) ..setNormalAbilities(commaList(GHOST_VIS_ID, AbilityIds.inventory)) ..setHotkey("") ..setProperNames(commaList("Mike", "Jason", "Rocky", "Herold", "Arthur", "Chev")) ..setProperNamesUsed(6) ..setName("|cff084294Strong Escaper") ..setManaInitialAmount(0) ..setStartingAgility(0) ..setStartingIntelligence(0) ..setStartingStrength(0) ..setHitPointsMaximumBase(300) ..setAgilityPerLevel(0) ..setStrengthPerLevel(0) ..setIntelligencePerLevel(0) ..hideHeroDeathMsg(true) ``` -------------------------------- ### Wurst.build Configuration Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_tutorials/wurstbuild.md This YAML snippet demonstrates the structure and common properties of a wurst.build file. It includes project name, dependencies, and detailed map data for build tasks. Dependencies are specified as URLs to Git repositories, and map data covers aspects like name, author, scenario details, player/force configurations, and game options. ```yaml projectName: Escape Builder Reloaded dependencies: - https://github.com/wurstscript/wurstStdlib2 - https://github.com/frotty/frentity buildMapData: name: JustAnotherWurstMap # Name shown ingame, may be colored fileName: MyWurstMap # Name of the map file author: SomeWurstUser # Name of the author scenarioData: description: WurstScript powered! # The map's description suggestedPlayers: DefaultSuggestedPlayers # Hint text displayed in lobby loadingScreen: model: MyModel.mdx # Use 'model' to specify a custom model as loading screen background: Generic # Use 'background' to use an existing loading screen title: DefaultTitle subTitle: DefaultSubtitle text: DefaultText optionsFlags: hideMinimapPreview: false forcesFixed: false maskedAreasPartiallyVisible: false showWavesOnCliffShores: false showWavesOnRollingShores: false useItemClassificationSystem: false players: - id: 0 name: DefaultPlayer race: HUMAN controller: USER fixedStartLoc: false forces: - name: DefaultForce playerIds: - 0 flags: allied: true alliedVictory: true sharedVision: true sharedControl: false sharedControlAdvanced: false ``` -------------------------------- ### Wurstscript: Basic Unit Tests for Data Structures and Operations Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_news/bestofthewurst4.md Demonstrates unit tests for a HashList, linear vector interpolation, and string joining. These tests verify the correctness of common data structure and utility functions in Wurstscript. ```wurst @Test function testAdd() new HashList..add(5).get(0).assertEquals(5) @Test function linearVecTest() let v = linear(vec2(3,4), vec2(6,2), 0.5) v.x.assertEquals(4.5) v.y.assertEquals(3) @Test function testJoin() new LinkedList()..add("this")..add("is")..add("a")..add("string") .joinBy(" ").assertEquals("this is a string") ``` -------------------------------- ### Wurst Code Example: Periodic Print (Illustrates Reload Behavior) Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_tutorials/jhcr.md Shows a Wurst code snippet that prints a message periodically. This example illustrates that modifications to code within repeating functions (like `doPeriodically`) are reflected after a hot code reload, whereas static initialization code is not. ```wurst init doPeriodically(1.) cb -> print("Hello") // If you change this to "There" and reload, the new text will show. ``` -------------------------------- ### WurstScript Array Members in Class Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Illustrates using sized arrays as class members in WurstScript. The example shows a 'Rectangle' class with an array of 'Point' objects, including methods to get and set points by index. ```wurst class Rectangle Point array[4] points function getPoint(int index) return points[index] function setPoint(int index, Point nP) points[index] = nP ``` -------------------------------- ### Create and Display DialogBox with Buttons Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/util/dialogbox.md Demonstrates creating a DialogBox, adding buttons with click actions, and displaying it to players. Note that dialogs cannot be created during map initialization and require a delay. ```wurst init // Can't create Dialogs during map init doAfter(0.1) -> let dBox = new DialogBox("Are you a noob?") dBox.addButton("Yes") -> GetTriggerPlayer()..addGold(500) dBox.display(GetTriggerPlayer(), false) dBox.addButton("No", () -> dBox.display(GetTriggerPlayer(), false)) for i = 0 to 11 dBox.display(players[i], true) ``` -------------------------------- ### Jurst Code Example 2: Near Wurst Syntax Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_tutorials/legacymaps.md Showcases a Jurst code snippet that uses syntax very similar to Wurst, including function definitions, event registration, and anonymous functions. It highlights the ability to call Wurst standard library functions like 'print'. ```wurst package NearlyTheSameAsWurst function act() print(GetTriggerUnit().getName() + " died.") end init CreateTrigger()..registerAnyUnitEvent(EVENT_PLAYER_UNIT_DEATH) ..addAction(function act) end // Note: "end" intentionally not present here. ``` -------------------------------- ### Configure and Initialize Algolia InstantSearch.js Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_includes/algolia.html This snippet shows how to instantiate the InstantSearch.js object with Algolia credentials and configure search widgets. It requires Algolia application ID, index name, and search-only API key. The output is a configured search instance ready to be started. ```javascript console.log("algolia", '{{ site.algolia.application_id }}', '{{ site.algolia.index_name }}', '{{ site.algolia.search_only_api_key }}'); // Instanciating InstantSearch.js with Algolia credentials const search = instantsearch({ appId: '{{ site.algolia.application_id }}', indexName: '{{ site.algolia.index_name }}', apiKey: '{{ site.algolia.search_only_api_key }}' }); console.log('search', search) // Adding searchbar and results widgets search.addWidget( instantsearch.widgets.searchBox({ container: '#search-searchbar', placeholder: 'Search into posts...', poweredBy: true // This is required if you're on the free Community plan }) ); search.addWidget( instantsearch.widgets.hits({ container: '#search-hits' }) ); // Starting the search search.start(); ``` -------------------------------- ### On-the-Spot DialogBox Creation Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/stdlib/util/dialogbox.md Illustrates creating a DialogBox dynamically within a function and passing the player to the callback. This method is useful for temporary dialogs. ```wurst function showBox(player p) let tempBox = new DialogBox(SOME_DYNAMIC_STRING) tempBox.addButton("OK") -> Log.info(p.getName() " as accepted.") destroy tempBox tempBox.display(p, false) ``` -------------------------------- ### Install with Composer Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Installs the jquery.scrollTo plugin using Composer, a dependency manager for PHP. This command requires Composer to be installed. ```php php composer.phar require --prefer-dist flesler/jquery.scrollto "*" ``` -------------------------------- ### Dummy Casting with WurstScript Source: https://context7.com/wurstscript/wurstscript.github.io/llms.txt Demonstrates programmatic ability casting using invisible dummy units. It includes examples for instant casts with shared dummy units and delayed/channeled spells requiring dedicated dummy units with a defined lifetime. Dependencies include DummyCaster, InstantDummyCaster, and AbilityObjEditing modules. ```wurst package DummyCasterExamples import DummyCaster import InstantDummyCaster import AbilityObjEditing // Create dummy spell at compiletime constant POLY_DUMMY_ID = compiletime(ABIL_ID_GEN.next()) constant STORM_DUMMY_ID = compiletime(ABIL_ID_GEN.next()) @compiletime function genDummySpells() new AbilityDefinitionPolymorph(POLY_DUMMY_ID) ..setDummyAbility() ..setDurationNormal(1, 5.) new AbilityDefinitionStormBolt(STORM_DUMMY_ID) ..setDummyAbility() ..setDamage(1, 100.) ..setDurationNormal(1, 2.) init // Instant cast - single shared dummy unit let target = GetSpellTargetUnit() InstantDummyCaster.castTarget(Player(0), POLY_DUMMY_ID, 1, OrderIds.polymorph, target) // Delayed/channeled spells - dedicated dummy with lifetime let caster = GetTriggerUnit() let targetPos = getSpellTargetPos() // Cross-pattern blizzard new DummyCaster(caster.getPos()) ..owner(caster.getOwner()) ..delay(15) // Dummy stays for 15 seconds ..castPoint(STORM_DUMMY_ID, 1, OrderIds.blizzard, targetPos + vec2(128, 0)) ..castPoint(STORM_DUMMY_ID, 1, OrderIds.blizzard, targetPos + vec2(-128, 0)) ..castPoint(STORM_DUMMY_ID, 1, OrderIds.blizzard, targetPos + vec2(0, 128)) ..castPoint(STORM_DUMMY_ID, 1, OrderIds.blizzard, targetPos + vec2(0, -128)) // Apply orb effect new DummyCaster() ..castTarget(AbilityIds.poisonSting, 1, OrderIds.attackonce, target) ``` -------------------------------- ### WurstScript Lambda Closure Implementation (Behind the Scenes) Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Illustrates the compiler's internal process of translating WurstScript lambda expressions into classes that implement specific interfaces. This example shows how captured variables become fields of the generated class, and how they are set when a new object of the class is created. ```wurst // (the interface was not shown in the above code, but it is the same): interface CallbackFunc function run() // compiler creates this closure class implementing the interface: class Closure implements CallbackFunc // a field for each captured variable: string s function run() // body of the lambda expression == body of the function print(s) s = s + "!" var s = "Hello!" let f = new Closure() // captured fields are set f.s = s s = "Bye!" f.run() // will print "Hello!" f.run() // will print "Hello!!" print(s) // will print "Bye!" ``` -------------------------------- ### Wurst Package Initialization Order Control with 'initlater' Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Illustrates how to manage package initialization order in Wurst using the 'initlater' keyword. This keyword postpones the initialization of an imported package, preventing cyclic dependencies and allowing manual control over the initialization sequence. ```wurst package A import initlater B import public initlater C import D ``` -------------------------------- ### Wurst Code Optimization Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_news/bestofthewurst7.md Illustrates a WurstScript code snippet and its compiled Jass output after compiler optimizations. The example shows a loop iterating through units in a group and adding HP. The optimized Jass code demonstrates efficient variable handling and loop structure. ```wurst let g = CreateGroup() for u from g u.addHP(100) ``` ```jass local group from = CreateGroup() local unit iterUnit loop exitwhen FirstOfGroup(from) == null set iterUnit = FirstOfGroup(from) call GroupRemoveUnit(from, iterUnit) call SetUnitState(iterUnit, UNIT_STATE_LIFE, GetUnitState(iterUnit, UNIT_STATE_LIFE) + 100.) endloop set from = null set iterUnit = null ``` -------------------------------- ### WurstScript LinkedList Basics and Transformations Source: https://context7.com/wurstscript/wurstscript.github.io/llms.txt Demonstrates the creation, population, stack/queue operations, and functional-style transformations (filter, map, fold) of a generic doubly-linked list in WurstScript. It also shows how to use LinkedListModule for class instances and custom sorting. ```wurst package ListExamples import LinkedList @Test function linkedListBasics() // Create and populate let list = new LinkedList list.add(1, 2, 3, 4, 5) // Factory function let numbers = asList(10, 20, 30, 40, 50) // Stack operations list.push(6) // Add to end let last = list.pop() // Remove and return last (6) // Queue operations let first = list.dequeue() // Remove and return first (1) list.size().assertEquals(4) @Test function listTransformations() let myList = asList(1, 2, 3, 4, 5, 6, 7, 8, 9) // Filter: keep values divisible by 3 let filtered = myList.filter(elem -> elem mod 3 == 0) // Result: [3, 6, 9] // Map: transform each element let doubled = myList.map(elem -> elem * 2) // Result: [2, 4, 6, 8, 10, 12, 14, 16, 18] // Fold: reduce to single value (sum) let sum = myList.foldl(0, (acc, elem) -> acc + elem) // Result: 45 // Sort with custom comparator let units = new LinkedList let target = vec2(0, 0) units.sortWith((u1, u2) -> (u1.getPos().distanceTo(target) - u2.getPos().distanceTo(target)).toInt()) let closest = units.pop() // LinkedListModule for class instances class Projectile use LinkedListModule vec2 pos construct(vec2 pos) this.pos = pos init new Projectile(vec2(100, 100)) new Projectile(vec2(200, 200)) // Iterate all instances without external list for proj in Projectile proj.pos += vec2(1, 0) ``` -------------------------------- ### Change Default Settings Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Modifies the default settings for all subsequent jQuery.scrollTo calls. This example sets the default axis to 'y' and duration to 800ms. ```javascript $.extend($.scrollTo.defaults, { axis: 'y', duration: 800 }); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Demonstrates the basic usage of jQuery.scrollTo by scrolling to a target element. The target can be a selector, DOM element, or a jQuery object. ```javascript $(element).scrollTo(target[,duration][,settings]); ``` -------------------------------- ### Scroll with Options Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/README.md Scrolls to a target with custom animation settings, such as duration, easing, and callbacks. This example scrolls with a duration of 1000ms and a custom onAfter callback. ```javascript $(element).scrollTo(target, { duration: 1000, onAfter: function(target, settings) { console.log('Scroll animation finished!'); } }); ``` -------------------------------- ### Configure Lightbox Defaults (jQuery) Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/lightbox/examples/index.html This example shows how to set default options for the `ekkoLightbox` plugin using `$.fn.ekkoLightbox.defaults`. This allows you to customize the behavior of all lightboxes without specifying options for each instance. Note that standard Bootstrap modal options like 'title' and 'footer' are excluded from direct defaults here. ```javascript $.fn.ekkoLightbox.defaults = $.extend({}, $.fn.modal.defaults, { gallery_parent_selector: '#grid' }); ``` -------------------------------- ### jQuery.scrollTo Settings Customization Examples Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/assets/plugins/jquery-scrollTo/demo/index.html Illustrates advanced configuration options for jQuery.scrollTo animations. This includes controlling the scroll axis, duration, easing, margins, offsets, progress, and callback functions. ```javascript jQuery(function( $ ){ var $settings = $('#pane-settings'); // Reset scroll to (0,0) before each animation $('#settings-examples a').click(function() { $settings.stop(true).scrollTo(0); }); // Scroll with default settings $('#settings-no').click(function() { $settings.scrollTo('li:eq(15)', 1000); }); // Scroll only horizontally $('#settings-axis').click(function() { $settings.scrollTo('li:eq(15)', 1000, { axis:'x' }); }); // Specify duration in the settings object $('#settings-duration').click(function() { $settings.scrollTo('li:eq(15)', { duration: 3000 }); }); // Use a custom easing function $('#settings-easing').click(function() { $settings.scrollTo('li:eq(15)', 2500, { easing:'elasout' }); }); // Scroll to the 'outer' position of the element (includes margins) $('#settings-margin').click(function() { $settings.scrollTo('li:eq(15)', 1000, { margin:true }); }); // Scroll with a fixed pixel offset $('#settings-offset').click(function() { $settings.scrollTo('li:eq(15)', 1000, { offset:-50 }); }); // Scroll with specific top and left pixel offsets $('#settings-offset-hash').click(function() { $settings.scrollTo('li:eq(15)', 1000, { offset:{ top:-5, left:-30 } }); }); // Scroll with offsets defined by a function $('#settings-offset-function').click(function() { $settings.scrollTo('li:eq(15)', 1000, {offset: function() { return {top:-30, left:-5}; }}); }); // Scroll to a percentage of the target element's position within the viewport $('#settings-over').click(function() { $settings.scrollTo('li:eq(15)', 1000, { over:0.5 }); }); // Scroll with specific top and left percentages $('#settings-over-hash').click(function() { $settings.scrollTo('li:eq(15)', 1000, { over:{ top:0.2, left:-0.5 } }); }); // Allow interruption of the scroll animation $('#settings-interrupt').click(function() { $settings.scrollTo('li:eq(15)', 10000, { interrupt:true }); }); // Queue animations (important for chained scrolls) $('#settings-queue').click(function() { $settings.scrollTo('li:eq(15)', 2000, { queue:true }); }); // Execute a callback after the scroll animation completes $('#settings-onAfter').click(function() { $settings.scrollTo('li:eq(15)', 2000, { onAfter:function() { $('#settings-message').text('Got there!'); } }); }); // Execute callbacks for chained animations $('#settings-onAfterFirst').click(function() { $settings.scrollTo('li:eq(15)', 1600, { queue:true, onAfterFirst:function() { $('#settings-message').text('Got there horizontally!'); }, onAfter:function() { $('#settings-message').text('Got there vertically!'); } }); }); // Provide a step function to track scroll progress $('#settings-step').click(function() { $settings.scrollTo('li:eq(15)', 2000, { step:function(now) { $('#settings-message').text(now.toFixed(2)); } }); }); // Provide a progress function to track overall animation progress $('#settings-progress').click(function() { $settings.scrollTo('li:eq(15)', 2000, { progress:function(_, now) { // 'now' represents the current scroll progress (0 to 1) } }); }); }); ``` -------------------------------- ### Lambda with Parameter for Iteration in WurstScript Source: https://github.com/wurstscript/wurstscript.github.io/blob/master/_doc/manual.md Illustrates using a lambda expression with a parameter (`u`) to iterate over units owned by a player. This example shows conditional logic within the lambda to identify towers, retrieve their properties, and perform actions like removing them and creating new units. ```wurst forUnitsOfPlayer(lastRinger) u -> if u.getTypeId() == TOWER_ID let pos = u.getPos() let facing = u.getFacingAngle() addEffect(UI.goldCredit, pos).destr() u.remove() createUnit(players[8], DUMMY_ID, pos, facing) ```