Compare commits

..
Author SHA1 Message Date
Lily 2f82f381d4 - added custom equip sounds
- tweaked armor material values
- made fireproof
- made trimmable
2023-09-08 15:25:00 -04:00
Lily 4d75103a68 WIP implementations of auspicious and malicious armor, to be completed for 1.5 2023-09-04 16:12:46 -04:00
Paul ff2db8fa11 You saw nothing 2023-09-04 18:49:38 +10:00
Paul 42d330e1c0 Added berry world gen weights to data 2023-09-04 18:45:27 +10:00
Paul 062cee2b9a Merge remote-tracking branch 'origin/main' 2023-09-04 18:16:36 +10:00
Paul 5730d812a0 Randomize berry positions for most berry trees (except for berry swords) 2023-09-04 18:16:28 +10:00
Hiroku cb4ad09a11 Merge branch 'heal-me-up-scotty' into 'main'
Potions are like healing berries

Closes #437

See merge request cable-mc/cobblemon!598
2023-09-04 05:52:07 +00:00
MoeBoy76 1d81df91eb Potions are like healing berries 2023-09-04 05:52:06 +00:00
Hiroku d962d30074 Merge branch 'fix-starter-volume' into 'main'
Fixes starter selection sound effect playing twice when clicking the arrow keys to navigate

Closes #427

See merge request cable-mc/cobblemon!599
2023-09-04 05:47:31 +00:00
Hiroku 5096d9a15a Merge branch 'pokemonloot-fix' into 'main'
Fixes pokemon dropping XP when doPokemonLoot gamerule is set to false

See merge request cable-mc/cobblemon!597
2023-09-04 04:20:21 +00:00
Hiroku 24737cf606 Merge branch 'selected-pokemon-pvp-fix' into 'main'
Fix player battle always starting with first pokemon

Closes #389

See merge request cable-mc/cobblemon!579
2023-09-04 04:12:14 +00:00
Mia 7bd1c24b57 Fix player battle always starting with first pokemon 2023-09-04 04:12:13 +00:00
miasmus 36b1bec04b Fixes starter selection sound effect playing twice when clicking the arrow keys to navigate 2023-09-03 20:19:52 -04:00
Hiroku 7f14b60efb Merge branch 'neo-1.4-fixes' into 'main'
Various bug fixes

See merge request cable-mc/cobblemon!596
2023-09-03 22:27:52 +00:00
Neovitalism 239559cfd3 Various bug fixes 2023-09-03 22:27:52 +00:00
miasmus c4b2a1546a Fixes pokemon dropping XP when doPokemonLoot gamerule is set to false 2023-09-03 13:39:51 -04:00
Paul 278b36234e Put the pre-render call back so pokeballs animate (oopsy) 2023-09-03 14:43:49 +10:00
Paul 1598c8209a Fixed ternary and boolean-not operators not working in Molang which broke berry friendship increase amounts 2023-09-03 14:38:44 +10:00
Hiroku deb7ece946 Merge branch 'berry' into 'main'
Berries

See merge request cable-mc/cobblemon!595
2023-09-02 06:05:40 +00:00
Apion d8f9f8926b Berries 2023-09-02 06:05:40 +00:00
Paul 9d8803caf2 Make entity accessible from poseable entity state 2023-09-01 09:01:12 +10:00
Paul 08827a742f Fixes to particle effects in bedrock animations 2023-08-28 18:27:19 +10:00
Paul a6a76052a6 Fixed various items not preventing off-hand interactions from playing 2023-08-27 15:58:57 +10:00
Paul abeb005bbb Improve error logging for bad MoLang expression parsing from String.asExpression 2023-08-27 13:05:03 +10:00
Paul 6835232aa6 Added support for effect looping in non-loop animations 2023-08-27 13:04:47 +10:00
Paul 78ebc9a9eb Added MoLang instructions: s.sound(effect, volume, pitch) and s.random(...) 2023-08-27 13:04:06 +10:00
Paul f5e85971f3 Made Pokémon appear red when hurt 2023-08-27 11:11:53 +10:00
Hiroku e85b2aa138 Merge branch 'battle_bugs_1' into 'main'
Fix Shedinja HP and Faint Softlock.

Closes #341 and #400

See merge request cable-mc/cobblemon!593
2023-08-26 02:33:53 +00:00
Segfault Guy 371e1426a3 Fix Shedinja HP and Faint Softlock. 2023-08-25 22:24:54 -04:00
Hiroku 256e09846d Merge branch 'main' into 'main'
Made Master Balls Fireproof (won't disappear when thrown in lava/fire)

See merge request cable-mc/cobblemon!591
2023-08-26 01:49:13 +00:00
Retro dd2d441b0c Made Master Balls Fireproof (won't disappear when thrown in lava/fire) 2023-08-26 01:49:13 +00:00
Nick ddc57ecd8d Merge branch 'fixed-tag-file' into 'main'
Fixed tag file

See merge request cable-mc/cobblemon!592
2023-08-24 19:50:57 +00:00
Deltric 202a6a0496 Fixed tag file 2023-08-24 14:26:32 -05:00
Hiroku fbc639cbf3 Merge branch 'power-items' into 'main'
Added in Power Items

See merge request cable-mc/cobblemon!580
2023-08-24 09:38:51 +00:00
Deltric 78faf30b32 Added in Power Items 2023-08-24 09:38:51 +00:00
Hiroku 39cbb448a6 Merge branch 'poke-select' into 'main'
Update Poke Select Interface

See merge request cable-mc/cobblemon!588
2023-08-22 09:21:51 +00:00
Test fd10f8efd8 Update Poke Select Interface 2023-08-22 09:21:51 +00:00
Hiroku 9161f61017 Merge branch 'spawn-issue' into 'main'
Bug fixes

Closes #402 and #403

See merge request cable-mc/cobblemon!577
2023-08-22 09:08:40 +00:00
Apion 4244680956 Bug fixes 2023-08-22 09:08:40 +00:00
Hiroku 92ad81f8d1 Merge branch 'sound' into 'main'
Various sound updates and volume tweaks

See merge request cable-mc/cobblemon!587
2023-08-22 09:06:17 +00:00
Sterrezo c1c7106bff Various sound updates and volume tweaks 2023-08-22 09:06:17 +00:00
Hiroku e36b1b22c4 Merge branch 'main' into 'main'
Persistent Data Fix

See merge request cable-mc/cobblemon!589
2023-08-22 09:05:39 +00:00
ItsJustChris85 e21d445e14 Persistent Data Fix 2023-08-22 00:51:00 -04:00
Paul 098ff1f96b Clamp set level within bounds instead of throwing exceptions (means we don't corrupt storages) 2023-08-20 17:21:25 +10:00
Paul f93445f081 JvmOverloads in battle builder, closes #410 2023-08-20 17:06:50 +10:00
Paul 85a962e924 Licenses 2023-08-20 15:13:23 +10:00
Paul f6d0f11c99 Implemented uncatchable, fixed some capture calculation issues, added PokeBallCaptureCalculatedEvent and PokemonCatchRateEvent 2023-08-20 13:51:08 +10:00
Paul e74b838fb2 Fixed lighting of pokemon model items 2023-08-20 10:35:29 +10:00
Hiroku 6dc4b6af24 Merge branch 'Zackghast7-main-patch-07680' into 'main'
Updated evYield for overqwil.json

See merge request cable-mc/cobblemon!586
2023-08-14 05:12:06 +00:00
Zack 071278caa2 Updated evYield for overqwil.json 2023-08-12 16:37:57 +00:00
Hiroku 12a29d1289 Merge branch 'Zackghast7-main-patch-64696' into 'main'
Update wyrdeer.json with the correct evs

See merge request cable-mc/cobblemon!585
2023-08-11 22:05:15 +00:00
Zack bc85fdb778 Update wyrdeer.json with the correct evs 2023-08-11 22:00:37 +00:00
Hiroku 0d0d659ce5 Merge branch 'added-sounds' into 'main'
New Healing Machine sound, shortened Healing Machine's heal time, updated PC and UI sounds

See merge request cable-mc/cobblemon!584
2023-08-11 21:42:15 +00:00
Sterrezo 535e0b6f87 New Healing Machine sound, shortened Healing Machine's heal time, updated PC and UI sounds 2023-08-11 21:42:15 +00:00
Licious dd8cb49295 Merge branch 'spawning-improvements' into 'main'
Fixed Pokémon spawning in walls, improve canSeeSky spawn condition, use new...

See merge request cable-mc/cobblemon!583
2023-08-11 19:24:56 +00:00
Paul 2c5968986d Fixed Pokémon spawning in walls, improve canSeeSky spawn condition, use new FlatSelector selection algorithm, remove terrible width spawn condition 2023-08-11 21:12:27 +10:00
Licious 7b29d31009 Merge branch 'pokemon_loot_gamerule' into 'main'
Add doPokemonLoot gamerule

See merge request cable-mc/cobblemon!576
2023-08-09 07:53:17 +00:00
Mia 8820a546db Add doPokemonLoot gamerule 2023-08-09 07:53:17 +00:00
Nick c4eb422722 Merge branch 'new-held-items' into 'main'
Added in five more held items

See merge request cable-mc/cobblemon!581
2023-08-08 22:48:19 +00:00
Deltric d8f4638806 Added in five more held items 2023-08-08 22:48:19 +00:00
Hiroku f92aa1777c Merge branch 'fix/pokemon-property-extractor' into 'main'
add createPokemonProperties(List)

See merge request cable-mc/cobblemon!578
2023-08-07 03:35:13 +00:00
FawksX 8d864a3ff8 add createPokemonProperties(List) 2023-08-07 03:35:13 +00:00
Paul 17a1409619 Fixed stat hex colour bleeding into text 2023-08-06 16:18:56 +10:00
Paul 51f92e1635 Further improvements to stat hex 2023-08-06 16:14:51 +10:00
Hiroku 9c3f8c9e8f Merge branch 'main' into 'main'
Fixes issue #394. Also fixes an (unlisted?) issue where special ivs/evs are not allocatable via pokegive

Closes #394

See merge request cable-mc/cobblemon!574
2023-08-06 00:44:12 +00:00
Apion 923f40ab68 Fixes issue #394. Also fixes an (unlisted?) issue where special ivs/evs are not allocatable via pokegive 2023-08-06 00:44:12 +00:00
Paul cd7c3a0319 Merge remote-tracking branch 'origin/main' 2023-08-06 10:17:02 +10:00
Paul 8311dd8785 Fixed chance of sheared Pokémon dropping no wool 2023-08-06 09:37:53 +10:00
Hiroku f489cd096f Merge branch 'solve_playerdata_cache' into 'main'
Solve playerdata cache

See merge request cable-mc/cobblemon!575
2023-08-05 21:46:43 +00:00
Pedro Souza 0a4dc34895 Solve playerdata cache 2023-08-05 21:46:42 +00:00
Paul b1bc867ef8 Merge remote-tracking branch 'origin/main' 2023-08-05 17:17:29 +10:00
Paul 3f6af25afa Added dire hit and guard spec to creative menu 2023-08-05 17:17:17 +10:00
Hiroku 9946c39de0 Merge branch 'sound_updates' into 'main'
Sound updates

See merge request cable-mc/cobblemon!573
2023-08-04 21:48:21 +00:00
Lily 037ba953b7 Sound updates 2023-08-04 21:48:21 +00:00
Hiroku 5b7b9342e5 Merge branch 'plant-issues' into 'main'
Various new crop fixes

Closes #396 and #347

See merge request cable-mc/cobblemon!569
2023-08-04 06:35:03 +00:00
Licious c52b99270b Various new crop fixes 2023-08-04 06:35:03 +00:00
Licious 2e67e804a7 Merge branch 'healing-items' into 'main'
Added healing items / bag items

See merge request cable-mc/cobblemon!333
2023-07-31 12:01:18 +00:00
Landon de58d11f9e Added healing items / bag items 2023-07-31 12:01:17 +00:00
1295 changed files with 28202 additions and 2944 deletions

No files matched your search

+14 -4
View File
@@ -8,11 +8,13 @@
- Added big roots, generating from cave ceiling dirt and sometimes spreading into energy roots.
- Added trading between players. Press R while looking at another player, you'll figure it out.
- Added pasture blocks, used to let your PC Pokémon roam around your base.
- Added 69 berry trees. Some are found in village farms, some from planting different berries close to each other.
- Added medicine brewing using medicinal leeks and berries in brewing stands.
- Added Pokémon cries when in battles and being sent out.
- Added support for scale in animations.
- Added support for jump keyframes (i.e. pre and post keyframes)
- Made Nosepass point towards world spawn while idle.
- Added AI for Nosepass to point towards world spawn when idle.
- Added structure spawn conditions
- Added Pokémon cry system for battles and sending out.
- Added cries for Gen 1-9 starters and their evolutions.
- Added cries for Chatot, Darmanitan, Darumaka, Lucario, Mimikyu, Quagsire, Riolu, Wooper, Caterpie, Metapod, Butterfree, Weedle, Kakuna, Beedrill, Pidgey, Pidgeotto, Pidgeot, Rattata, Raticate, Cleffa, Clefairy, Clefable, Tauros, Miltank, Buneary, Lopunny, Wooloo, Dubwool.
- Added recipes for Berry Juice, Heal Powder, Remedy, Fine Remedy, Superb Remedy, Revive, Max Revive, HP Up, Protein, Iron, Calcium, Zinc, Carbos, PP Up, PP Max, Pasture, Medicinal Leek to Magenta Dye, Roasted Leek, Leek and Potato Stew, Braised Vivichoke, Vivichoke Dip, Mulch Base, Growth Mulch, Surprise Mulch, Coarse Mulch, Humid Mulch, Rich Mulch, Loamy Mulch, Peat Mulch, Sandy Mulch, Health Feather, Muscle Feather, Resist Feather, Genius Feather, Clever Feather, Genius Feather
@@ -29,6 +31,7 @@
- Added the `/pokemonrestart <reset_starters>` and the `/pokemonrestartother <player> <reset_starters>` command allowing command block/mcfunction users to reset a players Pokémon data.
- Added support for "isBattle" and "isTouchingWater" properties on resource pack Pokémon poses. This allows your custom Pokémon to be posed differently when in battle.
- Added support for "isVisible" on a transformed part on resource pack Pokémon poses. This allows your custom Pokémon to have bones disappear in specific poses, such as hiding Greninja's throwing star when not in a battle pose.
- Added the `doPokemonLoot` gamerule to toggle Pokémon dropping items/exp on death.
### Pokémon Added
#### Gen 2
@@ -190,9 +193,13 @@
- Clicking categories of the Stat sub-section or the party reorder button in the Summary screen will now produce a click sound.
- Updated PC Recipe.
- Improved Pokémon AI and movement.
- Friendship will slowly increase when Pokémon are shoulder-mounted.
- Master balls are now unable to be burned when dropped into fire/lava.
- Pokémon will appear red when hurt, like regular entities, except when they're fainting.
### Fixes
- Fixed spawning moon phase dependent Pokémon only when the moon phase is wrong
- Fixed large Pokémon spawning partially inside walls where they suffocate.
- Fixed messages for entry hazards, screens, Tailwind, Perish Song, Destiny Bond, Shed Skin, Uproar, Forewarn, Disguise, Arena Trap, Yawn, Curse, Clamp, Whirlpool, Liquid Ooze, Miracle Eye and Safeguard.
- Fixed Porygon not evolving with an Upgrade.
- Fixed super sized Pumpkaboo not having any moves.
@@ -219,8 +226,11 @@
- Fixed particle animations not running when a Pokémon is off-screen.
- Fixed Pokémon variants and layers not rendering correctly when shouldered and playing on a dedicated server, existing shoulders affected will need to be retrieved and shouldered again.
- Shoulder effects will now stay applied through situations that remove potion effects such as drinking milk.
- Fixed Shedninja evolving to use the consumed Pokeball and removed the held item.
- Fixed non-existent species in spawn pool file causing random species to spawn
- Fixed Shedinja evolving to use the consumed Pokeball and removed the held item.
- Fixed non-existent species in spawn pool file causing random species to spawn.
- Fixed shearing Pokémon dropping 0-2 wool instead of 1-3.
- Fixed some alignment issues in the stat hexagon of the summary menu.
- Fixed capture calculations not applying ball bonuses entirely correctly.
### Developer
- Added SpawnEvent
@@ -1,3 +1,13 @@
/*
*
* * Copyright (C) 2023 Cobblemon Contributors
* *
* * This Source Code Form is subject to the terms of the Mozilla Public
* * License, v. 2.0. If a copy of the MPL was not distributed with this
* * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
*/
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
val accessWidenerFile = "src/main/resources/cobblemon-common.accesswidener"
@@ -13,6 +23,8 @@ plugins {
repositories {
mavenCentral()
//JEI
maven("https://maven.blamejared.com/")
}
license {
@@ -55,4 +67,4 @@ tasks {
withType<Jar> {
from(rootProject.file("LICENSE"))
}
}
}
+11
View File
@@ -1,3 +1,13 @@
/*
*
* * Copyright (C) 2023 Cobblemon Contributors
* *
* * This Source Code Form is subject to the terms of the Mozilla Public
* * License, v. 2.0. If a copy of the MPL was not distributed with this
* * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
*/
plugins {
id("cobblemon.base-conventions")
id("cobblemon.publish-conventions")
@@ -18,6 +28,7 @@ dependencies {
modImplementation(libs.fabricLoader)
modApi(libs.molang)
compileOnlyApi(libs.jeiApi)
// For Showdown
modCompileOnly(libs.graal)
@@ -0,0 +1,16 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.bridges;
import net.minecraft.structure.processor.StructureProcessor;
public interface StructureProcessorListBridge {
void append(StructureProcessor processor);
void clear();
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.cobblemonstructures;
public class CobblemonStructureIDs {
//Location of the nbt
//Not sure if this is a good way to store them but doing this meant I wouldnt have to keep typing this out during development
public static final String PLAINS_POKECENTER = "cobblemon:village_plains/village_plains_pokecenter";
public static final String DESERT_POKECENTER = "cobblemon:village_desert/village_desert_pokecenter";
public static final String SAVANNA_POKECENTER = "cobblemon:village_savanna/village_savanna_pokecenter";
public static final String SNOWY_POKECENTER = "cobblemon:village_snowy/village_snowy_pokecenter";
public static final String TAIGA_POKECENTER = "cobblemon:village_taiga/village_taiga_pokecenter";
public static final String PLAINS_LONG_PATH = "cobblemon:village_plains/village_plains_long_path";
public static final String DESERT_LONG_PATH = "cobblemon:village_desert/village_desert_long_path";
public static final String SAVANNA_LONG_PATH = "cobblemon:village_savanna/village_savanna_long_path";
public static final String SNOWY_LONG_PATH = "cobblemon:village_snowy/village_snowy_long_path";
public static final String TAIGA_LONG_PATH = "cobblemon:village_taiga/village_taiga_long_path";
}
@@ -0,0 +1,101 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.cobblemonstructures;
import com.cobblemon.mod.common.mixin.StructurePoolAccessor;
import com.mojang.datafixers.util.Pair;
import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.server.MinecraftServer;
import net.minecraft.structure.pool.LegacySinglePoolElement;
import net.minecraft.structure.pool.SinglePoolElement;
import net.minecraft.structure.pool.StructurePool;
import net.minecraft.structure.pool.StructurePoolElement;
import net.minecraft.structure.processor.StructureProcessorList;
import net.minecraft.structure.processor.StructureProcessorLists;
import net.minecraft.util.Identifier;
import java.util.ArrayList;
import java.util.List;
public class CobblemonStructures {
private static final RegistryKey<StructureProcessorList> EMPTY_PROCESSOR_LIST_KEY = RegistryKey.of(RegistryKeys.PROCESSOR_LIST, new Identifier("minecraft", "empty"));
private static final Integer pokecenterWeight = 35;
private static final Integer longPathWeight = 10;
public static void registerJigsaws(MinecraftServer server) {
Registry<StructurePool> templatePoolRegistry = server.getRegistryManager().get(RegistryKeys.TEMPLATE_POOL);
Registry<StructureProcessorList> processorListRegistry = server.getRegistryManager().get(RegistryKeys.PROCESSOR_LIST);
//No pokecenters yet
//addPokecenters(templatePoolRegistry, processorListRegistry);
//addLongPaths(templatePoolRegistry, processorListRegistry);
}
private static void addPokecenters(Registry<StructurePool> templatePoolRegistry, Registry<StructureProcessorList> processorListRegistry) {
Identifier plainsHousesPoolLocation = new Identifier("minecraft:village/plains/houses");
Identifier desertHousesPoolLocation = new Identifier("minecraft:village/desert/houses");
Identifier savannaHousesPoolLocation = new Identifier("minecraft:village/savanna/houses");
Identifier snowyHousesPoolLocation = new Identifier("minecraft:village/snowy/houses");
Identifier taigaHousesPoolLocation = new Identifier("minecraft:village/taiga/houses");
addBuildingToPool(templatePoolRegistry, processorListRegistry, plainsHousesPoolLocation, CobblemonStructureIDs.PLAINS_POKECENTER, pokecenterWeight, StructurePool.Projection.RIGID, EMPTY_PROCESSOR_LIST_KEY);
addBuildingToPool(templatePoolRegistry, processorListRegistry, desertHousesPoolLocation, CobblemonStructureIDs.DESERT_POKECENTER, pokecenterWeight, StructurePool.Projection.RIGID, EMPTY_PROCESSOR_LIST_KEY);
addBuildingToPool(templatePoolRegistry, processorListRegistry, savannaHousesPoolLocation, CobblemonStructureIDs.SAVANNA_POKECENTER, pokecenterWeight, StructurePool.Projection.RIGID, EMPTY_PROCESSOR_LIST_KEY);
addBuildingToPool(templatePoolRegistry, processorListRegistry, snowyHousesPoolLocation, CobblemonStructureIDs.SNOWY_POKECENTER, pokecenterWeight, StructurePool.Projection.RIGID, EMPTY_PROCESSOR_LIST_KEY);
addBuildingToPool(templatePoolRegistry, processorListRegistry, taigaHousesPoolLocation, CobblemonStructureIDs.TAIGA_POKECENTER, pokecenterWeight, StructurePool.Projection.RIGID, StructureProcessorLists.MOSSIFY_10_PERCENT);
}
private static void addLongPaths(Registry<StructurePool> templatePoolRegistry, Registry<StructureProcessorList> processorListRegistry) {
Identifier plainsStreetsPoolLocation = new Identifier("minecraft:village/plains/streets");
Identifier desertStreetsPoolLocation = new Identifier("minecraft:village/desert/streets");
Identifier savannaStreetsPoolLocation = new Identifier("minecraft:village/savanna/streets");
Identifier snowyStreetsPoolLocation = new Identifier("minecraft:village/snowy/streets");
Identifier taigaStreetsPoolLocation = new Identifier("minecraft:village/taiga/streets");
addLegacyBuildingToPool(templatePoolRegistry, processorListRegistry, plainsStreetsPoolLocation, CobblemonStructureIDs.PLAINS_LONG_PATH, longPathWeight, StructurePool.Projection.TERRAIN_MATCHING, StructureProcessorLists.STREET_PLAINS);
addLegacyBuildingToPool(templatePoolRegistry, processorListRegistry, desertStreetsPoolLocation, CobblemonStructureIDs.DESERT_LONG_PATH, longPathWeight, StructurePool.Projection.TERRAIN_MATCHING, EMPTY_PROCESSOR_LIST_KEY);
addLegacyBuildingToPool(templatePoolRegistry, processorListRegistry, savannaStreetsPoolLocation, CobblemonStructureIDs.SAVANNA_LONG_PATH, longPathWeight, StructurePool.Projection.TERRAIN_MATCHING, StructureProcessorLists.STREET_SAVANNA);
addLegacyBuildingToPool(templatePoolRegistry, processorListRegistry, snowyStreetsPoolLocation, CobblemonStructureIDs.SNOWY_LONG_PATH, longPathWeight, StructurePool.Projection.TERRAIN_MATCHING, StructureProcessorLists.STREET_SNOWY_OR_TAIGA);
addLegacyBuildingToPool(templatePoolRegistry, processorListRegistry, taigaStreetsPoolLocation, CobblemonStructureIDs.TAIGA_LONG_PATH, longPathWeight, StructurePool.Projection.TERRAIN_MATCHING, StructureProcessorLists.STREET_SNOWY_OR_TAIGA);
}
public static void addLegacyBuildingToPool(Registry<StructurePool> templatePoolRegistry, Registry<StructureProcessorList> processorListRegistry, Identifier poolRL, String nbtPieceRL, int weight, StructurePool.Projection projection, RegistryKey<StructureProcessorList> processorListKey) {
addBuildingToPool(templatePoolRegistry, processorListRegistry, poolRL, nbtPieceRL, weight, projection, processorListKey, true);
}
public static void addBuildingToPool(Registry<StructurePool> templatePoolRegistry, Registry<StructureProcessorList> processorListRegistry, Identifier poolRL, String nbtPieceRL, int weight, StructurePool.Projection projection, RegistryKey<StructureProcessorList> processorListKey) {
addBuildingToPool(templatePoolRegistry, processorListRegistry, poolRL, nbtPieceRL, weight, projection, processorListKey, false);
}
public static void addBuildingToPool(Registry<StructurePool> templatePoolRegistry, Registry<StructureProcessorList> processorListRegistry, Identifier poolRL, String nbtPieceRL, int weight, StructurePool.Projection projection, RegistryKey<StructureProcessorList> processorListKey, boolean shouldUseLegacySingePoolElement) {
if (processorListRegistry.getEntry(processorListKey).isEmpty()) return;
RegistryEntry.Reference<StructureProcessorList> processorList = processorListRegistry.getEntry(processorListKey).get();
StructurePool pool = templatePoolRegistry.get(poolRL);
if (pool == null) return;
SinglePoolElement piece;
if (shouldUseLegacySingePoolElement) {
piece = LegacySinglePoolElement.ofProcessedLegacySingle(nbtPieceRL, processorList).apply(projection);
} else {
piece = SinglePoolElement.ofProcessedSingle(nbtPieceRL, processorList).apply(projection);
}
for (int i = 0; i < weight; i++) {
((StructurePoolAccessor) pool).getElements().add(piece);
}
List<Pair<StructurePoolElement, Integer>> listOfPieceEntries = new ArrayList<>(((StructurePoolAccessor) pool).getElementCounts());
listOfPieceEntries.add(new Pair<>(piece, weight));
((StructurePoolAccessor) pool).setElementCounts(listOfPieceEntries);
}
}
@@ -8,14 +8,12 @@
package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.block.ApricornBlock;
import com.cobblemon.mod.common.block.ShearableBlock;
import kotlin.Unit;
import net.minecraft.block.BlockState;
import net.minecraft.block.dispenser.ShearsDispenserBehavior;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.event.GameEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -24,15 +22,12 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ShearsDispenserBehavior.class)
public abstract class ShearsDispenserBehaviorMixin {
// This exists so we can execute our custom interaction only if no one redirected shears interactions to overwrite the vanilla ones.
// This exists, so we can execute our custom interaction only if no one redirected shears interactions to overwrite the vanilla ones.
@Inject(method = "tryShearBlock", at = @At("HEAD"), cancellable = true)
private static void cobblemon$tryApricornHarvest(ServerWorld world, BlockPos pos, CallbackInfoReturnable<Boolean> cir) {
final BlockState state = world.getBlockState(pos);
if (state.getBlock() instanceof ApricornBlock apricornBlock && state.get(ApricornBlock.Companion.getAGE()) == ApricornBlock.MAX_AGE) {
world.playSound(null, pos, SoundEvents.ENTITY_SHEEP_SHEAR, SoundCategory.BLOCKS, 1F, 1F);
apricornBlock.harvest(world, state, pos);
world.emitGameEvent(null, GameEvent.SHEAR, pos);
cir.setReturnValue(true);
if (state.getBlock() instanceof ShearableBlock shearableBlock) {
cir.setReturnValue(shearableBlock.attemptShear(world, state, pos, () -> Unit.INSTANCE));
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.structure.pool.StructurePool;
import net.minecraft.structure.pool.StructurePoolElement;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.List;
@Mixin(StructurePool.class)
public interface StructurePoolAccessor {
@Accessor("elementCounts")
List<Pair<StructurePoolElement, Integer>> getElementCounts();
@Mutable
@Accessor("elementCounts")
void setElementCounts(List<Pair<StructurePoolElement, Integer>> elementCounts);
@Accessor("elements")
ObjectArrayList<StructurePoolElement> getElements();
}
@@ -0,0 +1,199 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.cobblemonstructures.CobblemonStructureIDs;
import net.minecraft.registry.Registry;
import net.minecraft.structure.PoolStructurePiece;
import net.minecraft.structure.StructureTemplateManager;
import net.minecraft.structure.pool.*;
import net.minecraft.util.math.random.Random;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.HeightLimitView;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.noise.NoiseConfig;
import org.apache.commons.lang3.mutable.MutableObject;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.*;
import java.util.stream.Collectors;
@Mixin(StructurePoolBasedGenerator.StructurePoolGenerator.class)
public abstract class StructurePoolGeneratorMixin {
@Final
@Mutable
@Shadow Deque<StructurePoolBasedGenerator.ShapedPoolStructurePiece> structurePieces;
Map<String, Integer> generatedStructureCounts;
private static final Map<String, Integer> structureMaxes;
static {
//Mapped using location string as key
Map<String, Integer> aMap = new HashMap<>();
aMap.put(CobblemonStructureIDs.PLAINS_POKECENTER, 1);
aMap.put(CobblemonStructureIDs.DESERT_POKECENTER, 1);
aMap.put(CobblemonStructureIDs.SAVANNA_POKECENTER, 1);
aMap.put(CobblemonStructureIDs.SNOWY_POKECENTER, 1);
aMap.put(CobblemonStructureIDs.TAIGA_POKECENTER, 1);
// aMap.put(CobblemonStructureIDs.PLAINS_LONG_PATH, 3);
// aMap.put(CobblemonStructureIDs.DESERT_LONG_PATH, 3);
// aMap.put(CobblemonStructureIDs.SAVANNA_LONG_PATH, 3);
// aMap.put(CobblemonStructureIDs.SNOWY_LONG_PATH, 3);
// aMap.put(CobblemonStructureIDs.TAIGA_LONG_PATH, 3);
structureMaxes = Collections.unmodifiableMap(aMap);
}
@Inject(method = "<init>", at = @At("RETURN"))
private void onStructurePoolGeneratorCreation(Registry<StructurePool> registry, int maxSize, ChunkGenerator chunkGenerator, StructureTemplateManager structureTemplateManager, List<? super PoolStructurePiece> children, Random random, CallbackInfo ci) {
generatedStructureCounts = new HashMap<>();
}
@ModifyVariable(method = "generatePiece", at = @At("STORE"), ordinal = 1)
private Iterator<StructurePoolElement> reduceStructurePoolELementIterator(Iterator<StructurePoolElement> iterator) {
List<StructurePoolElement> reducedList = new ArrayList<>();
while (iterator.hasNext()) {
StructurePoolElement structure = iterator.next();
String structurePieceLocationKey = getCobblemonOnlyLocation(structure);
if (structurePieceLocationKey == null) {
reducedList.add(structure);
continue;
}
Integer currentlyPlacedCount = generatedStructureCounts.get(structurePieceLocationKey);
if (currentlyPlacedCount == null) currentlyPlacedCount = 0;
Integer maxAllowed = structureMaxes.get(structurePieceLocationKey);
if (maxAllowed == null) {
reducedList.add(structure);
continue;
}
if (currentlyPlacedCount < maxAllowed) {
reducedList.add(structure);
}
}
for (String maxStructureLocationKey : structureMaxes.keySet()) {
Integer maxAllowed = structureMaxes.get(maxStructureLocationKey);
Integer currentlyGenerated = generatedStructureCounts.get(maxStructureLocationKey);
if (currentlyGenerated == null) currentlyGenerated = 0;
Integer allowedInstances = maxAllowed - currentlyGenerated;
reducedList = removeInstanceOfLocationKeyFrom(reducedList, allowedInstances, maxStructureLocationKey);
}
return reducedList.iterator();
}
@ModifyVariable(method = "generatePiece", at = @At("STORE"), ordinal = 1)
private PoolStructurePiece injected(PoolStructurePiece poolStructurePiece) {
String structureLocationKey = getCobblemonOnlyLocation(poolStructurePiece.getPoolElement());
if (structureLocationKey != null) {
Integer currentlyGenerated = generatedStructureCounts.get(structureLocationKey);
if (currentlyGenerated == null) currentlyGenerated = 0;
generatedStructureCounts.put(structureLocationKey, currentlyGenerated + 1);
}
return poolStructurePiece;
}
@Inject(method = "generatePiece", at = @At("HEAD"))
private void beforeGeneratePiece(PoolStructurePiece piece, MutableObject<VoxelShape> pieceShape, int minY, boolean modifyBoundingBox, HeightLimitView world, NoiseConfig noiseConfig, CallbackInfo ci) {
String structureLocationKey = getCobblemonOnlyLocation(piece.getPoolElement());
if (structureLocationKey != null && structureLocationKey.equals("cobblemon:village_snowy/village_snowy_pokecenter")) System.out.println("Before Counts" + generatedStructureCounts);
if (structureLocationKey != null) {
Integer currentlyGenerated = generatedStructureCounts.get(structureLocationKey);
if (currentlyGenerated == null) currentlyGenerated = 0;
generatedStructureCounts.put(structureLocationKey, currentlyGenerated + 1);
}
List<StructurePoolBasedGenerator.ShapedPoolStructurePiece> reducedStructurePiecesList = structurePieces.stream().toList();
for (String maxStructureLocationKey : structureMaxes.keySet()) {
Integer maxAllowed = structureMaxes.get(maxStructureLocationKey);
Integer currentlyGenerated = generatedStructureCounts.get(maxStructureLocationKey);
if (currentlyGenerated == null) currentlyGenerated = 0;
if (currentlyGenerated < maxAllowed) {
continue;
}
//Already have max so need to remove
reducedStructurePiecesList = reducedStructurePiecesList.stream()
.filter(shapedStructurePiece -> {
String locationKey = getCobblemonOnlyLocation(shapedStructurePiece.piece.getPoolElement());
if (locationKey == null) {
return true;
}
return !locationKey.equals(maxStructureLocationKey);
})
.collect(Collectors.toList());
}
structurePieces = new ArrayDeque<>(reducedStructurePiecesList);
}
private static String getCobblemonOnlyLocation(StructurePoolElement structurePoolElement) {
String location = getLocationIfAvailable(structurePoolElement);
if (location == null) return null;
if (!location.contains("cobblemon")) return null;
return location;
}
private static String getLocationIfAvailable(StructurePoolElement structurePoolElement) {
if (structurePoolElement instanceof LegacySinglePoolElement legacySinglePoolElement) {
if (legacySinglePoolElement.location.left().isEmpty()) return null;
return legacySinglePoolElement.location.left().get().toString();
} else if (structurePoolElement instanceof SinglePoolElement singlePoolElement) {
if (singlePoolElement.location.left().isEmpty()) return null;
return singlePoolElement.location.left().get().toString();
} else {
return null;
}
}
private List<StructurePoolElement> removeInstanceOfLocationKeyFrom(List<StructurePoolElement> structureList, Integer allowedNumberOfInstances, String locationKey) {
List<StructurePoolElement> reducedList = new ArrayList<>();
int instancesFound = 0;
for (StructurePoolElement structurePoolElement: structureList) {
String structureKey = getCobblemonOnlyLocation(structurePoolElement);
if (structureKey == null || !structureKey.equals(locationKey)) {
reducedList.add(structurePoolElement);
continue;
}
if (instancesFound >= allowedNumberOfInstances) {
continue;
}
reducedList.add(structurePoolElement);
instancesFound++;
}
return reducedList;
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.mixin;
import com.cobblemon.mod.common.bridges.StructureProcessorListBridge;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.structure.processor.StructureProcessor;
import net.minecraft.structure.processor.StructureProcessorList;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(StructureProcessorList.class)
public class StructureProcessorListMixin implements StructureProcessorListBridge {
@Final
@Mutable
@Shadow
private List<StructureProcessor> list;
@Override
public void append(StructureProcessor processor) {
List<StructureProcessor> mutable = new ArrayList<>(this.list);
mutable.add(processor);
this.list = ImmutableList.copyOf(mutable);
}
@Override
public void clear() {
this.list = ImmutableList.of();
}
}
@@ -33,4 +33,9 @@ public interface BlocksInvoker {
throw new UnsupportedOperationException();
}
@Invoker("createFlowerPotBlock")
static FlowerPotBlock createFlowerPotBlock(Block flower, FeatureFlag... requiredFeatures) {
throw new UnsupportedOperationException();
}
}
@@ -54,13 +54,19 @@ import com.cobblemon.mod.common.api.storage.pc.PCStore
import com.cobblemon.mod.common.api.storage.pc.link.PCLinkManager
import com.cobblemon.mod.common.api.storage.player.PlayerDataStoreManager
import com.cobblemon.mod.common.api.tags.CobblemonEntityTypeTags
import com.cobblemon.mod.common.battles.BagItems
import com.cobblemon.mod.common.battles.BattleFormat
import com.cobblemon.mod.common.battles.BattleRegistry
import com.cobblemon.mod.common.battles.BattleSide
import com.cobblemon.mod.common.battles.ShowdownThread
import com.cobblemon.mod.common.battles.actor.PokemonBattleActor
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.command.argument.*
import com.cobblemon.mod.common.command.argument.MoveArgumentType
import com.cobblemon.mod.common.command.argument.PartySlotArgumentType
import com.cobblemon.mod.common.command.argument.PokemonArgumentType
import com.cobblemon.mod.common.command.argument.PokemonPropertiesArgumentType
import com.cobblemon.mod.common.command.argument.PokemonStoreArgumentType
import com.cobblemon.mod.common.command.argument.SpawnBucketArgumentType
import com.cobblemon.mod.common.config.CobblemonConfig
import com.cobblemon.mod.common.config.LastChangedVersion
import com.cobblemon.mod.common.config.constraint.IntConstraint
@@ -85,10 +91,25 @@ import com.cobblemon.mod.common.pokemon.properties.tags.PokemonFlagProperty
import com.cobblemon.mod.common.pokemon.stat.CobblemonStatProvider
import com.cobblemon.mod.common.starter.CobblemonStarterHandler
import com.cobblemon.mod.common.trade.TradeManager
import com.cobblemon.mod.common.util.*
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.util.ifDedicatedServer
import com.cobblemon.mod.common.util.isLaterVersion
import com.cobblemon.mod.common.util.party
import com.cobblemon.mod.common.util.removeAmountIf
import com.cobblemon.mod.common.util.server
import com.cobblemon.mod.common.world.feature.CobblemonPlacedFeatures
import com.cobblemon.mod.common.world.feature.ore.CobblemonOrePlacedFeatures
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.PrintWriter
import java.util.UUID
import kotlin.properties.Delegates
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaField
import net.minecraft.client.MinecraftClient
import net.minecraft.command.argument.serialize.ConstantArgumentSerializer
import net.minecraft.entity.data.TrackedDataHandlerRegistry
@@ -98,15 +119,6 @@ import net.minecraft.registry.RegistryKey
import net.minecraft.util.WorldSavePath
import net.minecraft.world.World
import org.apache.logging.log4j.LogManager
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.PrintWriter
import java.util.*
import kotlin.properties.Delegates
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaField
object Cobblemon {
const val MODID = "cobblemon"
@@ -284,9 +296,9 @@ object Cobblemon {
var pokeball = Items.AIR
player.inventory.combinedInventory.forEach {
it.forEach {
itemStack -> if (itemStack.item is PokeBallItem && pokeball == Items.AIR) {
pokeball = itemStack.item as PokeBallItem
}
itemStack -> if (itemStack.item is PokeBallItem && pokeball == Items.AIR) {
pokeball = itemStack.item as PokeBallItem
}
}
}
player.inventory.removeAmountIf(1) { it.item is PokeBallItem }
@@ -301,7 +313,7 @@ object Cobblemon {
}
}
PokemonSpecies.observable.subscribe {
BagItems.observable.subscribe {
LOGGER.info("Starting dummy Showdown battle to force it to pre-load data.")
battleRegistry.startBattle(
BattleFormat.GEN_9_SINGLES,
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common
import com.cobblemon.mod.common.block.entity.BerryBlockEntity
import com.cobblemon.mod.common.block.entity.HealingMachineBlockEntity
import com.cobblemon.mod.common.block.entity.PCBlockEntity
import com.cobblemon.mod.common.block.entity.PokemonPastureBlockEntity
@@ -27,6 +28,7 @@ object CobblemonBlockEntities : PlatformRegistry<Registry<BlockEntityType<*>>, R
val HEALING_MACHINE: BlockEntityType<HealingMachineBlockEntity> = this.create("healing_machine", BlockEntityType.Builder.create(::HealingMachineBlockEntity, CobblemonBlocks.HEALING_MACHINE).build(null))
@JvmField
val PC: BlockEntityType<PCBlockEntity> = this.create("pc", BlockEntityType.Builder.create(::PCBlockEntity, CobblemonBlocks.PC).build(null))
val BERRY = this.create("berry", BlockEntityType.Builder.create(::BerryBlockEntity, *CobblemonBlocks.berries().values.toTypedArray()).build(null))
@JvmField
val PASTURE: BlockEntityType<PokemonPastureBlockEntity> = this.create("pasture", BlockEntityType.Builder.create(::PokemonPastureBlockEntity, CobblemonBlocks.PASTURE).build(null))
@@ -17,16 +17,20 @@ import com.cobblemon.mod.common.mixin.invoker.StairsBlockInvoker
import com.cobblemon.mod.common.mixin.invoker.TrapdoorBlockInvoker
import com.cobblemon.mod.common.mixin.invoker.*
import com.cobblemon.mod.common.platform.PlatformRegistry
import com.cobblemon.mod.common.util.cobblemonResource
import com.cobblemon.mod.common.block.BerryBlock
import net.minecraft.block.*
import net.minecraft.block.piston.PistonBehavior
import net.minecraft.entity.effect.StatusEffects
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.minecraft.registry.RegistryKey
import net.minecraft.registry.RegistryKeys
import net.minecraft.sound.BlockSoundGroup
import net.minecraft.util.Identifier
import net.minecraft.util.math.intprovider.UniformIntProvider
@Suppress("SameParameterValue", "HasPlatformType", "MemberVisibilityCanBePrivate")
@Suppress("SameParameterValue", "HasPlatformType", "MemberVisibilityCanBePrivate", "unused")
object CobblemonBlocks : PlatformRegistry<Registry<Block>, RegistryKey<Registry<Block>>, Block>() {
override val registry: Registry<Block> = Registries.BLOCK
@@ -130,7 +134,7 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, RegistryKey<Registry<
val YELLOW_APRICORN_SAPLING = this.create("yellow_apricorn_sapling", ApricornSaplingBlock(PLANT_PROPERTIES, Apricorn.YELLOW))
@JvmField
val MEDICINAL_LEEK_CROP = this.create("medicinal_leek_crop", MedicinalLeekBlock(AbstractBlock.Settings.create().pistonBehavior(PistonBehavior.DESTROY).burnable().mapColor(MapColor.DULL_RED).noCollision().ticksRandomly().breakInstantly().sounds(BlockSoundGroup.CROP)))
val MEDICINAL_LEEK = this.create("medicinal_leek", MedicinalLeekBlock(AbstractBlock.Settings.create().pistonBehavior(PistonBehavior.DESTROY).burnable().mapColor(MapColor.DULL_RED).noCollision().ticksRandomly().breakInstantly().sounds(BlockSoundGroup.CROP)))
@JvmField
val ENERGY_ROOT = this.create("energy_root", EnergyRootBlock(AbstractBlock.Settings.create().pistonBehavior(PistonBehavior.DESTROY).burnable().mapColor(MapColor.DIRT_BROWN).noCollision().ticksRandomly().breakInstantly().sounds(BlockSoundGroup.ROOTS)))
@JvmField
@@ -209,6 +213,10 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, RegistryKey<Registry<
@JvmField
val VIVICHOKE_SEEDS = this.create("vivichoke_seeds", VivichokeBlock(AbstractBlock.Settings.create().pistonBehavior(PistonBehavior.DESTROY).burnable().mapColor(MapColor.DARK_GREEN).noCollision().ticksRandomly().breakInstantly().sounds(BlockSoundGroup.CROP)))
@JvmField
val PEP_UP_FLOWER = this.create("pep_up_flower", FlowerBlock(StatusEffects.LEVITATION, 10, AbstractBlock.Settings.create().mapColor(MapColor.DARK_GREEN).noCollision().breakInstantly().sounds(BlockSoundGroup.GRASS).offset(AbstractBlock.OffsetType.XZ).pistonBehavior(PistonBehavior.DESTROY)))
@JvmField
val POTTED_PEP_UP_FLOWER = this.create("potted_pep_up_flower", BlocksInvoker.createFlowerPotBlock(PEP_UP_FLOWER))
/**
* Returns a map of all the blocks that can be stripped with an axe in the format of input - output.
@@ -222,6 +230,87 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, RegistryKey<Registry<
private fun apricornBlock(name: String, apricorn: Apricorn): ApricornBlock = this.create(name, ApricornBlock(AbstractBlock.Settings.create().mapColor(apricorn.mapColor()).ticksRandomly().strength(Blocks.OAK_LOG.hardness, Blocks.OAK_LOG.blastResistance).sounds(BlockSoundGroup.WOOD).nonOpaque(), apricorn))
private val berries = mutableMapOf<Identifier, BerryBlock>()
val AGUAV_BERRY = this.berryBlock("aguav")
val APICOT_BERRY = this.berryBlock("apicot")
val ASPEAR_BERRY = this.berryBlock("aspear")
val BABIRI_BERRY = this.berryBlock("babiri")
val BELUE_BERRY = this.berryBlock("belue")
val BLUK_BERRY = this.berryBlock("bluk")
val CHARTI_BERRY = this.berryBlock("charti")
val CHERI_BERRY = this.berryBlock("cheri")
val CHESTO_BERRY = this.berryBlock("chesto")
val CHILAN_BERRY = this.berryBlock("chilan")
val CHOPLE_BERRY = this.berryBlock("chople")
val COBA_BERRY = this.berryBlock("coba")
val COLBUR_BERRY = this.berryBlock("colbur")
val CORNN_BERRY = this.berryBlock("cornn")
val CUSTAP_BERRY = this.berryBlock("custap")
val DURIN_BERRY = this.berryBlock("durin")
val ENIGMA_BERRY = this.berryBlock("enigma")
val FIGY_BERRY = this.berryBlock("figy")
val GANLON_BERRY = this.berryBlock("ganlon")
val GREPA_BERRY = this.berryBlock("grepa")
val HABAN_BERRY = this.berryBlock("haban")
val HONDEW_BERRY = this.berryBlock("hondew")
val HOPO_BERRY = this.berryBlock("hopo")
val IAPAPA_BERRY = this.berryBlock("iapapa")
val JABOCA_BERRY = this.berryBlock("jaboca")
val KASIB_BERRY = this.berryBlock("kasib")
val KEBIA_BERRY = this.berryBlock("kebia")
val KEE_BERRY = this.berryBlock("kee")
val KELPSY_BERRY = this.berryBlock("kelpsy")
val LANSAT_BERRY = this.berryBlock("lansat")
val LEPPA_BERRY = this.berryBlock("leppa")
val LIECHI_BERRY = this.berryBlock("liechi")
val LUM_BERRY = this.berryBlock("lum")
val MAGO_BERRY = this.berryBlock("mago")
val MAGOST_BERRY = this.berryBlock("magost")
val MARANGA_BERRY = this.berryBlock("maranga")
val MICLE_BERRY = this.berryBlock("micle")
val NANAB_BERRY = this.berryBlock("nanab")
val NOMEL_BERRY = this.berryBlock("nomel")
val OCCA_BERRY = this.berryBlock("occa")
val ORAN_BERRY = this.berryBlock("oran")
val PAMTRE_BERRY = this.berryBlock("pamtre")
val PASSHO_BERRY = this.berryBlock("passho")
val PAYAPA_BERRY = this.berryBlock("payapa")
val PECHA_BERRY = this.berryBlock("pecha")
val PERSIM_BERRY = this.berryBlock("persim")
val PETAYA_BERRY = this.berryBlock("petaya")
val PINAP_BERRY = this.berryBlock("pinap")
val POMEG_BERRY = this.berryBlock("pomeg")
val QUALOT_BERRY = this.berryBlock("qualot")
val RABUTA_BERRY = this.berryBlock("rabuta")
val RAWST_BERRY = this.berryBlock("rawst")
val RAZZ_BERRY = this.berryBlock("razz")
val RINDO_BERRY = this.berryBlock("rindo")
val ROSELI_BERRY = this.berryBlock("roseli")
val ROWAP_BERRY = this.berryBlock("rowap")
val SALAC_BERRY = this.berryBlock("salac")
val SHUCA_BERRY = this.berryBlock("shuca")
val SITRUS_BERRY = this.berryBlock("sitrus")
val SPELON_BERRY = this.berryBlock("spelon")
val STARF_BERRY = this.berryBlock("starf")
val TAMATO_BERRY = this.berryBlock("tamato")
val TANGA_BERRY = this.berryBlock("tanga")
val TOUGA_BERRY = this.berryBlock("touga")
val WACAN_BERRY = this.berryBlock("wacan")
val WATMEL_BERRY = this.berryBlock("watmel")
val WEPEAR_BERRY = this.berryBlock("wepear")
val WIKI_BERRY = this.berryBlock("wiki")
val YACHE_BERRY = this.berryBlock("yache")
fun berries() = this.berries.toMap()
private fun berryBlock(name: String): BerryBlock {
val identifier = cobblemonResource("${name}_berry")
val block = this.create(identifier.path, BerryBlock(identifier, AbstractBlock.Settings.copy(Blocks.WHEAT).dynamicBounds().sounds(BlockSoundGroup.CROP)))
this.berries[identifier] = block
return block
}
/**
* Helper method for creating logs
* copied over from Vanilla
@@ -243,4 +332,4 @@ object CobblemonBlocks : PlatformRegistry<Registry<Block>, RegistryKey<Registry<
val block = BlocksInvoker.createLeavesBlock(BlockSoundGroup.GRASS)
return this.create(name, block)
}
}
}
@@ -8,29 +8,41 @@
package com.cobblemon.mod.common
import com.cobblemon.mod.common.api.mulch.MulchVariant
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.Natures
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.block.BerryBlock
import com.cobblemon.mod.common.block.MintBlock.MintType
import com.cobblemon.mod.common.item.*
import com.cobblemon.mod.common.item.group.CobblemonItemGroups
import com.cobblemon.mod.common.item.interactive.CandyItem
import com.cobblemon.mod.common.item.interactive.EnergyRoot
import com.cobblemon.mod.common.item.interactive.LinkCableItem
import com.cobblemon.mod.common.item.interactive.MintItem
import com.cobblemon.mod.common.item.interactive.RemedyItem
import com.cobblemon.mod.common.item.interactive.VitaminItem
import com.cobblemon.mod.common.item.battle.DireHitItem
import com.cobblemon.mod.common.item.battle.GuardSpecItem
import com.cobblemon.mod.common.item.battle.XStatItem
import com.cobblemon.mod.common.item.berry.FriendshipRaisingBerryItem
import com.cobblemon.mod.common.item.berry.HealingBerryItem
import com.cobblemon.mod.common.item.berry.PPRestoringBerryItem
import com.cobblemon.mod.common.item.berry.PortionHealingBerryItem
import com.cobblemon.mod.common.item.berry.StatusCuringBerryItem
import com.cobblemon.mod.common.item.berry.VolatileCuringBerryItem
import com.cobblemon.mod.common.item.interactive.*
import com.cobblemon.mod.common.item.interactive.PotionItem
import com.cobblemon.mod.common.platform.PlatformRegistry
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.helditem.CobblemonHeldItemManager
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.block.Block
import net.minecraft.block.ComposterBlock
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.effect.StatusEffectInstance
import net.minecraft.entity.effect.StatusEffects
import net.minecraft.item.*
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.minecraft.registry.RegistryKey
import net.minecraft.registry.RegistryKeys
import net.minecraft.util.Identifier
import net.minecraft.world.World
@Suppress("unused")
object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<Item>>, Item>() {
@@ -219,8 +231,84 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
@JvmField val PEAT_BLOCK = noSettingsItem("peat_block")
@JvmField val RAZOR_CLAW = noSettingsItem("razor_claw")
@JvmField val RAZOR_FANG = noSettingsItem("razor_fang")
// ToDo enable me when malicious armor goes in the game
//@JvmField val AUSPICIOUS_ARMOR = heldItem("auspicious_armor")
// Armor
@JvmField val AUSPICIOUS_ARMOR = armorItem("auspicious_armor", AuspiciousArmorMaterial(), ArmorItem.Type.CHESTPLATE, Item.Settings().fireproof())
@JvmField val MALICIOUS_ARMOR = armorItem("malicious_armor", MaliciousArmorMaterial(), ArmorItem.Type.CHESTPLATE, Item.Settings().fireproof())
private val berries = mutableMapOf<Identifier, BerryItem>()
// Plants
@JvmField val ORAN_BERRY = berryItem("oran", HealingBerryItem(CobblemonBlocks.ORAN_BERRY) { CobblemonMechanics.berries.oranRestoreAmount })
@JvmField val CHERI_BERRY = berryItem("cheri", StatusCuringBerryItem(CobblemonBlocks.CHERI_BERRY, Statuses.PARALYSIS))
@JvmField val CHESTO_BERRY = berryItem("chesto", StatusCuringBerryItem(CobblemonBlocks.CHESTO_BERRY, Statuses.SLEEP))
@JvmField val PECHA_BERRY = berryItem("pecha", StatusCuringBerryItem(CobblemonBlocks.PECHA_BERRY, Statuses.POISON, Statuses.POISON_BADLY))
@JvmField val RAWST_BERRY = berryItem("rawst", StatusCuringBerryItem(CobblemonBlocks.RAWST_BERRY, Statuses.BURN))
@JvmField val ASPEAR_BERRY = berryItem("aspear", StatusCuringBerryItem(CobblemonBlocks.ASPEAR_BERRY, Statuses.FROZEN))
@JvmField val PERSIM_BERRY = berryItem("persim", VolatileCuringBerryItem(CobblemonBlocks.PERSIM_BERRY, "confusion"))
@JvmField val RAZZ_BERRY = berryItem("razz", CobblemonBlocks.RAZZ_BERRY)
@JvmField val BLUK_BERRY = berryItem("bluk", CobblemonBlocks.BLUK_BERRY)
@JvmField val NANAB_BERRY = berryItem("nanab", CobblemonBlocks.NANAB_BERRY)
@JvmField val WEPEAR_BERRY = berryItem("wepear", CobblemonBlocks.WEPEAR_BERRY)
@JvmField val PINAP_BERRY = berryItem("pinap", CobblemonBlocks.PINAP_BERRY)
@JvmField val OCCA_BERRY = berryItem("occa", CobblemonBlocks.OCCA_BERRY)
@JvmField val PASSHO_BERRY = berryItem("passho", CobblemonBlocks.PASSHO_BERRY)
@JvmField val WACAN_BERRY = berryItem("wacan", CobblemonBlocks.WACAN_BERRY)
@JvmField val RINDO_BERRY = berryItem("rindo", CobblemonBlocks.RINDO_BERRY)
@JvmField val YACHE_BERRY = berryItem("yache", CobblemonBlocks.YACHE_BERRY)
@JvmField val CHOPLE_BERRY = berryItem("chople", CobblemonBlocks.CHOPLE_BERRY)
@JvmField val KEBIA_BERRY = berryItem("kebia", CobblemonBlocks.KEBIA_BERRY)
@JvmField val SHUCA_BERRY = berryItem("shuca", CobblemonBlocks.SHUCA_BERRY)
@JvmField val COBA_BERRY = berryItem("coba", CobblemonBlocks.COBA_BERRY)
@JvmField val PAYAPA_BERRY = berryItem("payapa", CobblemonBlocks.PAYAPA_BERRY)
@JvmField val TANGA_BERRY = berryItem("tanga", CobblemonBlocks.TANGA_BERRY)
@JvmField val CHARTI_BERRY = berryItem("charti", CobblemonBlocks.CHARTI_BERRY)
@JvmField val KASIB_BERRY = berryItem("kasib", CobblemonBlocks.KASIB_BERRY)
@JvmField val HABAN_BERRY = berryItem("haban", CobblemonBlocks.HABAN_BERRY)
@JvmField val COLBUR_BERRY = berryItem("colbur", CobblemonBlocks.COLBUR_BERRY)
@JvmField val BABIRI_BERRY = berryItem("babiri", CobblemonBlocks.BABIRI_BERRY)
@JvmField val CHILAN_BERRY = berryItem("chilan", CobblemonBlocks.CHILAN_BERRY)
@JvmField val ROSELI_BERRY = berryItem("roseli", CobblemonBlocks.ROSELI_BERRY)
@JvmField val LEPPA_BERRY = berryItem("leppa", PPRestoringBerryItem(CobblemonBlocks.LEPPA_BERRY) { CobblemonMechanics.berries.ppRestoreAmount })
@JvmField val LUM_BERRY = berryItem("lum", StatusCuringBerryItem(CobblemonBlocks.LUM_BERRY))
@JvmField val FIGY_BERRY = berryItem("figy", PortionHealingBerryItem(CobblemonBlocks.FIGY_BERRY, true) { CobblemonMechanics.berries.portionHealRatio })
@JvmField val WIKI_BERRY = berryItem("wiki", PortionHealingBerryItem(CobblemonBlocks.WIKI_BERRY, true) { CobblemonMechanics.berries.portionHealRatio })
@JvmField val MAGO_BERRY = berryItem("mago", PortionHealingBerryItem(CobblemonBlocks.MAGO_BERRY, true) { CobblemonMechanics.berries.portionHealRatio })
@JvmField val AGUAV_BERRY = berryItem("aguav", PortionHealingBerryItem(CobblemonBlocks.AGUAV_BERRY, true) { CobblemonMechanics.berries.portionHealRatio })
@JvmField val IAPAPA_BERRY = berryItem("iapapa", PortionHealingBerryItem(CobblemonBlocks.IAPAPA_BERRY, true) { CobblemonMechanics.berries.portionHealRatio })
@JvmField val SITRUS_BERRY = berryItem("sitrus", HealingBerryItem(CobblemonBlocks.SITRUS_BERRY) { CobblemonMechanics.berries.sitrusHealAmount })
@JvmField val TOUGA_BERRY = berryItem("touga", CobblemonBlocks.TOUGA_BERRY)
@JvmField val CORNN_BERRY = berryItem("cornn", CobblemonBlocks.CORNN_BERRY)
@JvmField val MAGOST_BERRY = berryItem("magost", CobblemonBlocks.MAGOST_BERRY)
@JvmField val RABUTA_BERRY = berryItem("rabuta", CobblemonBlocks.RABUTA_BERRY)
@JvmField val NOMEL_BERRY = berryItem("nomel", CobblemonBlocks.NOMEL_BERRY)
@JvmField val ENIGMA_BERRY = berryItem("enigma", CobblemonBlocks.ENIGMA_BERRY)
@JvmField val POMEG_BERRY = berryItem("pomeg", FriendshipRaisingBerryItem(CobblemonBlocks.POMEG_BERRY, Stats.HP))
@JvmField val KELPSY_BERRY = berryItem("kelpsy", FriendshipRaisingBerryItem(CobblemonBlocks.KELPSY_BERRY, Stats.ATTACK))
@JvmField val QUALOT_BERRY = berryItem("qualot", FriendshipRaisingBerryItem(CobblemonBlocks.QUALOT_BERRY, Stats.DEFENCE))
@JvmField val HONDEW_BERRY = berryItem("hondew", FriendshipRaisingBerryItem(CobblemonBlocks.HONDEW_BERRY, Stats.SPECIAL_ATTACK))
@JvmField val GREPA_BERRY = berryItem("grepa", FriendshipRaisingBerryItem(CobblemonBlocks.GREPA_BERRY, Stats.SPECIAL_DEFENCE))
@JvmField val TAMATO_BERRY = berryItem("tamato", FriendshipRaisingBerryItem(CobblemonBlocks.TAMATO_BERRY, Stats.SPEED))
@JvmField val SPELON_BERRY = berryItem("spelon", CobblemonBlocks.SPELON_BERRY)
@JvmField val PAMTRE_BERRY = berryItem("pamtre", CobblemonBlocks.PAMTRE_BERRY)
@JvmField val WATMEL_BERRY = berryItem("watmel", CobblemonBlocks.WATMEL_BERRY)
@JvmField val DURIN_BERRY = berryItem("durin", CobblemonBlocks.DURIN_BERRY)
@JvmField val BELUE_BERRY = berryItem("belue", CobblemonBlocks.BELUE_BERRY)
@JvmField val KEE_BERRY = berryItem("kee", CobblemonBlocks.KEE_BERRY)
@JvmField val MARANGA_BERRY = berryItem("maranga", CobblemonBlocks.MARANGA_BERRY)
@JvmField val HOPO_BERRY = berryItem("hopo", PPRestoringBerryItem(CobblemonBlocks.HOPO_BERRY) { CobblemonMechanics.berries.ppRestoreAmount })
@JvmField val LIECHI_BERRY = berryItem("liechi", CobblemonBlocks.LIECHI_BERRY)
@JvmField val GANLON_BERRY = berryItem("ganlon", CobblemonBlocks.GANLON_BERRY)
@JvmField val SALAC_BERRY = berryItem("salac", CobblemonBlocks.SALAC_BERRY)
@JvmField val PETAYA_BERRY = berryItem("petaya", CobblemonBlocks.PETAYA_BERRY)
@JvmField val APICOT_BERRY = berryItem("apicot", CobblemonBlocks.APICOT_BERRY)
@JvmField val LANSAT_BERRY = berryItem("lansat", CobblemonBlocks.LANSAT_BERRY)
@JvmField val STARF_BERRY = berryItem("starf", CobblemonBlocks.STARF_BERRY)
@JvmField val MICLE_BERRY = berryItem("micle", CobblemonBlocks.MICLE_BERRY)
@JvmField val CUSTAP_BERRY = berryItem("custap", CobblemonBlocks.CUSTAP_BERRY)
@JvmField val JABOCA_BERRY = berryItem("jaboca", CobblemonBlocks.JABOCA_BERRY)
@JvmField val ROWAP_BERRY = berryItem("rowap", CobblemonBlocks.ROWAP_BERRY)
@JvmField val BERRY_JUICE = this.create("berry_juice", BerryJuiceItem())
// Medicine
@JvmField
@@ -248,17 +336,30 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
@JvmField
val ZINC = create("zinc", VitaminItem(Stats.SPECIAL_DEFENCE))
@JvmField
val MEDICINAL_LEEK = create("medicinal_leek", MedicinalLeekItem(CobblemonBlocks.MEDICINAL_LEEK_CROP))
val MEDICINAL_LEEK = create("medicinal_leek", MedicinalLeekItem(CobblemonBlocks.MEDICINAL_LEEK, Item.Settings().food(FoodComponent.Builder().snack().hunger(1).saturationModifier(0.2f).build())))
@JvmField
val ROASTED_LEEK = create("roasted_leek", Item(Item.Settings().food(FoodComponent.Builder().snack().hunger(3).saturationModifier(0.2f).build())))
val ROASTED_LEEK = create("roasted_leek", Item(Item.Settings().food(FoodComponent.Builder().snack().hunger(3).saturationModifier(0.3f).build())))
@JvmField
val BRAISED_VIVICHOKE = create("braised_vivichoke", Item(Item.Settings().food(FoodComponent.Builder().hunger(6).saturationModifier(0.6f).build())))
val BRAISED_VIVICHOKE = create("braised_vivichoke", Item(Item.Settings().maxCount(1).food(FoodComponent.Builder().hunger(6).saturationModifier(0.6f).build())))
@JvmField
val ENERGY_ROOT = create("energy_root", EnergyRoot(CobblemonBlocks.ENERGY_ROOT))
val VIVICHOKE_DIP = create("vivichoke_dip", object : StewItem(Settings().maxCount(1)
.food(FoodComponent.Builder()
.hunger(10)
.saturationModifier(1.2F)
.statusEffect(StatusEffectInstance(StatusEffects.ABSORPTION, 900, 0), 1F)
.alwaysEdible()
.build())) {
override fun finishUsing(stack: ItemStack?, world: World?, user: LivingEntity?): ItemStack {
user?.clearStatusEffects()
return super.finishUsing(stack, world, user)
}
})
@JvmField
val ENERGY_ROOT = create("energy_root", EnergyRootItem(CobblemonBlocks.ENERGY_ROOT, Item.Settings().food(FoodComponent.Builder().hunger(1).snack().saturationModifier(0.2f).build())))
@JvmField
val REVIVAL_HERB = create("revival_herb", RevivalHerbItem(CobblemonBlocks.REVIVAL_HERB))
@JvmField
val PEP_UP_FLOWER = create("pep_up_flower", PepUpFlowerItem(Item.Settings()))
val PEP_UP_FLOWER = blockItem("pep_up_flower", CobblemonBlocks.PEP_UP_FLOWER)
@JvmField
val MEDICINAL_BREW = create("medicinal_brew", Item(Item.Settings()))
@JvmField
@@ -267,18 +368,30 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
val FINE_REMEDY = create("fine_remedy", RemedyItem(RemedyItem.FINE))
@JvmField
val SUPERB_REMEDY = create("superb_remedy", RemedyItem(RemedyItem.SUPERB))
@JvmField
val HEAL_POWDER = create("heal_powder", Item(Item.Settings()))
val POTION = create("potion", PotionItem(PotionType.POTION))
@JvmField
val LEEK_AND_POTATO_STEW = create("leek_and_potato_stew", StewItem(Item.Settings().food(FoodComponent.Builder().hunger(8).saturationModifier(0.6f).build())))
val SUPER_POTION = create("super_potion", PotionItem(PotionType.SUPER_POTION))
@JvmField
val REVIVE = create("revive", Item(Item.Settings()))
val HYPER_POTION = create("hyper_potion", PotionItem(PotionType.HYPER_POTION))
@JvmField
val MAX_REVIVE = create("max_revive", Item(Item.Settings()))
val MAX_POTION = create("max_potion", PotionItem(PotionType.MAX_POTION))
@JvmField
val PP_UP = create("pp_up", Item(Item.Settings()))
val FULL_RESTORE = create("full_restore", PotionItem(PotionType.FULL_RESTORE))
@JvmField
val PP_MAX = create("pp_max", Item(Item.Settings()))
val HEAL_POWDER = create("heal_powder", HealPowderItem())
@JvmField
val LEEK_AND_POTATO_STEW = create("leek_and_potato_stew", StewItem(Item.Settings().food(FoodComponent.Builder().hunger(8).saturationModifier(0.6f).build()).maxCount(1)))
@JvmField
val REVIVE = create("revive", ReviveItem(max = false))
@JvmField
val MAX_REVIVE = create("max_revive", ReviveItem(max = true))
@JvmField
val PP_UP = create("pp_up", PPUpItem(1))
@JvmField
val PP_MAX = create("pp_max", PPUpItem(3))
@JvmField
val RED_MINT_SEEDS = blockItem("red_mint_seeds", MintType.RED.getCropBlock())
@@ -348,12 +461,28 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
@JvmField
val SERIOUS_MINT = create("serious_mint", MintItem(Natures.SERIOUS))
@JvmField val X_ACCURACY = create("x_accuracy", CobblemonItem(Item.Settings()))
@JvmField val X_ATTACK = create("x_attack", CobblemonItem(Item.Settings()))
@JvmField val X_DEFENSE = create("x_defense", CobblemonItem(Item.Settings()))
@JvmField val X_SP_ATK = create("x_sp_atk", CobblemonItem(Item.Settings()))
@JvmField val X_SP_DEF = create("x_sp_def", CobblemonItem(Item.Settings()))
@JvmField val X_SPEED = create("x_speed", CobblemonItem(Item.Settings()))
@JvmField val X_ACCURACY = create("x_${Stats.ACCURACY.identifier.path}", XStatItem(Stats.ACCURACY))
@JvmField val X_ATTACK = create("x_${Stats.ATTACK.identifier.path}", XStatItem(Stats.ATTACK))
@JvmField val X_DEFENSE = create("x_${Stats.DEFENCE.identifier.path}", XStatItem(Stats.DEFENCE))
@JvmField val X_SP_ATK = create("x_${Stats.SPECIAL_ATTACK.identifier.path}", XStatItem(Stats.SPECIAL_ATTACK))
@JvmField val X_SP_DEF = create("x_${Stats.SPECIAL_DEFENCE.identifier.path}", XStatItem(Stats.SPECIAL_DEFENCE))
@JvmField val X_SPEED = create("x_${Stats.SPEED.identifier.path}", XStatItem(Stats.SPEED))
@JvmField val DIRE_HIT = create("dire_hit", DireHitItem())
@JvmField val GUARD_SPEC = create("guard_spec", GuardSpecItem())
@JvmField val BURN_HEAL = create("burn_heal", StatusCureItem("item.cobblemon.burn_heal", Statuses.BURN))
@JvmField val PARALYZE_HEAL = create("paralyze_heal", StatusCureItem("item.cobblemon.paralyze_heal", Statuses.PARALYSIS))
@JvmField val ICE_HEAL = create("ice_heal", StatusCureItem("item.cobblemon.ice_heal", Statuses.FROZEN))
@JvmField val ANTIDOTE = create("antidote", StatusCureItem("item.cobblemon.antidote", Statuses.POISON, Statuses.POISON_BADLY))
@JvmField val AWAKENING = create("awakening", StatusCureItem("item.cobblemon.awakening", Statuses.SLEEP))
@JvmField val FULL_HEAL = create("full_heal", StatusCureItem("item.cobblemon.full_heal"))
@JvmField val ETHER = create("ether", EtherItem(max = false))
@JvmField val MAX_ETHER = create("max_ether", EtherItem(max = true))
@JvmField val ELIXIR = create("elixir", ElixirItem(max = false))
@JvmField val MAX_ELIXIR = create("max_elixir", ElixirItem(max = true))
/**
* Evolution Ores and Stones
@@ -425,7 +554,7 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
@JvmField
val ASSAULT_VEST = heldItem("assault_vest")
@JvmField
val BIG_ROOT = create("big_root", BigRoot(CobblemonBlocks.BIG_ROOT))
val BIG_ROOT = blockItem("big_root", CobblemonBlocks.BIG_ROOT)
@JvmField
val BLACK_BELT = heldItem("black_belt")
@JvmField
@@ -488,26 +617,56 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
val TWISTED_SPOON = heldItem("twisted_spoon")
@JvmField
val WISE_GLASSES = heldItem("wise_glasses")
@JvmField
val MENTAL_HERB = heldItem("mental_herb")
@JvmField
val MIRROR_HERB = heldItem("mirror_herb")
@JvmField
val POWER_HERB = heldItem("power_herb")
@JvmField
val WHITE_HERB = heldItem("white_herb")
@JvmField
val BRIGHT_POWDER = heldItem("bright_powder")
@JvmField
val METAL_POWDER = heldItem("metal_powder")
@JvmField
val QUICK_POWDER = heldItem("quick_powder")
@JvmField
val DESTINY_KNOT = heldItem("destiny_knot")
@JvmField
val EVERSTONE = heldItem("everstone")
@JvmField
val POWER_ANKLET = heldItem("power_anklet")
@JvmField
val POWER_BAND = heldItem("power_band")
@JvmField
val POWER_BELT = heldItem("power_belt")
@JvmField
val POWER_BRACER = heldItem("power_bracer")
@JvmField
val POWER_LENS = heldItem("power_lens")
@JvmField
val POWER_WEIGHT = heldItem("power_weight")
// Mulch
@JvmField
val MULCH_BASE = noSettingsItem("mulch_base")
@JvmField
val COARSE_MULCH = noSettingsItem("coarse_mulch")
val COARSE_MULCH = mulchItem("coarse_mulch", MulchVariant.COARSE)
@JvmField
val GROWTH_MULCH = noSettingsItem("growth_mulch")
val GROWTH_MULCH = mulchItem("growth_mulch", MulchVariant.GROWTH)
@JvmField
val HUMID_MULCH = noSettingsItem("humid_mulch")
val HUMID_MULCH = mulchItem("humid_mulch", MulchVariant.HUMID)
@JvmField
val LOAMY_MULCH = noSettingsItem("loamy_mulch")
val LOAMY_MULCH = mulchItem("loamy_mulch", MulchVariant.LOAMY)
@JvmField
val PEAT_MULCH = noSettingsItem("peat_mulch")
val PEAT_MULCH = mulchItem("peat_mulch", MulchVariant.PEAT)
@JvmField
val RICH_MULCH = noSettingsItem("rich_mulch")
val RICH_MULCH = mulchItem("rich_mulch", MulchVariant.RICH)
@JvmField
val SANDY_MULCH = noSettingsItem("sandy_mulch")
val SANDY_MULCH = mulchItem("sandy_mulch", MulchVariant.SANDY)
@JvmField
val SURPRISE_MULCH = noSettingsItem("surprise_mulch")
val SURPRISE_MULCH = mulchItem("surprise_mulch", MulchVariant.SURPRISE)
// Misc
@JvmField
@@ -517,6 +676,10 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
private fun noSettingsItem(name: String): CobblemonItem = this.create(name, CobblemonItem(Item.Settings()))
fun berries() = this.berries.toMap()
private fun mulchItem(name: String, mulchVariant: MulchVariant): MulchItem = this.create(name, MulchItem(mulchVariant))
private fun pokeBallItem(pokeBall: PokeBall): PokeBallItem {
val item = create(pokeBall.name.path, PokeBallItem(pokeBall))
pokeBall.item = item
@@ -535,4 +698,23 @@ object CobblemonItems : PlatformRegistry<Registry<Item>, RegistryKey<Registry<It
}
)
}
private fun armorItem(name: String, type: ArmorMaterial, slot: ArmorItem.Type, settings: Item.Settings): ArmorItem {
val armor = ArmorItem(type, slot, settings)
val item = create(name, armor)
return item
}
private fun berryItem(name: String, berryBlock: BerryBlock): BerryItem {
val finalName = "${name}_berry"
val item = this.create(finalName, BerryItem(berryBlock))
this.berries[cobblemonResource(finalName)] = item
return item
}
private fun berryItem(name: String, berryItem: BerryItem): BerryItem {
val finalName = "${name}_berry"
val item = this.create(finalName, berryItem)
this.berries[cobblemonResource(finalName)] = item
return item
}
}
@@ -11,6 +11,8 @@ package com.cobblemon.mod.common
import com.bedrockk.molang.Expression
import com.cobblemon.mod.common.api.data.DataRegistry
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.mechanics.BerriesMechanic
import com.cobblemon.mod.common.mechanics.PotionsMechanic
import com.cobblemon.mod.common.mechanics.RemediesMechanic
import com.cobblemon.mod.common.util.adapters.ExpressionAdapter
import com.cobblemon.mod.common.util.cobblemonResource
@@ -30,11 +32,19 @@ object CobblemonMechanics : DataRegistry {
.create()
var remedies = RemediesMechanic()
var berries = BerriesMechanic()
var potions = PotionsMechanic()
override fun sync(player: ServerPlayerEntity) {}
override fun reload(manager: ResourceManager) {
manager.getResourceOrThrow(cobblemonResource("mechanics/remedies.json")).inputStream.use {
remedies = gson.fromJson(it.reader(), RemediesMechanic::class.java)
remedies = loadMechanic(manager, "remedies", RemediesMechanic::class.java)
berries = loadMechanic(manager, "berries", BerriesMechanic::class.java)
potions = loadMechanic(manager, "potions", PotionsMechanic::class.java)
}
private fun <T> loadMechanic(manager: ResourceManager, name: String, clazz: Class<T>): T {
manager.getResourceOrThrow(cobblemonResource("mechanics/$name.json")).inputStream.use {
return gson.fromJson(it.reader(), clazz)
}
}
}
@@ -13,6 +13,9 @@ import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.api.net.ServerNetworkPacketHandler
import com.cobblemon.mod.common.client.net.SetClientPlayerDataHandler
import com.cobblemon.mod.common.client.net.battle.*
import com.cobblemon.mod.common.client.net.callback.move.OpenMoveCallbackHandler
import com.cobblemon.mod.common.client.net.callback.party.OpenPartyCallbackHandler
import com.cobblemon.mod.common.client.net.callback.partymove.OpenPartyMoveCallbackHandler
import com.cobblemon.mod.common.client.net.data.DataRegistrySyncPacketHandler
import com.cobblemon.mod.common.client.net.data.UnlockReloadPacketHandler
import com.cobblemon.mod.common.client.net.effect.SpawnSnowstormParticleHandler
@@ -49,7 +52,11 @@ import com.cobblemon.mod.common.client.net.trade.TradeOfferNotificationHandler
import com.cobblemon.mod.common.client.net.trade.TradeStartedHandler
import com.cobblemon.mod.common.client.net.trade.TradeUpdatedHandler
import com.cobblemon.mod.common.net.messages.client.battle.*
import com.cobblemon.mod.common.net.messages.client.callback.OpenMoveCallbackPacket
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyCallbackPacket
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyMoveCallbackPacket
import com.cobblemon.mod.common.net.messages.client.data.AbilityRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.data.BerryRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.data.MovesRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.data.PropertiesCompletionRegistrySyncPacket
import com.cobblemon.mod.common.net.messages.client.data.SpeciesRegistrySyncPacket
@@ -98,6 +105,12 @@ import com.cobblemon.mod.common.net.messages.server.RequestMoveSwapPacket
import com.cobblemon.mod.common.net.messages.server.SelectStarterPacket
import com.cobblemon.mod.common.net.messages.server.SendOutPokemonPacket
import com.cobblemon.mod.common.net.messages.server.battle.BattleSelectActionsPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.move.MoveSelectedPacket
import com.cobblemon.mod.common.net.messages.server.callback.party.PartyPokemonSelectedPacket
import com.cobblemon.mod.common.net.messages.server.callback.party.PartySelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.partymove.PartyMoveSelectCancelledPacket
import com.cobblemon.mod.common.net.messages.server.callback.partymove.PartyPokemonMoveSelectedPacket
import com.cobblemon.mod.common.net.messages.server.pasture.PasturePokemonPacket
import com.cobblemon.mod.common.net.messages.server.pasture.UnpastureAllPokemonPacket
import com.cobblemon.mod.common.net.messages.server.pasture.UnpasturePokemonPacket
@@ -122,6 +135,12 @@ import com.cobblemon.mod.common.net.messages.server.trade.OfferTradePacket
import com.cobblemon.mod.common.net.messages.server.trade.UpdateTradeOfferPacket
import com.cobblemon.mod.common.net.serverhandling.ChallengeHandler
import com.cobblemon.mod.common.net.serverhandling.battle.BattleSelectActionsHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.move.MoveSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartyPokemonSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.callback.party.PartySelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.partymove.PartyMoveSelectCancelledHandler
import com.cobblemon.mod.common.net.serverhandling.callback.partymove.PartyPokemonMoveSelectedHandler
import com.cobblemon.mod.common.net.serverhandling.evolution.AcceptEvolutionHandler
import com.cobblemon.mod.common.net.serverhandling.pasture.PasturePokemonHandler
import com.cobblemon.mod.common.net.serverhandling.pasture.UnpastureAllPokemonHandler
@@ -236,7 +255,7 @@ object CobblemonNetwork : NetworkManager {
this.createClientBound(BattleCaptureStartPacket.ID, BattleCaptureStartPacket::decode, BattleCaptureStartHandler)
this.createClientBound(BattleCaptureEndPacket.ID, BattleCaptureEndPacket::decode, BattleCaptureEndHandler)
this.createClientBound(BattleCaptureShakePacket.ID, BattleCaptureShakePacket::decode, BattleCaptureShakeHandler)
this.createClientBound(BattleApplyCaptureResponsePacket.ID, BattleApplyCaptureResponsePacket::decode, BattleApplyCaptureResponseHandler)
this.createClientBound(BattleApplyPassResponsePacket.ID, BattleApplyPassResponsePacket::decode, BattleApplyPassResponseHandler)
this.createClientBound(BattleChallengeNotificationPacket.ID, BattleChallengeNotificationPacket::decode, BattleChallengeNotificationHandler)
this.createClientBound(BattleUpdateTeamPokemonPacket.ID, BattleUpdateTeamPokemonPacket::decode, BattleUpdateTeamPokemonHandler)
this.createClientBound(BattlePersistentStatusPacket.ID, BattlePersistentStatusPacket::decode, BattlePersistentStatusHandler)
@@ -255,6 +274,7 @@ object CobblemonNetwork : NetworkManager {
this.createClientBound(SpeciesRegistrySyncPacket.ID, SpeciesRegistrySyncPacket::decode, DataRegistrySyncPacketHandler())
this.createClientBound(PropertiesCompletionRegistrySyncPacket.ID, PropertiesCompletionRegistrySyncPacket::decode, DataRegistrySyncPacketHandler())
this.createClientBound(UnlockReloadPacket.ID, UnlockReloadPacket::decode, UnlockReloadPacketHandler)
this.createClientBound(BerryRegistrySyncPacket.ID, BerryRegistrySyncPacket::decode, DataRegistrySyncPacketHandler())
// Effects
this.createClientBound(SpawnSnowstormParticlePacket.ID, SpawnSnowstormParticlePacket::decode, SpawnSnowstormParticleHandler)
@@ -282,6 +302,15 @@ object CobblemonNetwork : NetworkManager {
// Behaviours
this.createClientBound(PokemonCryPacket.ID, PokemonCryPacket::decode, PokemonCryHandler)
// Move select packets
this.createClientBound(OpenMoveCallbackPacket.ID, OpenMoveCallbackPacket::decode, OpenMoveCallbackHandler)
// Party select packets
this.createClientBound(OpenPartyCallbackPacket.ID, OpenPartyCallbackPacket::decode, OpenPartyCallbackHandler)
// Party move select packets
this.createClientBound(OpenPartyMoveCallbackPacket.ID, OpenPartyMoveCallbackPacket::decode, OpenPartyMoveCallbackHandler)
}
override fun registerServerBound() {
@@ -332,6 +361,18 @@ object CobblemonNetwork : NetworkManager {
this.createServerBound(PasturePokemonPacket.ID, PasturePokemonPacket::decode, PasturePokemonHandler)
this.createServerBound(UnpasturePokemonPacket.ID, UnpasturePokemonPacket::decode, UnpasturePokemonHandler)
this.createServerBound(UnpastureAllPokemonPacket.ID, UnpastureAllPokemonPacket::decode, UnpastureAllPokemonHandler)
// Move select packets
this.createServerBound(MoveSelectedPacket.ID, MoveSelectedPacket::decode, MoveSelectedHandler)
this.createServerBound(MoveSelectCancelledPacket.ID, MoveSelectCancelledPacket::decode, MoveSelectCancelledHandler)
// Party select packets
this.createServerBound(PartyPokemonSelectedPacket.ID, PartyPokemonSelectedPacket::decode, PartyPokemonSelectedHandler)
this.createServerBound(PartySelectCancelledPacket.ID, PartySelectCancelledPacket::decode, PartySelectCancelledHandler)
// Party move select packets
this.createServerBound(PartyPokemonMoveSelectedPacket.ID, PartyPokemonMoveSelectedPacket::decode, PartyPokemonMoveSelectedHandler)
this.createServerBound(PartyMoveSelectCancelledPacket.ID, PartyMoveSelectCancelledPacket::decode, PartyMoveSelectCancelledHandler)
}
private inline fun <reified T : NetworkPacket<T>> createClientBound(identifier: Identifier, noinline decoder: (PacketByteBuf) -> T, handler: ClientNetworkPacketHandler<T>) {
@@ -34,6 +34,8 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, RegistryKey<Regi
val PC_DROP = this.create("pc.drop")
@JvmField
val PC_RELEASE = this.create("pc.release")
@JvmField
val PC_CLICK = this.create("pc.click")
@JvmField
val HEALING_MACHINE_ACTIVE = this.create("healing_machine.active")
@@ -68,7 +70,26 @@ object CobblemonSounds : PlatformRegistry<Registry<SoundEvent>, RegistryKey<Regi
val PVW_BATTLE = this.create("battle.pvw.default")
@JvmField
val MINT_USE = this.create("mint.use")
val MEDICINE_HERB_USE = this.create("medicine_herb.use")
@JvmField
val MEDICINE_LIQUID_USE = this.create("medicine_liquid.use")
@JvmField
val MEDICINE_PILLS_USE = this.create("medicine_pills.use")
@JvmField
val MEDICINE_SPRAY_USE = this.create("medicine_spray.use")
@JvmField
val BERRY_EAT = this.create("berry.eat")
@JvmField
val MULCH_PLACE = this.create("mulch.place")
@JvmField
val MULCH_REMOVE = this.create("mulch.remove")
@JvmField
val AUSPICIOUS_ARMOR_EQUIP = this.create("auspicious_armor.equip")
@JvmField
val MALICIOUS_ARMOR_EQUIP = this.create("malicious_armor.equip")
private fun create(name: String): SoundEvent = this.create(name, SoundEvent.of(cobblemonResource(name)))
@@ -37,7 +37,7 @@ object Abilities : DataRegistry {
PotentialAbility.types.add(CommonAbilityType)
PotentialAbility.types.add(HiddenAbilityType)
this.abilityMap.clear()
val abilitiesJson = ShowdownService.get().getAbilityIds()
val abilitiesJson = ShowdownService.service.getAbilityIds()
for (i in 0 until abilitiesJson.size()) {
val id = abilitiesJson[i].asString
val ability = AbilityTemplate(id)
@@ -12,6 +12,7 @@ import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.battles.ActiveBattlePokemon
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import java.util.UUID
/**
* A class responsible for parsing a raw simulator protocol message received from Showdown.
@@ -25,7 +26,6 @@ import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
* @since December 31st, 2022
*/
class BattleMessage(rawMessage: String) {
/**
* The ID of the action received in the message.
*/
@@ -53,11 +53,6 @@ class BattleMessage(rawMessage: String) {
*/
private val optionalArgumentMatcher = Regex("^\\$OPTIONAL_ARG_START([^]]+)$OPTIONAL_ARG_END")
/**
* Pattern to match a Showdown position.
*/
private val pnxMatcher = Regex("p\\d[a-c]")
init {
this.parse(rawMessage)
}
@@ -122,6 +117,10 @@ class BattleMessage(rawMessage: String) {
return this
}
fun pokemonByUuid(index: Int, battle: PokemonBattle): BattlePokemon? {
return this.argumentAt(index)?.let { UUID.fromString(it) }?.let { uuid -> battle.actors.flatMap { it.pokemonList }.find { it.uuid == uuid } }
}
/**
* Queries an argument at the given [index] for a 'pnx' that will be parsed into a [BattleActor] and [ActiveBattlePokemon].
*
@@ -165,12 +164,14 @@ class BattleMessage(rawMessage: String) {
* @return A 'pnx' String representing position and a 'uuid' String representing the unique Pokemon if parsed correctly, otherwise null.
*/
fun pnxAndUuid(index: Int): Pair<String, String>? {
val argument = this.argumentAt(index)?.takeIf { it.length >= 3 }?.split(":")?.takeIf { it.size == 2 } ?: return null
val pnx = argument[0].takeIf { it.matches(pnxMatcher) } ?: return null
val argument = this.argumentAt(index)?.takeIf { it.length >= 2 }?.split(":")?.takeIf { it.size == 2 } ?: return null
val pnx = argument[0].takeIf { it.matches(PNX_MATCHER) } ?: return null
val uuid = argument[1].trim()
return pnx to uuid
}
/**
* Attempts to parse an [Effect] from an argument at the given [index].
*
@@ -238,6 +239,14 @@ class BattleMessage(rawMessage: String) {
private const val OPTIONAL_ARG_START = "["
private const val OPTIONAL_ARG_END = "]"
}
/**
* Pattern to match a Showdown position e.g. p2a, p1b
*/
val PNX_MATCHER = Regex("p\\d[a-c]")
/**
* Pattern to match a Showdown side position e.g. p2, p1
*/
val PN_MATCHER = Regex("p\\d")
}
}
@@ -52,6 +52,7 @@ interface Effect {
ABILITY("ability:"),
ITEM("item:"),
MOVE("move:"),
BAGITEM("bagitem:"),
PURE(""),
}
@@ -42,13 +42,11 @@ import com.cobblemon.mod.common.net.messages.client.battle.BattleMusicPacket
import com.cobblemon.mod.common.pokemon.evolution.progress.DefeatEvolutionProgress
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getPlayer
import net.minecraft.entity.Entity
import java.io.File
import java.util.UUID
import java.util.concurrent.ConcurrentLinkedQueue
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
import java.io.File
import kotlin.io.path.Path
import kotlin.io.path.writeLines
/**
* Individual battle instance
@@ -61,7 +59,7 @@ open class PokemonBattle(
val side1: BattleSide,
val side2: BattleSide
) {
/** Whether or not logging will be silenced for this battle. */
/** Whether logging will be silenced for this battle. */
var mute = true
init {
@@ -149,6 +147,11 @@ open class PokemonBattle(
return actors.find { actor -> actor.uuid == actorId }
}
/**
* Gets the first battle actor whom the given player controls, or null if there is no such actor.
*/
fun getActor(player: ServerPlayerEntity) = actors.firstOrNull { it.isForPlayer(player) }
/**
* Gets a BattleActor and an [ActiveBattlePokemon] from a pnx key, e.g. p2a
*
@@ -181,7 +184,7 @@ open class PokemonBattle(
fun writeShowdownAction(vararg messages: String) {
log(messages.joinToString("\n"))
ShowdownService.get().send(battleId, messages.toList().toTypedArray())
ShowdownService.service.send(battleId, messages.toList().toTypedArray())
}
fun turn(newTurnNumber: Int) {
@@ -443,4 +446,4 @@ open class PokemonBattle(
LOGGER.error("Missing interpretation on '{}' action: \nPublic » {}\nPrivate » {}", publicMessage.id, publicMessage.rawMessage, privateMessage.rawMessage)
return Text.literal("Missing interpretation on '${publicMessage.id}' action please report to the developers").red()
}
}
}
@@ -11,12 +11,13 @@ package com.cobblemon.mod.common.api.battles.model.actor
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.net.NetworkPacket
import com.cobblemon.mod.common.battles.ActiveBattlePokemon
import com.cobblemon.mod.common.battles.BallActionResponse
import com.cobblemon.mod.common.battles.ForcePassActionResponse
import com.cobblemon.mod.common.battles.ShowdownActionRequest
import com.cobblemon.mod.common.battles.ShowdownActionResponse
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.exception.IllegalActionChoiceException
import com.cobblemon.mod.common.net.messages.client.battle.BattleApplyPassResponsePacket
import com.cobblemon.mod.common.net.messages.client.battle.BattleMakeChoicePacket
import com.cobblemon.mod.common.net.messages.client.battle.BattleMessagePacket
import java.util.UUID
@@ -40,7 +41,7 @@ abstract class BattleActor(
var request: ShowdownActionRequest? = null
var responses = mutableListOf<ShowdownActionResponse>()
var expectingCaptureActions = 0
val expectingPassActions = mutableListOf<ShowdownActionResponse>()
var mustChoose = false
/** For when battles start, it's the number of Pokémon that are still in the process of being sent out (animation wise) */
@@ -48,6 +49,16 @@ abstract class BattleActor(
abstract val type: ActorType
fun canFitForcedAction() = mustChoose && request?.let { request ->
val countMovable = (request.active?.count() ?: 0) - request.forceSwitch.count { it }
return@let countMovable > expectingPassActions.size && !battle.ended
} ?: false
fun forceChoose(response: ShowdownActionResponse) {
expectingPassActions.add(response)
sendUpdate(BattleApplyPassResponsePacket())
}
fun getSide() = if (this in battle.side1.actors) battle.side1 else battle.side2
open fun getPlayerUUIDs(): Iterable<UUID> = emptyList()
@@ -63,7 +74,7 @@ abstract class BattleActor(
val requestActive = request.active
if (requestActive == null || requestActive.isEmpty() || request.wait) {
this.request = null
expectingCaptureActions = 0
expectingPassActions.clear()
return
}
}
@@ -81,23 +92,24 @@ abstract class BattleActor(
fun setActionResponses(responses: List<ShowdownActionResponse>) {
val request = request ?: return
val originalCaptureActions = expectingCaptureActions
val originalPassActions = expectingPassActions.toList()
responses.forEachIndexed { index, response ->
val activeBattlePokemon = activePokemon.let { if (it.size > index) it[index] else return }
val showdownMoveSet = request.active?.let { if (it.size > index) it[index] else null }
val forceSwitch = request.forceSwitch.let { if (it.size > index) it[index] else false }
if (!response.isValid(activeBattlePokemon, showdownMoveSet, forceSwitch)) {
expectingCaptureActions = originalCaptureActions
expectingPassActions.clear()
expectingPassActions.addAll(originalPassActions)
throw IllegalActionChoiceException(this, "Invalid action choice for ${activeBattlePokemon.battlePokemon!!.getName().string}: $response")
} else if (response is BallActionResponse) {
expectingCaptureActions--
} else if (response is ForcePassActionResponse) {
this.responses.add(expectingPassActions.removeAt(0))
} else {
this.responses.add(response)
}
this.responses.add(response)
}
if (expectingCaptureActions > 0) {
if (expectingPassActions.size > 0) {
throw IllegalActionChoiceException(this, "Invalid action choice: a capture was expected. Are you hacking me?")
}
expectingCaptureActions = originalCaptureActions
mustChoose = false
battle.checkForInputDispatch()
}
@@ -113,7 +125,7 @@ abstract class BattleActor(
}
responses.clear()
request = null
expectingCaptureActions = 0
expectingPassActions.clear()
battle.writeShowdownAction(">$showdownId ${showdownMessages.joinToString()}")
}
@@ -0,0 +1,108 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.berry.spawncondition.BerrySpawnCondition
import com.cobblemon.mod.common.api.data.JsonDataRegistry
import com.cobblemon.mod.common.api.mulch.MulchVariant
import com.cobblemon.mod.common.api.pokemon.stats.Stat
import com.cobblemon.mod.common.api.pokemon.status.Status
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.net.messages.client.data.BerryRegistrySyncPacket
import com.cobblemon.mod.common.pokemon.adapters.CobblemonStatTypeAdapter
import com.cobblemon.mod.common.util.adapters.*
import com.cobblemon.mod.common.util.cobblemonResource
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.awt.Color
import net.minecraft.predicate.NumberRange
import net.minecraft.registry.RegistryKeys
import net.minecraft.registry.tag.TagKey
import net.minecraft.resource.ResourceType
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Identifier
import net.minecraft.util.math.Box
import net.minecraft.util.math.Vec3d
import net.minecraft.world.biome.Biome
/**
* The data registry for [Berry].
*
* @author Licious
* @since November 28th, 2022
*/
object Berries : JsonDataRegistry<Berry> {
override val id: Identifier = cobblemonResource("berries")
override val type: ResourceType = ResourceType.SERVER_DATA
override val observable = SimpleObservable<Berries>()
override val gson = GsonBuilder()
.disableHtmlEscaping()
.setPrettyPrinting()
.registerTypeAdapter(MulchVariant::class.java, MulchVariantAdapter)
.registerTypeAdapter(NumberRange.FloatRange::class.java, FloatNumberRangeAdapter)
.registerTypeAdapter(Status::class.java, StatusAdapter)
.registerTypeAdapter(Box::class.java, BoxAdapter)
.registerTypeAdapter(Vec3d::class.java, VerboseVec3dAdapter)
.registerTypeAdapter(Identifier::class.java, IdentifierAdapter)
.registerTypeAdapter(GrowthFactor::class.java, CobblemonGrowthFactorAdapter)
.registerTypeAdapter(IntRange::class.java, VerboseIntRangeAdapter)
.registerTypeAdapter(Color::class.java, LiteralHexColorAdapter)
.registerTypeAdapter(Stat::class.java, CobblemonStatTypeAdapter)
.registerTypeAdapter(TypeToken.getParameterized(TagKey::class.java, Biome::class.java).type, TagKeyAdapter(RegistryKeys.BIOME))
.registerTypeAdapter(BerrySpawnCondition::class.java, CobblemonBerrySpawnConditionAdapter)
.create()
override val typeToken: TypeToken<Berry> = TypeToken.get(Berry::class.java)
override val resourcePath = "berries"
private val berries = hashMapOf<Identifier, Berry>()
val PECHA
get() = this.getByName("")
override fun reload(data: Map<Identifier, Berry>) {
this.berries.clear()
data.forEach { (identifier, berry) ->
try {
berry.identifier = identifier
berry.validate()
this.berries[identifier] = berry
} catch (e: Exception) {
Cobblemon.LOGGER.error("Skipped loading the {} berry", identifier, e)
}
}
Cobblemon.LOGGER.info("Loaded {} berries", this.berries.size)
this.observable.emit(this)
}
override fun sync(player: ServerPlayerEntity) {
BerryRegistrySyncPacket(this.all()).sendToPlayer(player)
}
fun all() = this.berries.values.toList()
/**
* Gets a berry if loaded.
*
* @param identifier The identifier of the berry.
* @return The [Berry] if loaded otherwise null.
*/
fun getByIdentifier(identifier: Identifier): Berry? = this.berries[identifier]
/**
* Gets a berry if loaded.
*
* @param name The path of the identifier of the berry under the [Cobblemon.MODID] namespace.
* @return The [Berry] if loaded otherwise null.
*/
fun getByName(name: String): Berry? = this.getByIdentifier(cobblemonResource(name))
}
@@ -0,0 +1,349 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.api.berry.spawncondition.BerrySpawnCondition
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.berry.BerryYieldCalculationEvent
import com.cobblemon.mod.common.api.mulch.MulchVariant
import com.cobblemon.mod.common.block.BerryBlock
import com.cobblemon.mod.common.block.entity.BerryBlockEntity
import com.cobblemon.mod.common.item.BerryItem
import com.cobblemon.mod.common.pokemon.Nature
import com.cobblemon.mod.common.util.readBox
import com.cobblemon.mod.common.util.writeBox
import com.google.gson.annotations.SerializedName
import java.awt.Color
import java.util.EnumSet
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.client.model.ModelPart
import net.minecraft.entity.LivingEntity
import net.minecraft.network.PacketByteBuf
import net.minecraft.registry.tag.TagKey
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Box
import net.minecraft.util.math.Vec3d
import net.minecraft.util.shape.VoxelShape
import net.minecraft.util.shape.VoxelShapes
import net.minecraft.world.World
import net.minecraft.world.biome.Biome
/**
* Represents the data behind a berry.
*
* @property identifier The [Identifier] of this berry.
* @property baseYield The [IntRange] possible for the berry tree before [bonusYield] is calculated.
* @property preferredBiomeTags The [TagKey]s of the berries preffered biomes. Determines spawning and yield
* @property growthTime The [IntRange] possible in minutes for how long the berry tree takes to grow.
* @property refreshRate The [IntRange] possible in minutes for how long the berry tree takes to regrow its berries once it has been harvested.
* @depreciated @property lifeCycles The [IntRange] possible for the berry to live for between harvests.
* @property favoriteMulches The types of mulches that benefit this berries yield
* @property growthFactors An array of [GrowthFactor]s that will affect this berry. The client is not aware of these.
* @property mutations A map of the partner berry as the key and the value as the resulting mutation with this berry.
* @property growthPoints A collection of [GrowthPoint]s for the berry flowers and fruit.
* @property sproutShapeBoxes A collection of [Box]es that make up the tree [VoxelShape] during the sprouting stages.
* @property matureShapeBoxes A collection of [Box]es that make up the tree [VoxelShape] during the mature stages.
* @property flavors The [Flavor] values.
* @property tintIndexes Determines tints at specific indexes if any.
* @property flowerModelIdentifier The [Identifier] for the model of the berry in flower form.
* @property flowerTexture The [Identifier] for the texture of the berry in flower form. This is resolved into a [ModelPart] on the client.
* @property fruitModelIdentifier The [Identifier] for the model of the berry in flower form. This is resolved into a [ModelPart] on the client.
* @property fruitTexture The [Identifier] for the texture of the berry in flower form.
*
* @throws IllegalArgumentException if the any yield range argument is not a positive range.
*/
class Berry(
identifier: Identifier,
val baseYield: IntRange,
val preferredBiomeTags: List<TagKey<Biome>>,
val growthTime: IntRange,
val refreshRate: IntRange,
//val lifeCycles: IntRange,
val favoriteMulches: EnumSet<MulchVariant>,
val growthFactors: Collection<GrowthFactor>,
val spawnConditions: List<BerrySpawnCondition>,
var growthPoints: Array<GrowthPoint>,
val randomizedGrowthPoints: Boolean = true,
val mutations: Map<Identifier, Identifier>,
@SerializedName("sproutShape")
private val sproutShapeBoxes: Collection<Box>,
@SerializedName("matureShape")
private val matureShapeBoxes: Collection<Box>,
private val flavors: Map<Flavor, Int>,
val tintIndexes: Map<Int, Color>,
@SerializedName("flowerModel")
val flowerModelIdentifier: Identifier,
val flowerTexture: Identifier,
@SerializedName("fruitModel")
val fruitModelIdentifier: Identifier,
val fruitTexture: Identifier,
val weight: Float
) {
@Transient
var identifier: Identifier = identifier
internal set
@Transient
private lateinit var shapedFlower: HashMap<Int, VoxelShape>
@Transient
private lateinit var shapedFruit: HashMap<Int, VoxelShape>
/**
* The [VoxelShape] of the tree during the sprouting stages.
*/
@Transient
lateinit var sproutShape: VoxelShape
private set
/**
* The [VoxelShape] of the tree during the mature stages.
*/
@Transient
lateinit var matureShape: VoxelShape
private set
init {
this.validate()
}
/**
* Finds the [BerryItem] that uses this berry for data.
*
* @return The [BerryItem] if existing.
*/
fun item(): BerryItem? = CobblemonItems.berries()[this.identifier]
/**
* Finds the [BerryBlock] that uses this berry for data.
*
* @return The [BerryBlock] if existing.
*/
fun block(): BerryBlock? = CobblemonBlocks.berries()[this.identifier]
/**
* Query the value of a certain flavor.
*
* @param flavor The [Flavor] being queried.
* @return The value if any or 0.
*/
fun flavor(flavor: Flavor): Int = this.flavors[flavor] ?: 0
fun dislikedBy(nature: Nature): Boolean {
val dislikedFlavor = nature.dislikedFlavor ?: return false
return flavor(dislikedFlavor) > 0
}
/**
* Calculates the yield for a berry tree being planted or replanted after a life cycle.
* Triggers [BerryYieldCalculationEvent].
*
* @param world The [World] the tree is present in.
* @param state The [BlockState] of the tree.
* @param pos The [BlockPos] of the tree.
* @param placer The [LivingEntity] tending to the tree, if any.
* @return The total berry stack count.
*/
fun calculateYield(world: World, state: BlockState, pos: BlockPos, placer: LivingEntity? = null): Int {
val base = this.baseYield.random()
val bonus = this.bonusYield(world, state, pos)
var yield = base + bonus.first
val event = BerryYieldCalculationEvent(this, world, state, pos, placer, yield, bonus.second)
val treeEntity = world.getBlockEntity(pos) as BerryBlockEntity
if (treeEntity.mulchVariant == MulchVariant.RICH) {
yield = yield.times(1.2).coerceAtMost(maxYield().toDouble()).toInt()
treeEntity.mulchDuration--
}
CobblemonEvents.BERRY_YIELD.post(event) { yield = it.yield }
return yield
//Just for testing the renderer
//return growthPoints.size
}
/**
* Calculates and returns the minimum possible yield by summing [baseYield] and [growthFactors] minimum values.
*
* @return The minimum possible yield.
*/
fun minYield() = this.baseYield.first + this.growthFactors.sumOf { it.minYield() }
/**
* Calculates and returns the maximum possible yield by summing [baseYield] and [growthFactors] max values.
*
* @return The maximum possible yield.
*/
fun maxYield() = this.baseYield.last + this.growthFactors.sumOf { it.maxYield() }
/**
* Checks if this berry can mutate with the given [partner].
* For the berry the mutations may produce use [mutationWith].
*
* @param partner The [Berry] being checked as a possible mutation partner.
* @return If a mutation is possible.
*/
fun canMutateWith(partner: Berry) = this.mutationWith(partner) != null
/**
* Query for the possible mutation with the given [partner].
*
* @param partner The [Berry] being mutated with.
* @return The resulting [Berry] if the mutation is possible.
*/
fun mutationWith(partner: Berry): Berry? {
val berryIdentifier = this.mutations[partner.identifier] ?: return null
return Berries.getByIdentifier(berryIdentifier)
}
/**
* Query for a possible partner to mutate into the given [resulting].
*
* @param resulting The [Berry] the mutation should result in.
* @return The [Berry] that mutates with this berry into the given [resulting] if possible.
*/
fun partnerForMutation(resulting: Berry): Berry? {
return this.mutations.firstNotNullOfOrNull { (partner, result) ->
if (result == resulting.identifier)
Berries.getByIdentifier(partner)
else
null
}
}
// A cheat since gson doesn't invoke init block
internal fun validate() {
if (this.baseYield.first < 0 || this.baseYield.last < 0) {
throw IllegalArgumentException("A berry base yield must be a positive range")
}
if (this.growthTime.first < 0 || this.growthTime.last < 0) {
throw IllegalArgumentException("The growth time must be a positive range")
}
if (this.refreshRate.first < 0 || this.refreshRate.last < 0) {
throw IllegalArgumentException("The refresh rate must be a positive range")
}
/*
if (this.lifeCycles.first < 0 || this.lifeCycles.last < 0) {
throw IllegalArgumentException("A berry life cycle must be a positive range")
}
*/
this.growthFactors.forEach { it.validateArguments() }
val maxYield = this.maxYield()
if (this.growthPoints.size < maxYield) {
throw IllegalArgumentException("Anchor points must have enough elements for the max possible yield of $maxYield you've provided ${this.growthPoints.size} points")
}
this.shapedFlower = hashMapOf()
this.shapedFruit = hashMapOf()
this.sproutShape = this.createAndUniteShapes(this.sproutShapeBoxes)
this.matureShape = this.createAndUniteShapes(this.matureShapeBoxes)
}
internal fun encode(buffer: PacketByteBuf) {
buffer.writeIdentifier(this.identifier)
buffer.writeInt(this.baseYield.first)
buffer.writeInt(this.baseYield.last)
buffer.writeEnumSet(favoriteMulches, MulchVariant::class.java)
//buffer.writeInt(this.lifeCycles.first)
//buffer.writeInt(this.lifeCycles.last)
buffer.writeInt(this.growthTime.first)
buffer.writeInt(this.growthTime.last)
buffer.writeInt(this.refreshRate.first)
buffer.writeInt(this.refreshRate.last)
buffer.writeCollection(this.growthPoints.toList()) { writer, value ->
writer.writeDouble(value.position.x)
writer.writeDouble(value.position.y)
writer.writeDouble(value.position.z)
writer.writeDouble(value.rotation.x)
writer.writeDouble(value.rotation.y)
writer.writeDouble(value.rotation.z)
}
buffer.writeBoolean(this.randomizedGrowthPoints)
buffer.writeMap(this.mutations, { writer, key -> writer.writeIdentifier(key) }, { writer, value -> writer.writeIdentifier(value) })
buffer.writeCollection(this.sproutShapeBoxes) { writer, value ->
writer.writeBox(value)
}
buffer.writeCollection(this.matureShapeBoxes) { writer, value ->
writer.writeBox(value)
}
buffer.writeMap(this.flavors, { writer, key -> writer.writeEnumConstant(key) }, { writer, value -> writer.writeInt(value) })
buffer.writeMap(this.tintIndexes, { writer, key -> writer.writeInt(key) }, { writer, value -> writer.writeInt(value.rgb) })
buffer.writeIdentifier(this.flowerModelIdentifier)
buffer.writeIdentifier(this.flowerTexture)
buffer.writeIdentifier(this.fruitModelIdentifier)
buffer.writeIdentifier(this.fruitTexture)
}
/**
* Calculates the bonus yield for the berry tree.
*
* @param world The [World] the tree is present in.
* @param state The [BlockState] of the tree.
* @param pos The [BlockPos] of the tree.
* @return The bonus yield, the growth factors that passed.
*/
private fun bonusYield(world: World, state: BlockState, pos: BlockPos): Pair<Int, Collection<GrowthFactor>> {
var bonus = 0
val passed = arrayListOf<GrowthFactor>()
val entity = world.getBlockEntity(pos) as BerryBlockEntity
val hasBiomeMulch = favoriteMulches.contains(entity.mulchVariant)
this.growthFactors.forEach { factor ->
if (factor.isValid(world, state, pos)) {
bonus += factor.yield()
passed += factor
}
else if (hasBiomeMulch) {
bonus += factor.yield()
}
}
return bonus to passed
}
private fun createAndUniteShapes(boxes: Collection<Box>): VoxelShape {
var shape: VoxelShape? = null
boxes.forEach { box ->
shape = if (shape == null) {
Block.createCuboidShape(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ)
} else {
VoxelShapes.union(shape, Block.createCuboidShape(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ))
}
}
return shape ?: VoxelShapes.fullCube()
}
companion object {
internal fun decode(buffer: PacketByteBuf): Berry {
val identifier = buffer.readIdentifier()
val baseYield = IntRange(buffer.readInt(), buffer.readInt())
val favMulchs = buffer.readEnumSet(MulchVariant::class.java)
//val lifeCycles = IntRange(buffer.readInt(), buffer.readInt())
val growthTime = IntRange(buffer.readInt(), buffer.readInt())
val refreshRate = IntRange(buffer.readInt(), buffer.readInt())
val growthPoints = buffer.readList { reader ->
GrowthPoint(Vec3d(reader.readDouble(), reader.readDouble(), reader.readDouble()), Vec3d(reader.readDouble(), reader.readDouble(), reader.readDouble()))
}.toTypedArray()
val randomizedGrowthPoints = buffer.readBoolean()
val mutations = buffer.readMap({ reader -> reader.readIdentifier() }, { reader -> reader.readIdentifier() })
val sproutShapeBoxes = buffer.readList { it.readBox() }
val matureShapeBoxes = buffer.readList { it.readBox() }
val flavors = buffer.readMap({ reader -> reader.readEnumConstant(Flavor::class.java) }, { reader -> reader.readInt() })
val tintIndexes = buffer.readMap({ reader -> reader.readInt() }, { reader -> Color(reader.readInt()) })
val flowerModelIdentifier = buffer.readIdentifier()
val flowerTexture = buffer.readIdentifier()
val fruitModelIdentifier = buffer.readIdentifier()
val fruitTexture = buffer.readIdentifier()
return Berry(identifier, baseYield, emptyList(), growthTime, refreshRate, favMulchs, emptySet(), emptyList(), growthPoints, randomizedGrowthPoints, mutations, sproutShapeBoxes, matureShapeBoxes, flavors, tintIndexes, flowerModelIdentifier, flowerTexture, fruitModelIdentifier, fruitTexture, 0F)
}
}
}
@@ -0,0 +1,47 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
import com.cobblemon.mod.common.CobblemonBlocks
import com.cobblemon.mod.common.block.BerryBlock
import com.cobblemon.mod.common.world.feature.BerryGroveFeature
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import net.minecraft.registry.entry.RegistryEntry
import net.minecraft.world.biome.Biome
object BerryHelper {
private val CACHE_LOADER = object : CacheLoader<RegistryEntry<Biome>, List<BerryBlock>>() {
override fun load(key: RegistryEntry<Biome>): List<BerryBlock> {
return naturalBerries.filter { berryBlock ->
val berry = berryBlock.berry()
berry?.spawnConditions?.any { it.canSpawn(berry, key) } ?: false
}
}
}
private val naturalBerries = CobblemonBlocks.berries().values.filter {
(it.berry()?.spawnConditions?.size ?: 0) > 0
}
private val validBerryCache: LoadingCache<RegistryEntry<Biome>, List<BerryBlock>> = CacheBuilder.newBuilder()
.maximumSize(4)
.build(CACHE_LOADER)
fun getBerriesForBiome(biome: RegistryEntry<Biome>): List<BerryBlock> {
return validBerryCache.get(biome)
}
fun getNaturallyGeneratingBerries(): List<BerryBlock> {
return naturalBerries
}
}
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
/**
* Represents the different flavors associated with berries and other Pokémon consumables.
* See the [Bulbapedia](https://bulbapedia.bulbagarden.net/wiki/Flavor) article for more information.
*
* @author Licious
* @since November 28th, 2022
*/
enum class Flavor {
SPICY,
DRY,
SWEET,
BITTER,
SOUR
}
@@ -0,0 +1,61 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
import net.minecraft.block.BlockState
import net.minecraft.util.math.BlockPos
import net.minecraft.world.WorldView
/**
* Represents a condition that impacts extra berry yield.
*
* @author Licious
* @since December 2nd, 2022
*/
interface GrowthFactor {
/**
* Validates the arguments contained in this factor, this is invoked during loading.
*
* @throws IllegalArgumentException If an argument isn't valid.
*/
fun validateArguments()
/**
* Checks if this factor should yield a bonus.
*
* @param world The [WorldView] the berry tree is in.
* @param state The [BlockState] of the berry tree.
* @param pos The [BlockPos] of the berry tree.
* @return If the bonus should activate.
*/
fun isValid(world: WorldView, state: BlockState, pos: BlockPos): Boolean
/**
* Resolves the amount of bonus berries to grow if [isValid] was true.
*
* @return The amount of extra berries to grow.
*/
fun yield(): Int
/**
* Returns the minimum possible yield for this factor.
*
* @return The minimum possible yield for this factor.
*/
fun minYield(): Int
/**
* Returns the maximum possible yield for this factor.
*
* @return The maximum possible yield for this factor.
*/
fun maxYield(): Int
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry
import net.minecraft.util.math.Vec3d
/**
* Represents a position in a berry tree where a berry will flower then fruit.
*
* @property position The coordinates of the berry in the tree block.
* @property rotation The degree value for the rotation each axis.
*
* @author Licious
* @since December 19th, 2022
*/
data class GrowthPoint(
val position: Vec3d,
val rotation: Vec3d
)
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry.adapter
import com.cobblemon.mod.common.api.berry.GrowthFactor
import com.cobblemon.mod.common.util.adapters.CobblemonGrowthFactorAdapter
import com.google.gson.JsonDeserializer
import com.google.gson.JsonSerializer
import net.minecraft.util.Identifier
import kotlin.reflect.KClass
/**
* A type adapter for [GrowthFactor]s.
* For the default implementation see [CobblemonGrowthFactorAdapter].
*
* @author Licious
* @since December 2nd, 2022
*/
interface GrowthFactorAdapter : JsonDeserializer<GrowthFactor>, JsonSerializer<GrowthFactor> {
/**
* Register a [GrowthFactor] to be used by this adapter.
*
* @param type The [KClass] of the [GrowthFactor].
* @param identifier The expected [Identifier] in the parsed JSON.
*/
fun register(type: KClass<out GrowthFactor>, identifier: Identifier)
}
@@ -0,0 +1,34 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry.adapter
import com.cobblemon.mod.common.api.berry.GrowthFactor
import com.cobblemon.mod.common.api.berry.spawncondition.BerrySpawnCondition
import com.cobblemon.mod.common.util.adapters.CobblemonBerrySpawnConditionAdapter
import com.google.gson.JsonDeserializer
import com.google.gson.JsonSerializer
import net.minecraft.util.Identifier
import kotlin.reflect.KClass
/**
* A type adapter for [GrowthFactor]s.
* For the default implementation see [CobblemonBerrySpawnConditionAdapter].
*
* @author Apion
* @since August 14, 2023
*/
interface SpawnConditionAdapter : JsonDeserializer<BerrySpawnCondition>, JsonSerializer<BerrySpawnCondition> {
/**
* Register a [BerrySpawnCondition] to be used by this adapter.
*
* @param type The [KClass] of the [BerrySpawnCondition].
* @param identifier The expected [Identifier] in the parsed JSON.
*/
fun register(type: KClass<out BerrySpawnCondition>, identifier: Identifier)
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry.spawncondition
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.registry.entry.RegistryEntry
import net.minecraft.util.math.random.Random
import net.minecraft.world.biome.Biome
class AllBiomeCondition(val minGroveSize: Int, val maxGroveSize: Int) : BerrySpawnCondition{
override fun canSpawn(berry: Berry, biome: RegistryEntry<Biome>): Boolean {
return true
}
override fun getGroveSize(random: Random): Int {
return random.nextBetween(minGroveSize, maxGroveSize)
}
companion object {
val ID = cobblemonResource("all_biome")
}
}
@@ -0,0 +1,20 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry.spawncondition
import com.cobblemon.mod.common.api.berry.Berry
import net.minecraft.registry.entry.RegistryEntry
import net.minecraft.util.math.random.Random
import net.minecraft.world.biome.Biome
interface BerrySpawnCondition {
fun getGroveSize(random: Random): Int
fun canSpawn(berry: Berry, biome: RegistryEntry<Biome>): Boolean
}
@@ -0,0 +1,32 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.berry.spawncondition
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.registry.entry.RegistryEntry
import net.minecraft.util.math.random.Random
import net.minecraft.world.biome.Biome
import kotlin.math.min
class PreferredBiomeCondition(val minGroveSize: Int, val maxGroveSize: Int) : BerrySpawnCondition{
override fun getGroveSize(random: Random): Int {
return random.nextBetween(minGroveSize, maxGroveSize)
}
override fun canSpawn(berry: Berry, biome: RegistryEntry<Biome>): Boolean {
val preferredBiomeTags = berry.preferredBiomeTags
return preferredBiomeTags.any {biome.isIn(it)}
}
companion object {
val ID = cobblemonResource("preferred_biome")
}
}
@@ -0,0 +1,133 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.callback
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.moves.Move
import com.cobblemon.mod.common.api.moves.MoveTemplate
import com.cobblemon.mod.common.api.moves.Moves
import com.cobblemon.mod.common.api.text.text
import com.cobblemon.mod.common.battles.InBattleMove
import com.cobblemon.mod.common.net.IntSize
import com.cobblemon.mod.common.net.messages.client.callback.OpenMoveCallbackPacket
import com.cobblemon.mod.common.util.readSizedInt
import com.cobblemon.mod.common.util.writeSizedInt
import java.util.UUID
import net.minecraft.network.PacketByteBuf
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
/**
* Used for opening move selection screens for players and handling their choice. Currently
* only supports up to 4 moves to select from.
*
* @author Hiroku
* @since July 1st, 2023
*/
object MoveSelectCallbacks {
val callbacks = mutableMapOf<UUID, MoveSelectCallback>()
@JvmOverloads
fun create(
player: ServerPlayerEntity,
title: Text = "".text(),
possibleMoves: List<MoveSelectDTO>,
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (ServerPlayerEntity, index: Int, MoveSelectDTO) -> Unit
) {
val callback = MoveSelectCallback(
shownMoves = possibleMoves,
cancel = cancel,
handler = handler
)
callbacks[player.uuid] = callback
player.sendPacket(OpenMoveCallbackPacket(callback.uuid, title.copy(), possibleMoves))
}
@JvmOverloads
fun create(
player: ServerPlayerEntity,
moves: List<Move>,
canSelect: (Move) -> Boolean = { true },
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (Move) -> Unit
) = create(
player = player,
possibleMoves = moves.map { battleMove -> MoveSelectDTO(battleMove).also { it.enabled = canSelect(battleMove) } },
cancel = cancel,
handler = { _, index, _ -> handler(moves[index]) }
)
@JvmOverloads
fun createBattleSelect(
player: ServerPlayerEntity,
moves: List<InBattleMove>,
canSelect: (InBattleMove) -> Boolean = { true },
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (InBattleMove) -> Unit
) = create(
player = player,
possibleMoves = moves.map { battleMove -> MoveSelectDTO(battleMove).also { it.enabled = canSelect(battleMove) } },
cancel = cancel,
handler = { _, index, _ -> handler(moves[index]) }
)
fun handleCancelled(player: ServerPlayerEntity, uuid: UUID) {
val callback = callbacks[player.uuid] ?: return
if (callback.uuid != uuid) {
return
}
callbacks.remove(player.uuid)
callback.cancel(player)
}
fun handleCallback(player: ServerPlayerEntity, uuid: UUID, index: Int) {
val callback = callbacks[player.uuid] ?: return
callbacks.remove(player.uuid)
if (callback.uuid != uuid) {
Cobblemon.LOGGER.warn("A move select callback ran but with a mismatching UUID from ${player.gameProfile.name}. Hacking attempts?")
} else if (index >= callback.shownMoves.size) {
Cobblemon.LOGGER.warn("${player.gameProfile.name} used move select callback with an index that was out of bounds. Hacking attempts? Tried $index, possible size was ${callback.shownMoves.size}")
} else if (!callback.shownMoves[index].enabled) {
Cobblemon.LOGGER.warn("${player.gameProfile.name} used move select callback with a move that is not enabled. Hacking attempts?")
} else {
callback.handler(player, index, callback.shownMoves[index])
}
}
}
class MoveSelectCallback(
val uuid: UUID = UUID.randomUUID(),
val shownMoves: List<MoveSelectDTO>,
val cancel: (ServerPlayerEntity) -> Unit = {},
val handler: (ServerPlayerEntity, Int, MoveSelectDTO) -> Unit
)
class MoveSelectDTO(val moveTemplate: MoveTemplate, var enabled: Boolean, val pp: Int = -1, val ppMax: Int = -1) {
@JvmOverloads
constructor(move: Move, enabled: Boolean = true): this(moveTemplate = move.template, enabled = enabled, pp = move.currentPp, ppMax = move.maxPp)
@JvmOverloads
constructor(move: InBattleMove, enabled: Boolean = true): this(moveTemplate = Moves.getByNameOrDummy(move.move), enabled = enabled, pp = move.pp, ppMax = move.maxpp)
constructor(buffer: PacketByteBuf): this(
moveTemplate = Moves.getByNameOrDummy(buffer.readString()),
enabled = buffer.readBoolean(),
pp = buffer.readSizedInt(IntSize.BYTE),
ppMax = buffer.readSizedInt(IntSize.BYTE)
)
fun writeToBuffer(buffer: PacketByteBuf) {
buffer.writeString(moveTemplate.name)
buffer.writeBoolean(enabled)
buffer.writeSizedInt(IntSize.BYTE, pp)
buffer.writeSizedInt(IntSize.BYTE, ppMax)
}
}
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.callback
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.moves.Move
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyMoveCallbackPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.lang
import java.util.UUID
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.MutableText
/**
* Used for opening a party select screen for players which routes to move selection when they choose a Pokémon.
* You can do the same sort of thing with combined [MoveSelectCallbacks] and [PartySelectCallbacks] but it isn't
* as smooth an experience.
*
* @author Hiroku
* @since July 29th, 2023
*/
object PartyMoveSelectCallbacks {
val callbacks = mutableMapOf<UUID, PartyMoveSelectCallback>()
@JvmOverloads
fun create(
player: ServerPlayerEntity,
partyTitle: MutableText = lang("ui.party"),
pokemon: List<Pair<PartySelectPokemonDTO, List<MoveSelectDTO>>>,
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (ServerPlayerEntity, pokemonIndex: Int, PartySelectPokemonDTO, moveIndex: Int, MoveSelectDTO) -> Unit
) {
val callback = PartyMoveSelectCallback(
pokemon = pokemon,
cancel = cancel,
handler = handler
)
callbacks[player.uuid] = callback
player.sendPacket(OpenPartyMoveCallbackPacket(callback.uuid, partyTitle, callback.pokemon))
}
@JvmOverloads
fun createFromPokemon(
player: ServerPlayerEntity,
partyTitle: MutableText = lang("ui.party"),
pokemon: List<Pokemon>,
moves: (Pokemon) -> List<Move> = { it.moveSet.getMoves() },
canSelectPokemon: (Pokemon) -> Boolean = { true },
canSelectMove: (Pokemon, Move) -> Boolean = { _, _ -> true },
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (Pokemon, Move) -> Unit
) {
val pokemonList = mutableListOf<Pair<PartySelectPokemonDTO, List<MoveSelectDTO>>>()
for (pk in pokemon) {
val enabled = canSelectPokemon(pk)
val moveList = moves(pk).map { MoveSelectDTO(it, enabled = canSelectMove(pk, it)) }
pokemonList.add(PartySelectPokemonDTO(pk, enabled) to moveList)
}
create(
player = player,
partyTitle = partyTitle,
pokemon = pokemonList,
cancel = cancel,
handler = { _, pkIndex, _, moveIndex, _ ->
handler(pokemon[pkIndex], pokemon[pkIndex].moveSet[moveIndex] ?: return@create)
}
)
}
fun handleCancelled(player: ServerPlayerEntity, uuid: UUID) {
val callback = callbacks[player.uuid] ?: return
if (callback.uuid != uuid) {
return
}
callbacks.remove(player.uuid)
callback.cancel(player)
}
fun handleCallback(player: ServerPlayerEntity, uuid: UUID, pokemonIndex: Int, moveIndex: Int) {
val callback = callbacks[player.uuid] ?: return
callbacks.remove(player.uuid)
if (callback.uuid != uuid) {
return Cobblemon.LOGGER.warn("A party move select callback ran but with a mismatching UUID from ${player.gameProfile.name}. Hacking attempts?")
} else if (pokemonIndex >= callback.pokemon.size) {
return Cobblemon.LOGGER.warn("${player.gameProfile.name} used party move select callback with a Pokémon index that was out of bounds. Hacking attempts? Tried $pokemonIndex, possible size was ${callback.pokemon.size}")
}
val (pokemon, moves) = callback.pokemon[pokemonIndex]
if (!pokemon.enabled) {
return Cobblemon.LOGGER.warn("${player.gameProfile.name} used party move select callback with a Pokémon that is not enabled. Hacking attempts?")
} else if (moveIndex >= moves.size) {
return Cobblemon.LOGGER.warn("${player.gameProfile.name} used party move select callback with a move index that was out of bounds. Hacking attempts? Tried $pokemonIndex-$moveIndex, possible size was ${moves.size}")
}
val move = moves[moveIndex]
if (!move.enabled) {
Cobblemon.LOGGER.warn("${player.gameProfile.name} used party move select callback with a move that is not enabled. Hacking attempts?")
} else {
callback.handler(player, pokemonIndex, pokemon, moveIndex, move)
}
}
}
class PartyMoveSelectCallback(
val uuid: UUID = UUID.randomUUID(),
val pokemon: List<Pair<PartySelectPokemonDTO, List<MoveSelectDTO>>>,
val cancel: (ServerPlayerEntity) -> Unit = {},
val handler: (ServerPlayerEntity, pokemonIndex: Int, PartySelectPokemonDTO, moveIndex: Int, MoveSelectDTO) -> Unit
)
@@ -0,0 +1,160 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.callback
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.CobblemonNetwork.sendPacket
import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonPropertyExtractor
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.net.messages.client.callback.OpenPartyCallbackPacket
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.lang
import java.util.UUID
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtCompound
import net.minecraft.network.PacketByteBuf
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
/**
* Used for opening party Pokémon selection screens for players and handling their choice. Currently
* only supports up to 6 Pokémon to select from.
*
* @author Hiroku
* @since July 1st, 2023
*/
object PartySelectCallbacks {
val callbacks = mutableMapOf<UUID, PartySelectCallback>()
@JvmOverloads
fun create(
player: ServerPlayerEntity,
title: Text = lang("ui.party"),
pokemon: List<PartySelectPokemonDTO>,
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (ServerPlayerEntity, index: Int) -> Unit
) {
val callback = PartySelectCallback(
shownPokemon = pokemon,
cancel = cancel,
handler = handler
)
callbacks[player.uuid] = callback
player.sendPacket(
OpenPartyCallbackPacket(
uuid = callback.uuid,
title = title.copy(),
pokemon = pokemon
)
)
}
@JvmOverloads
fun createBattleSelect(
player: ServerPlayerEntity,
title: Text = lang("ui.party"),
pokemon: List<BattlePokemon>,
canSelect: (BattlePokemon) -> Boolean,
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (BattlePokemon) -> Unit
) = create(
player = player,
title = title,
cancel = cancel,
pokemon = pokemon.map { pk -> PartySelectPokemonDTO(pk.effectedPokemon).also { it.enabled = canSelect(pk) } }
) { _, index -> handler(pokemon[index]) }
@JvmOverloads
fun createFromPokemon(
player: ServerPlayerEntity,
title: Text = lang("ui.party"),
pokemon: List<Pokemon>,
canSelect: (Pokemon) -> Boolean,
cancel: (ServerPlayerEntity) -> Unit = {},
handler: (Pokemon) -> Unit
) = create(
player = player,
title = title,
cancel = cancel,
pokemon = pokemon.map { pk -> PartySelectPokemonDTO(pk).also { it.enabled = canSelect(pk) } }
) { _, index -> handler(pokemon[index]) }
fun handleCancelled(player: ServerPlayerEntity, uuid: UUID) {
val callback = callbacks[player.uuid] ?: return
if (callback.uuid != uuid) {
return
}
callbacks.remove(player.uuid)
callback.cancel(player)
}
fun handleCallback(player: ServerPlayerEntity, uuid: UUID, index: Int) {
val callback = callbacks[player.uuid] ?: return
callbacks.remove(player.uuid)
if (callback.uuid != uuid) {
Cobblemon.LOGGER.warn("A party select callback ran but with a mismatching UUID from ${player.gameProfile.name}. Hacking attempts?")
} else if (index >= callback.shownPokemon.size) {
Cobblemon.LOGGER.warn("${player.gameProfile.name} used party select callback with an out of bounds index. Hacking attempts? Tried $index, Pokémon list size was ${callback.shownPokemon.size}")
} else if (!callback.shownPokemon[index].enabled) {
Cobblemon.LOGGER.warn("${player.gameProfile.name} used party select callback with a Pokémon that is not enabled. Hacking attempts?")
} else {
callback.handler(player, index)
}
}
}
class PartySelectCallback(
val uuid: UUID = UUID.randomUUID(),
val shownPokemon: List<PartySelectPokemonDTO>,
val cancel: (ServerPlayerEntity) -> Unit = {},
val handler: (ServerPlayerEntity, index: Int) -> Unit
)
open class PartySelectPokemonDTO(
val pokemonProperties: PokemonProperties,
val heldItem: ItemStack = ItemStack.EMPTY,
var currentHealth: Int,
var maxHealth: Int,
var enabled: Boolean
) {
@JvmOverloads
constructor(pokemon: Pokemon, enabled: Boolean = true): this(
pokemonProperties = pokemon.createPokemonProperties(
PokemonPropertyExtractor.ASPECTS,
PokemonPropertyExtractor.SPECIES,
PokemonPropertyExtractor.LEVEL,
PokemonPropertyExtractor.NICKNAME,
PokemonPropertyExtractor.POKEBALL,
PokemonPropertyExtractor.STATUS
),
heldItem = pokemon.heldItemNoCopy(),
currentHealth = pokemon.currentHealth,
maxHealth = pokemon.hp,
enabled = enabled
)
constructor(buffer: PacketByteBuf): this(
pokemonProperties = PokemonProperties().loadFromNBT(buffer.readNbt() as NbtCompound),
heldItem = buffer.readItemStack(),
currentHealth = buffer.readInt(),
maxHealth = buffer.readInt(),
enabled = buffer.readBoolean()
)
fun writeToBuffer(buffer: PacketByteBuf) {
buffer.writeNbt(pokemonProperties.saveToNBT())
buffer.writeItemStack(heldItem)
buffer.writeInt(currentHealth)
buffer.writeInt(maxHealth)
buffer.writeBoolean(enabled)
}
}
@@ -13,6 +13,8 @@ import com.cobblemon.mod.common.api.events.battles.BattleFledEvent
import com.cobblemon.mod.common.api.events.battles.BattleStartedPostEvent
import com.cobblemon.mod.common.api.events.battles.BattleStartedPreEvent
import com.cobblemon.mod.common.api.events.battles.BattleVictoryEvent
import com.cobblemon.mod.common.api.events.berry.*
import com.cobblemon.mod.common.api.events.battles.*
import com.cobblemon.mod.common.api.events.drops.LootDroppedEvent
import com.cobblemon.mod.common.api.events.entity.PokemonEntityLoadEvent
import com.cobblemon.mod.common.api.events.entity.PokemonEntitySaveEvent
@@ -20,6 +22,8 @@ import com.cobblemon.mod.common.api.events.entity.PokemonEntitySaveToWorldEvent
import com.cobblemon.mod.common.api.events.entity.SpawnEvent
import com.cobblemon.mod.common.api.events.farming.ApricornHarvestEvent
import com.cobblemon.mod.common.api.events.item.LeftoversCreatedEvent
import com.cobblemon.mod.common.api.events.pokeball.PokeBallCaptureCalculatedEvent
import com.cobblemon.mod.common.api.events.pokeball.PokemonCatchRateEvent
import com.cobblemon.mod.common.api.events.pokeball.ThrownPokeballHitEvent
import com.cobblemon.mod.common.api.events.pokemon.*
import com.cobblemon.mod.common.api.events.pokemon.evolution.EvolutionAcceptedEvent
@@ -59,6 +63,10 @@ object CobblemonEvents {
@JvmField
val THROWN_POKEBALL_HIT = CancelableObservable<ThrownPokeballHitEvent>()
@JvmField
val POKEMON_CATCH_RATE = EventObservable<PokemonCatchRateEvent>()
@JvmField
val POKE_BALL_CAPTURE_CALCULATED = EventObservable<PokeBallCaptureCalculatedEvent>()
@JvmField
val POKEMON_CAPTURED = EventObservable<PokemonCapturedEvent>()
// @JvmField
// val EGG_HATCH = EventObservable<HatchEggEvent>()
@@ -120,6 +128,15 @@ object CobblemonEvents {
@JvmField
val APRICORN_HARVESTED = EventObservable<ApricornHarvestEvent>()
// Berries
@JvmField
val BERRY_HARVEST = EventObservable<BerryHarvestEvent>()
@JvmField
val BERRY_MUTATION_OFFER = EventObservable<BerryMutationOfferEvent>()
@JvmField
val BERRY_MUTATION_RESULT = EventObservable<BerryMutationResultEvent>()
@JvmField
val BERRY_YIELD = EventObservable<BerryYieldCalculationEvent>()
@JvmField
val LEFTOVERS_CREATED = CancelableObservable<LeftoversCreatedEvent>()
@JvmField
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.berry
import com.cobblemon.mod.common.api.berry.Berry
/**
* The base of all Berry related events.
*
* @author Licious
* @since November 28th, 2022
*/
interface BerryEvent {
/**
* The [Berry] related to the event trigger
*/
val berry: Berry
}
@@ -0,0 +1,41 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.berry
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.block.entity.BerryBlockEntity
import net.minecraft.block.BlockState
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* An event fired when [BerryBlockEntity.harvest] is invoked.
*
* @property berry The [Berry] the tree is attached to.
* @property player The [ServerPlayerEntity] harvesting the tree.
* @property world The [World] the tree is in.
* @property pos The [BlockPos] of the tree.
* @property state The [BlockState] of the tree.
* @property blockEntity The backing [BerryBlockEntity]-
* @property drops A collection of [ItemStack]s produced by this harvest.
*
* @author Licious
* @since November 28th, 2022
*/
data class BerryHarvestEvent(
override val berry: Berry,
val player: ServerPlayerEntity,
val world: World,
val pos: BlockPos,
val state: BlockState,
val blockEntity: BerryBlockEntity,
val drops: MutableList<ItemStack>
) : BerryEvent
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.berry
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.block.BerryBlock
import net.minecraft.block.BlockState
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* The event fired when [BerryBlock.grow] is invoked and the tree passes to [BerryBlock.MATURE_AGE].
* This allows you to modify the possible mutations for the tree, for the event that decides which of these mutations is used see [BerryMutationResultEvent].
*
* @property world The [World] the berry tree is in.
* @property state The [BlockState] of the berry tree.
* @property pos The [BlockPos] of the berry tree.
* @property mutations The possible [Berry] mutations.
*
* @author Licious
* @since January 19th, 2022
*/
data class BerryMutationOfferEvent(
override val berry: Berry,
val world: World,
val state: BlockState,
val pos: BlockPos,
val mutations: MutableSet<Berry>
) : BerryEvent
@@ -0,0 +1,37 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.berry
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.block.BerryBlock
import net.minecraft.block.BlockState
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* The event fired when [BerryBlock.grow] is invoked and the tree passes to [BerryBlock.MATURE_AGE].
* This allows you to modify the possible mutations for the tree, for the event that decides which of these mutations is used see [BerryMutationResultEvent].
*
* @property world The [World] the berry tree is in.
* @property state The [BlockState] of the berry tree.
* @property pos The [BlockPos] of the berry tree.
* @property mutations The possible [Berry] mutations.
* @property pickedMutation The [Berry] chosen to mutate into, if null the mutation will not occur.
*
* @author Licious
* @since January 19th, 2022
*/
data class BerryMutationResultEvent(
override val berry: Berry,
val world: World,
val state: BlockState,
val pos: BlockPos,
val mutations: Set<Berry>,
var pickedMutation: Berry?
) : BerryEvent
@@ -0,0 +1,58 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.berry
import com.cobblemon.mod.common.api.berry.Berry
import com.cobblemon.mod.common.api.berry.GrowthFactor
import net.minecraft.block.BlockState
import net.minecraft.entity.LivingEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* The event fired when [Berry.calculateYield] is invoked.
*
* @property world The [World] the berry tree is in.
* @property state The [BlockState] of the berry tree.
* @property pos The [BlockPos] of the berry tree.
* @property placer The [LivingEntity] triggering the calculation.
* @property yield The current yield of berries.
* @property passedGrowthFactors The [Berry.growthFactors] where [GrowthFactor.isValid] was true.
*
* @author Licious
* @since November 28th, 2022
*/
class BerryYieldCalculationEvent(
override val berry: Berry,
val world: World,
val state: BlockState,
val pos: BlockPos,
val placer: LivingEntity?,
yield: Int,
val passedGrowthFactors: Collection<GrowthFactor>
) : BerryEvent {
/**
* The amount of berries this tree will yield.
*
* @throws IllegalArgumentException If a new value exceeds [Berry.maxYield] or be lesser than 0.
*/
var yield: Int = yield
set(value) {
val max = this.berry.maxYield()
if (value > max) {
throw IllegalArgumentException("Cannot set the berry yield for ${this.berry.identifier} above $max")
}
if (value < 0) {
throw IllegalArgumentException("A berry tree cannot yield a negative amount of berries")
}
field = value
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.pokeball
import com.cobblemon.mod.common.api.pokeball.catching.CaptureContext
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import net.minecraft.entity.LivingEntity
import net.minecraft.server.network.ServerPlayerEntity
/**
* Event fired when a Poké Ball has completed its capture calculation and is about to begin shaking
* or breaking free. The result of the capture can be changed by replacing [captureResult].
*
* @author Hiroku
* @since August 20th, 2023
*/
class PokeBallCaptureCalculatedEvent(
val thrower: LivingEntity,
val pokemonEntity: PokemonEntity,
val pokeBallEntity: EmptyPokeBallEntity,
var captureResult: CaptureContext
) {
fun ifPlayer(action: PokeBallCaptureCalculatedEvent.(player: ServerPlayerEntity) -> Unit) {
if (thrower is ServerPlayerEntity) {
action(this, thrower)
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.events.pokeball
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import net.minecraft.entity.LivingEntity
/**
* Event fired when a capture calculator is accessing a Pokémon's catch rate. The [catchRate] property can
* be changed to adjust the rate.
*
* If you want to prevent a Pokémon from being caught, you should be handling the [PokeBallCaptureCalculatedEvent]
* event instead.
*
* @author Hiroku
* @since August 20th, 2023
*/
class PokemonCatchRateEvent(
val thrower: LivingEntity,
val pokeBallEntity: EmptyPokeBallEntity,
val pokemonEntity: PokemonEntity,
var catchRate: Float
)
@@ -8,10 +8,12 @@
package com.cobblemon.mod.common.api.events.pokemon
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.server.network.ServerPlayerEntity
data class PokemonCapturedEvent (
val pokemon: Pokemon,
val player: ServerPlayerEntity
val player: ServerPlayerEntity,
val pokeBallEntity: EmptyPokeBallEntity
)
@@ -11,12 +11,13 @@ package com.cobblemon.mod.common.api.events.world
import com.cobblemon.mod.common.api.events.Cancelable
import com.cobblemon.mod.common.block.BigRootBlock
import com.cobblemon.mod.common.block.EnergyRootBlock
import net.minecraft.block.BlockState
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
/**
* Event fired when a [BigRootBlock] attempts to spread. The event includes the original root position
* as well as the position of the new root. [isEnergyRoot] controls whether the new root will be an
* as well as the position of the new root. [resultingSpread] controls whether the new root will be an
* [EnergyRootBlock]. The new root position and whether it is an energy root is mutable.
*
* Cancelling this event will prevent propagation from occurring.
@@ -28,5 +29,5 @@ class BigRootPropagatedEvent(
val world: ServerWorld,
val pos: BlockPos,
var newRootPosition: BlockPos,
var isEnergyRoot: Boolean
var resultingSpread: BlockState
) : Cancelable()
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.interaction
import net.minecraft.entity.Entity
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
/**
* An interaction that will affect an [Entity].
* These need to be triggered.
*
* @param T The type of the [Entity] this interaction will affect.
*/
interface EntityInteraction<T : Entity> {
/**
* Fired when a [ServerPlayerEntity] interacts with the target entity.
*
* @param player The [ServerPlayerEntity] interacting with the [entity].
* @param entity The [Entity] of type [T] being interacted.
* @param stack The [ItemStack] used in this interaction.
* @return true if the interaction was successful and no further interactions should be processed
*/
fun onInteraction(player: ServerPlayerEntity, entity: T, stack: ItemStack): Boolean
/**
* Decreases the stack size by a given amount.
* The stack size should be validated beforehand.
* If the [player] is in creative mode the decrement won't be performed.
*
* @param player The [ServerPlayerEntity] that caused the interaction, this is used to check for creative mode.
* @param stack The [ItemStack] being mutated.
* @param amount The amount to deduct from the stack, default is 1.
*/
fun consumeItem(player: ServerPlayerEntity, stack: ItemStack, amount: Int = 1) {
if (!player.isCreative) {
stack.decrement(amount)
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.interaction
import com.google.gson.JsonDeserializer
import com.google.gson.JsonSerializer
import kotlin.reflect.KClass
import net.minecraft.util.Identifier
/**
* A type adapter for [EntityInteraction]s.
* For the default implementation with Pokémon entities see [CobblemonPokemonEntityInteractionTypeAdapter].
*
* @param T The type of [EntityInteraction].
*
* @author Licious
* @since November 30th, 2022
*/
interface EntityInteractionTypeAdapter<T : EntityInteraction<*>> : JsonDeserializer<T>, JsonSerializer<T> {
fun registerInteraction(identifier: Identifier, type: KClass<out T>)
}
@@ -6,24 +6,26 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.item.interactive
package com.cobblemon.mod.common.api.interaction
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.item.interactive.PokemonInteractiveItem.Ownership
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.sound.SoundEvent
/**
* An [InteractiveItem] targeting [PokemonEntity]s.
*
* @param accepted The [Ownership] variants for this interaction to fire [PokemonInteractiveItem.processInteraction].
* An [EntityInteraction] targeting [PokemonEntity]s.
* These need to be manually triggered if not implemented by an item.
*/
interface PokemonInteractiveItem : InteractiveItem<PokemonEntity> {
interface PokemonEntityInteraction : EntityInteraction<PokemonEntity> {
/**
* The accepted [Ownership] for the Pokémon entity in order for the interaction to fire.
*/
val accepted: Set<Ownership>
fun getSound(): SoundEvent? = CobblemonSounds.ITEM_USE
val sound: SoundEvent?
get() = CobblemonSounds.ITEM_USE
override fun onInteraction(player: ServerPlayerEntity, entity: PokemonEntity, stack: ItemStack): Boolean {
val pokemon = entity.pokemon
@@ -41,30 +43,15 @@ interface PokemonInteractiveItem : InteractiveItem<PokemonEntity> {
}
/**
* Fired after [InteractiveItem.onInteraction] the [Ownership] is checked if contained in [accepted].
* Fired after [EntityInteraction.onInteraction] the [Ownership] is checked if contained in [accepted].
*
* @param player The [ServerPlayerEntity] interacting with the [entity].
* @param entity The [PokemonEntity] being interacted with.
* @param stack The [ItemStack] used in this interaction. [ItemStack.getItem] will always be of the same type as this [InteractiveItem].
* @param stack The [ItemStack] used in this interaction.
* @return true if the interaction was successful and no further interactions should be processed.
*/
fun processInteraction(player: ServerPlayerEntity, entity: PokemonEntity, stack: ItemStack): Boolean
/**
* Decreases the stack size by a given amount.
* The stack size should be validated beforehand.
* If the [player] is in creative mode the decrement won't be performed.
*
* @param player The [ServerPlayerEntity] that caused the interaction, this is used to check for creative mode.
* @param stack The [ItemStack] being mutated.
* @param amount The amount to deduct from the stack, default is 1.
*/
fun consumeItem(player: ServerPlayerEntity, stack: ItemStack, amount: Int = 1) {
if (!player.isCreative) {
stack.decrement(amount)
}
}
/**
* Represents the ownership status of a Pokemon relative to a Player.
*
@@ -0,0 +1,149 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.item
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.callback.MoveSelectCallbacks
import com.cobblemon.mod.common.api.callback.PartyMoveSelectCallbacks
import com.cobblemon.mod.common.api.moves.Move
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.battles.BagItemActionResponse
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.item.battle.BagItem
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getBattleState
import com.cobblemon.mod.common.util.isHeld
import com.cobblemon.mod.common.util.isLookingAt
import com.cobblemon.mod.common.util.party
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.TypedActionResult
import net.minecraft.util.math.Box
/**
* Interface to make it easier to define items that will, upon use, prompt you to
* select a Pokémon and move for the item to be used on. This can be by interacting
* with the Pokémon directly (which will skip the Pokémon selection screen) or by
* interacting with air which will first show a Pokémon selection screen.
*
* @author Hiroku
* @since July 29th, 2023
*/
interface PokemonAndMoveSelectingItem {
fun use(player: ServerPlayerEntity, stack: ItemStack): TypedActionResult<ItemStack>? {
val entity = player.world
.getOtherEntities(player, Box.of(player.pos, 16.0, 16.0, 16.0))
.filter { player.isLookingAt(it, stepDistance = 0.1F) }
.minByOrNull { it.distanceTo(player) } as? PokemonEntity?
player.getBattleState()?.let { (_, actor) ->
if (bagItem == null) {
return TypedActionResult.fail(stack)
}
if (!actor.canFitForcedAction()) {
player.sendMessage(battleLang("bagitem.cannot").red())
return TypedActionResult.fail(stack)
}
val battlePokemon = actor.pokemonList.find { it.effectedPokemon == entity?.pokemon }
if (entity == null) {
return interactGeneralBattle(player, stack, actor)
} else if (battlePokemon != null) {
return interactWithSpecificBattle(player, stack, battlePokemon)
}
} ?: run {
if (entity != null) {
val pokemon = entity.pokemon
if (entity.ownerUuid == player.uuid) {
return interactWithSpecific(player, stack, pokemon)
} else {
return TypedActionResult.fail(stack)
}
} else {
return interactGeneral(player, stack)
}
}
return null
}
val bagItem: BagItem?
fun applyToPokemon(player: ServerPlayerEntity, stack: ItemStack, pokemon: Pokemon, move: Move)
fun applyToBattlePokemon(player: ServerPlayerEntity, stack: ItemStack, battlePokemon: BattlePokemon, move: Move) {
val battle = battlePokemon.actor.battle
val bagItem = bagItem
if (!battlePokemon.actor.canFitForcedAction()) {
player.sendMessage(battleLang("bagitem.cannot").red())
} else if (!bagItem!!.canUse(battle, battlePokemon)) {
player.sendMessage(battleLang("bagitem.invalid").red())
} else {
battlePokemon.actor.forceChoose(BagItemActionResponse(bagItem, battlePokemon, move.template.name))
if (!player.isCreative) {
stack.decrement(1)
}
}
}
fun canUseOnPokemon(pokemon: Pokemon): Boolean
fun canUseOnBattlePokemon(battlePokemon: BattlePokemon): Boolean = bagItem!!.canUse(battlePokemon.actor.battle, battlePokemon)
fun canUseOnMove(pokemon: Pokemon, move: Move): Boolean = canUseOnMove(move)
fun canUseOnMove(move: Move): Boolean
fun interactWithSpecific(player: ServerPlayerEntity, stack: ItemStack, pokemon: Pokemon): TypedActionResult<ItemStack>? {
MoveSelectCallbacks.create(
player = player,
moves = pokemon.moveSet.toList(),
canSelect = ::canUseOnMove,
handler = { move -> if (stack.isHeld(player)) applyToPokemon(player, stack, pokemon, move) }
)
return TypedActionResult.success(stack)
}
fun interactWithSpecificBattle(player: ServerPlayerEntity, stack: ItemStack, battlePokemon: BattlePokemon): TypedActionResult<ItemStack>? {
return if (canUseOnBattlePokemon(battlePokemon)) {
MoveSelectCallbacks.create(
player = player,
moves = battlePokemon.moveSet.getMoves(),
canSelect = ::canUseOnMove,
handler = { applyToBattlePokemon(player, stack, battlePokemon, it) }
)
TypedActionResult.success(stack)
} else {
player.sendMessage(battleLang("bagitem.invalid").red())
TypedActionResult.fail(stack)
}
}
fun interactGeneral(player: ServerPlayerEntity, stack: ItemStack): TypedActionResult<ItemStack>? {
PartyMoveSelectCallbacks.createFromPokemon(
player = player,
pokemon = player.party().toList(),
canSelectPokemon = ::canUseOnPokemon,
canSelectMove = ::canUseOnMove,
handler = { pk, mv -> if (stack.isHeld(player)) applyToPokemon(player, stack, pk, mv) }
)
return TypedActionResult.success(stack)
}
fun interactGeneralBattle(player: ServerPlayerEntity, stack: ItemStack, actor: BattleActor): TypedActionResult<ItemStack>? {
PartyMoveSelectCallbacks.createFromPokemon(
player = player,
pokemon = actor.pokemonList.map { it.effectedPokemon },
moves = { pk -> actor.pokemonList.find { it.effectedPokemon == pk }!!.moveSet.getMoves() },
canSelectPokemon = { pk -> canUseOnBattlePokemon(actor.pokemonList.find { it.effectedPokemon == pk }!!) },
canSelectMove = ::canUseOnMove,
handler = { pk, mv -> applyToBattlePokemon(player, stack, actor.pokemonList.find { it.effectedPokemon == pk }!!, mv) }
)
return TypedActionResult.success(stack)
}
}
@@ -0,0 +1,141 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.item
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.callback.PartySelectCallbacks
import com.cobblemon.mod.common.api.text.red
import com.cobblemon.mod.common.battles.BagItemActionResponse
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.item.battle.BagItem
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getBattleState
import com.cobblemon.mod.common.util.isHeld
import com.cobblemon.mod.common.util.isLookingAt
import com.cobblemon.mod.common.util.party
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.TypedActionResult
import net.minecraft.util.math.Box
/**
* Interface to make it easier to define items that will, upon use, prompt you to
* select a Pokémon for it to be used on. This can be by interacting with the Pokémon
* directly (which will skip the Pokémon selection screen) or by interacting with air
* which will first show a Pokémon selection screen.
*
* Works for battle items too.
*
* @author Hiroku
* @since July 29th, 2023
*/
interface PokemonSelectingItem {
fun use(player: ServerPlayerEntity, stack: ItemStack): TypedActionResult<ItemStack> {
val entity = player.world
.getOtherEntities(player, Box.of(player.pos, 16.0, 16.0, 16.0))
.filter { player.isLookingAt(it, stepDistance = 0.1F) }
.minByOrNull { it.distanceTo(player) } as? PokemonEntity?
player.getBattleState()?.let { (_, actor) ->
if (bagItem == null) return TypedActionResult.fail(stack)
val battlePokemon = actor.pokemonList.find { it.effectedPokemon == entity?.pokemon }
if (!actor.canFitForcedAction()) {
player.sendMessage(battleLang("bagitem.cannot").red())
return TypedActionResult.fail(stack)
}
if (entity == null) {
return interactGeneralBattle(player, stack, actor)
} else if (battlePokemon != null) {
return interactWithSpecificBattle(player, stack, battlePokemon)
}
} ?: run {
if (entity != null) {
val pokemon = entity.pokemon
if (entity.ownerUuid == player.uuid) {
return applyToPokemon(player, stack, pokemon) ?: TypedActionResult.pass(stack)
} else {
return TypedActionResult.fail(stack)
}
} else {
return interactGeneral(player, stack)
}
}
return TypedActionResult.pass(stack)
}
val bagItem: BagItem?
fun applyToPokemon(player: ServerPlayerEntity, stack: ItemStack, pokemon: Pokemon): TypedActionResult<ItemStack>?
fun applyToBattlePokemon(player: ServerPlayerEntity, stack: ItemStack, battlePokemon: BattlePokemon) {
val battle = battlePokemon.actor.battle
val bagItem = bagItem
if (!battlePokemon.actor.canFitForcedAction()) {
player.sendMessage(battleLang("bagitem.cannot").red())
} else if (!bagItem!!.canUse(battle, battlePokemon)) {
player.sendMessage(battleLang("bagitem.invalid").red())
} else {
battlePokemon.actor.forceChoose(BagItemActionResponse(bagItem, battlePokemon))
if (!player.isCreative) {
stack.decrement(1)
}
}
}
fun canUseOnPokemon(pokemon: Pokemon): Boolean
fun canUseOnBattlePokemon(battlePokemon: BattlePokemon): Boolean = bagItem!!.canUse(battlePokemon.actor.battle, battlePokemon)
fun interactWithSpecificBattle(player: ServerPlayerEntity, stack: ItemStack, battlePokemon: BattlePokemon): TypedActionResult<ItemStack> {
return if (canUseOnBattlePokemon(battlePokemon)) {
applyToBattlePokemon(player, stack, battlePokemon)
TypedActionResult.success(stack)
} else {
player.sendMessage(battleLang("bagitem.invalid").red())
TypedActionResult.fail(stack)
}
}
fun interactGeneral(player: ServerPlayerEntity, stack: ItemStack): TypedActionResult<ItemStack> {
val party = player.party().toList()
if (party.isEmpty()) {
return TypedActionResult.fail(stack)
}
PartySelectCallbacks.createFromPokemon(
player = player,
pokemon = party,
canSelect = ::canUseOnPokemon,
handler = { pk ->
if (stack.isHeld(player)) {
applyToPokemon(player, stack, pk)
if (!player.isCreative) {
stack.decrement(1)
}
}
}
)
return TypedActionResult.success(stack)
}
fun interactGeneralBattle(player: ServerPlayerEntity, stack: ItemStack, actor: BattleActor): TypedActionResult<ItemStack> {
PartySelectCallbacks.createBattleSelect(
player = player,
pokemon = actor.pokemonList,
canSelect = { pk -> canUseOnBattlePokemon(actor.pokemonList.find { it.effectedPokemon == pk.effectedPokemon }!!) },
handler = { pk -> applyToBattlePokemon(player, stack, actor.pokemonList.find { it.effectedPokemon == pk.effectedPokemon }!!) }
)
return TypedActionResult.success(stack)
}
}
@@ -16,6 +16,7 @@ import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.readSizedInt
import com.cobblemon.mod.common.util.writeSizedInt
import com.google.gson.JsonObject
import kotlin.math.ceil
import kotlin.properties.Delegates
import net.minecraft.nbt.NbtCompound
import net.minecraft.network.PacketByteBuf
@@ -29,17 +30,31 @@ open class Move(
currentPp: Int,
raisedPpStages: Int = 0
) {
private var emit = true
val observable = SimpleObservable<Move>()
var currentPp: Int by Delegates.observable(currentPp) { _, oldValue, newValue ->
if (oldValue != newValue) {
observable.emit(this)
update()
}
}
var raisedPpStages: Int by Delegates.observable(raisedPpStages) { _, oldValue, newValue ->
if (oldValue != newValue) {
update()
}
}
fun doThenUpdate(action: () -> Unit) {
val oldEmit = emit
emit = false
action()
emit = oldEmit
update()
}
fun update() {
if (emit) {
observable.emit(this)
}
}
@@ -71,6 +86,20 @@ open class Move(
val maxPp: Int
get() = template.pp + raisedPpStages * template.pp / 5
/** Raises the max PP and rescales the current PP value. Returns false if it was already maxed out. */
fun raiseMaxPP(amount: Int): Boolean {
val oldPp = maxPp
doThenUpdate {
val ppRatio = currentPp / maxPp.toFloat()
raisedPpStages += amount
if (raisedPpStages > 3) {
raisedPpStages = 3
}
currentPp = ceil(ppRatio * maxPp).toInt()
}
return oldPp != maxPp
}
fun saveToNBT(nbt: NbtCompound): NbtCompound {
nbt.putString(DataKeys.POKEMON_MOVESET_MOVENAME, name)
nbt.putInt(DataKeys.POKEMON_MOVESET_MOVEPP, currentPp)
@@ -128,6 +128,7 @@ class MoveSet : Iterable<Move> {
observable.emit(this)
}
}
fun doWithoutEmitting(action: () -> Unit) {
val previousEmit = emit
emit = false
@@ -38,7 +38,7 @@ object Moves : DataRegistry {
override fun reload(manager: ResourceManager) {
this.allMoves.clear()
this.idMapping.clear()
val movesJson = ShowdownService.get().getMoves()
val movesJson = ShowdownService.service.getMoves()
for (i in 0 until movesJson.size()) {
val jsMove = movesJson[i].asJsonObject
val id = jsMove.get("id").asString
@@ -0,0 +1,49 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.mulch
import com.cobblemon.mod.common.CobblemonItems
import com.cobblemon.mod.common.item.MulchItem
import net.minecraft.util.StringIdentifiable
import java.time.Duration
/**
* Represents the different types of Mulch implemented in the mod.
*
*/
enum class MulchVariant(val isBiomeMulch: Boolean = true, val duration: Int = 0) : StringIdentifiable {
COARSE,
GROWTH(false, 3),
HUMID,
LOAMY,
PEAT,
RICH(false, 3),
SANDY,
SURPRISE(false, 3);
/**
* Resolves the item version of the Mulch.
*
* @return The [MulchItem] equivalent.
*/
fun item(): MulchItem = when (this) {
COARSE -> CobblemonItems.COARSE_MULCH
GROWTH -> CobblemonItems.GROWTH_MULCH
HUMID -> CobblemonItems.HUMID_MULCH
LOAMY -> CobblemonItems.LOAMY_MULCH
PEAT -> CobblemonItems.PEAT_MULCH
RICH -> CobblemonItems.RICH_MULCH
SANDY -> CobblemonItems.SANDY_MULCH
SURPRISE -> CobblemonItems.SURPRISE_MULCH
}
override fun asString(): String {
return name.lowercase()
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.mulch
import net.minecraft.block.BlockState
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.random.Random
/**
* Represents something that can have mulch applied to it.
* Typically, this will be a block implementation.
*/
interface Mulchable {
/**
* Checks if mulch can be applied to a specific spot in the world.
*
* @param world The affected [ServerWorld].
* @param pos The [BlockPos] being checked.
* @param state The [BlockState] of the block at the [pos] in the [world].
* @param variant The [MulchVariant] being applied.
* @return If the application is possible.
*/
fun canHaveMulchApplied(world: ServerWorld, pos: BlockPos, state: BlockState, variant: MulchVariant): Boolean
/**
* Applies the mulch to the specified spot.
* This is expected to be invoked if [canHaveMulchApplied] is true.
*
* @param world The affected [ServerWorld].
* @param random The [Random] instance being used in the interaction.
* @param pos The [BlockPos] being checked.
* @param state The [BlockState] of the block at the [pos] in the [world].
* @param variant The [MulchVariant] being applied.
*/
fun applyMulch(world: ServerWorld, random: Random, pos: BlockPos, state: BlockState, variant: MulchVariant)
}
@@ -8,9 +8,12 @@
package com.cobblemon.mod.common.api.pokeball.catching.calculators
import com.cobblemon.mod.common.api.events.CobblemonEvents
import com.cobblemon.mod.common.api.events.pokeball.PokemonCatchRateEvent
import com.cobblemon.mod.common.api.pokeball.catching.CaptureContext
import com.cobblemon.mod.common.entity.pokeball.EmptyPokeBallEntity
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokeball.PokeBall
import com.cobblemon.mod.common.pokemon.Pokemon
import net.minecraft.entity.LivingEntity
/**
@@ -24,7 +27,6 @@ import net.minecraft.entity.LivingEntity
* @since November 30, 2021
*/
interface CaptureCalculator {
/**
* The literal ID of this calculator.
* Used when registering the calculator to the registry in order to be used by the game rule.
@@ -37,10 +39,22 @@ interface CaptureCalculator {
* Processes a capture attempt with the given params.
*
* @param thrower The [LivingEntity] that threw the [PokeBall].
* @param pokeBall The [PokeBall] used.
* @param target The target [Pokemon] attempting to be captured.
* @return
* @param pokeBallEntity The [EmptyPokeBallEntity] used.
* @param target The target [PokemonEntity] attempting to be captured.
* @return a [CaptureContext] that is the result of the capture attempt.
*/
fun processCapture(thrower: LivingEntity, pokeBall: PokeBall, target: Pokemon) : CaptureContext
fun processCapture(thrower: LivingEntity, pokeBallEntity: EmptyPokeBallEntity, target: PokemonEntity) : CaptureContext
fun getCatchRate(thrower: LivingEntity, pokeBallEntity: EmptyPokeBallEntity, target: PokemonEntity, catchRate: Float): Float {
val event = PokemonCatchRateEvent(
thrower = thrower,
pokemonEntity = target,
pokeBallEntity = pokeBallEntity,
catchRate = catchRate
)
CobblemonEvents.POKEMON_CATCH_RATE.post(event)
return event.catchRate
}
}
@@ -8,7 +8,7 @@
package com.cobblemon.mod.common.api.pokemon
import com.cobblemon.mod.common.api.item.Flavor
import com.cobblemon.mod.common.api.berry.Flavor
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.pokemon.Nature
import com.cobblemon.mod.common.util.cobblemonResource
@@ -13,9 +13,12 @@ import com.cobblemon.mod.common.api.abilities.Abilities
import com.cobblemon.mod.common.api.pokeball.PokeBalls
import com.cobblemon.mod.common.api.pokemon.aspect.AspectProvider
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.api.properties.CustomPokemonProperty
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.*
import com.cobblemon.mod.common.pokemon.status.PersistentStatus
import com.cobblemon.mod.common.pokemon.status.PersistentStatusContainer
import com.cobblemon.mod.common.util.DataKeys
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.isInt
@@ -81,12 +84,13 @@ open class PokemonProperties {
props.pokeball = parseIdentifierOfRegistry(keyPairs, listOf("pokeball")) { identifier -> PokeBalls.getPokeBall(identifier)?.name?.toString() }
props.nature = parseIdentifierOfRegistry(keyPairs, listOf("nature")) { identifier -> Natures.getNature(identifier)?.name?.toString() }
props.ability = parseStringOfRegistry(keyPairs, listOf("ability")) { Abilities.get(it)?.name }
props.status = parseStringOfRegistry(keyPairs, listOf("status")) { (Statuses.getStatus(it) ?: Statuses.getStatus(it.asIdentifierDefaultingNamespace()))?.showdownName }
props.nickname = parseText(keyPairs, listOf("nickname", "nick"))
val maybeIVs = IVs()
val maybeEVs = EVs()
Stats.PERMANENT.forEach{ stat ->
val statName = stat.displayName.string.lowercase()
val statName = stat.toString().lowercase()
parseIntProperty(keyPairs, listOf("${statName}_iv"))?.coerceIn(0, IVs.MAX_VALUE)?.let { maybeIVs[stat] = it }
parseIntProperty(keyPairs, listOf("${statName}_ev"))?.coerceIn(0, EVs.MAX_STAT_VALUE)?.let { maybeEVs[stat] = it }
}
@@ -241,6 +245,7 @@ open class PokemonProperties {
var nature: String? = null
var ability: String? = null
var aspects: Set<String> = emptySet()
var status: String? = null
var ivs: IVs? = null
var evs: EVs? = null
@@ -278,15 +283,16 @@ open class PokemonProperties {
pokeball?.let { PokeBalls.getPokeBall(it.asIdentifierDefaultingNamespace())?.let { pokeball -> pokemon.caughtBall = pokeball } }
nature?.let { Natures.getNature(it.asIdentifierDefaultingNamespace())?.let { nature -> pokemon.nature = nature } }
ability?.let { Abilities.getOrException(it).create(true).let { ability -> pokemon.ability = ability } }
status?.let { Statuses.getStatus(it)?.let { pokemon.applyStatus(it as PersistentStatus) } }
customProperties.forEach { it.apply(pokemon) }
ivs?.let { ivs ->
ivs.forEach { stat ->
pokemon.ivs[stat.key] = stat.value
pokemon.setIV(stat.key, stat.value)
}
}
evs?.let { evs ->
evs.forEach { stat ->
pokemon.evs[stat.key] = stat.value
pokemon.setEV(stat.key, stat.value)
}
}
}
@@ -312,15 +318,16 @@ open class PokemonProperties {
pokeball?.let { PokeBalls.getPokeBall(it.asIdentifierDefaultingNamespace())?.let { pokeball -> pokemonEntity.pokemon.caughtBall = pokeball } }
nature?.let { Natures.getNature(it.asIdentifierDefaultingNamespace())?.let { nature -> pokemonEntity.pokemon.nature = nature } }
ability?.let { Abilities.getOrException(it).create(true).let { ability -> pokemonEntity.pokemon.ability = ability } }
status?.let { Statuses.getStatus(it)?.let { pokemonEntity.pokemon.applyStatus(it as PersistentStatus) } }
customProperties.forEach { it.apply(pokemonEntity) }
ivs?.let { ivs ->
ivs.forEach { stat ->
pokemonEntity.pokemon.ivs[stat.key] = stat.value
pokemonEntity.pokemon.setIV(stat.key, stat.value)
}
}
evs?.let { evs ->
evs.forEach { stat ->
pokemonEntity.pokemon.evs[stat.key] = stat.value
pokemonEntity.pokemon.setEV(stat.key, stat.value)
}
}
}
@@ -348,7 +355,8 @@ open class PokemonProperties {
friendship?.takeIf { it != pokemon.friendship }?.let { return false }
pokeball?.takeIf { it != pokemon.caughtBall.name.toString() }?.let { return false }
nature?.takeIf { it != pokemon.nature.name.toString() }?.let { return false }
ability?.takeIf { it != pokemon.ability.name }?. let { return false }
ability?.takeIf { it != pokemon.ability.name }?.let { return false }
status?.takeIf { it != pokemon.status?.status?.showdownName }?.let { return false }
ivs?.forEach{ stat ->
if (stat.value != pokemon.ivs[stat.key]) { return false }
}
@@ -379,7 +387,8 @@ open class PokemonProperties {
friendship?.takeIf { it != pokemonEntity.pokemon.friendship }?.let { return false }
pokeball?.takeIf { it != pokemonEntity.pokemon.caughtBall.name.toString() }?.let { return false }
nature?.takeIf { it != pokemonEntity.pokemon.nature.name.toString() }?.let { return false }
ability?.takeIf { it != pokemonEntity.pokemon.ability.name }?. let { return false }
ability?.takeIf { it != pokemonEntity.pokemon.ability.name }?.let { return false }
status?.takeIf { it != pokemonEntity.pokemon.status?.status?.showdownName }?.let { return false }
ivs?.forEach{ stat ->
if (stat.value != pokemonEntity.pokemon.ivs[stat.key]) { return false }
}
@@ -410,7 +419,8 @@ open class PokemonProperties {
friendship?.takeIf { it != properties.friendship }?.let { return false }
pokeball?.takeIf { it != properties.pokeball }?.let { return false }
nature?.takeIf { it != properties.nature }?.let { return false }
ability?.takeIf { it != properties.ability }?. let { return false }
ability?.takeIf { it != properties.ability }?.let { return false }
status?.takeIf { it != properties.status }?.let { return false }
ivs?.let{ ivs ->
ivs.forEach{ stat ->
//If the potential subset has IV and the main set does not then it cant be a subset
@@ -460,6 +470,7 @@ open class PokemonProperties {
pokeball?.let { nbt.putString(DataKeys.POKEMON_CAUGHT_BALL, it) }
nature?.let { nbt.putString(DataKeys.POKEMON_NATURE, it) }
ability?.let { nbt.putString(DataKeys.POKEMON_ABILITY, it) }
status?.let { nbt.putString(DataKeys.POKEMON_STATUS_NAME, it) }
ivs?.let { nbt.put(DataKeys.POKEMON_IVS, it.saveToNBT(NbtCompound())) }
evs?.let { nbt.put(DataKeys.POKEMON_EVS, it.saveToNBT(NbtCompound())) }
val custom = NbtList()
@@ -480,6 +491,7 @@ open class PokemonProperties {
pokeball = if (tag.contains(DataKeys.POKEMON_CAUGHT_BALL)) tag.getString(DataKeys.POKEMON_CAUGHT_BALL) else null
nature = if (tag.contains(DataKeys.POKEMON_NATURE)) tag.getString(DataKeys.POKEMON_NATURE) else null
ability = if (tag.contains(DataKeys.POKEMON_ABILITY)) tag.getString(DataKeys.POKEMON_ABILITY) else null
status = if (tag.contains(DataKeys.POKEMON_STATUS_NAME)) tag.getString(DataKeys.POKEMON_STATUS_NAME) else null
ivs = if (tag.contains(DataKeys.POKEMON_IVS)) ivs?.loadFromNBT(tag.getCompound(DataKeys.POKEMON_IVS)) as IVs? else null
evs = if (tag.contains(DataKeys.POKEMON_EVS)) evs?.loadFromNBT(tag.getCompound(DataKeys.POKEMON_EVS)) as EVs? else null
val custom = tag.getList(DataKeys.POKEMON_PROPERTIES_CUSTOM, NbtElement.STRING_TYPE.toInt())
@@ -502,6 +514,7 @@ open class PokemonProperties {
pokeball?.let { json.addProperty(DataKeys.POKEMON_CAUGHT_BALL, it) }
nature?.let { json.addProperty(DataKeys.POKEMON_NATURE, it) }
ability?.let { json.addProperty(DataKeys.POKEMON_ABILITY, it) }
status?.let { json.addProperty(DataKeys.POKEMON_STATUS_NAME, it) }
ivs?.let { json.add(DataKeys.POKEMON_IVS, it.saveToJSON(JsonObject())) }
evs?.let { json.add(DataKeys.POKEMON_EVS, it.saveToJSON(JsonObject())) }
val custom = JsonArray()
@@ -523,6 +536,7 @@ open class PokemonProperties {
pokeball = json.get(DataKeys.POKEMON_CAUGHT_BALL)?.asString
nature = json.get(DataKeys.POKEMON_NATURE)?.asString
ability = json.get(DataKeys.POKEMON_ABILITY)?.asString
status = json.get(DataKeys.POKEMON_STATUS_NAME)?.asString
ivs?.loadFromJSON(json.getAsJsonObject(DataKeys.POKEMON_IVS))
evs?.loadFromJSON(json.getAsJsonObject(DataKeys.POKEMON_EVS))
val custom = json.get(DataKeys.POKEMON_PROPERTIES_CUSTOM)?.asJsonArray
@@ -544,6 +558,7 @@ open class PokemonProperties {
pokeball?.let { pieces.add("pokeball=$it") }
nature?.let { pieces.add("nature=$it") }
ability?.let { pieces.add("ability=$it") }
status?.let { pieces.add("status=$it") }
ivs?.forEach{ stat ->
pieces.add("${stat.key}_iv=${stat.value}")
}
@@ -21,28 +21,37 @@ import com.cobblemon.mod.common.pokemon.Pokemon
fun interface PokemonPropertyExtractor {
companion object {
@JvmField
val SPECIES = PokemonPropertyExtractor { pokemon, properties -> properties.species = pokemon.species.resourceIdentifier.toString() }
@JvmField
val FORM = PokemonPropertyExtractor { pokemon, properties -> properties.form = pokemon.form.formOnlyShowdownId() }
@JvmField
val SHINY = PokemonPropertyExtractor { pokemon, properties -> properties.shiny = pokemon.shiny }
@JvmField
val ASPECTS = PokemonPropertyExtractor { pokemon, properties -> properties.aspects = pokemon.aspects }
@JvmField
val LEVEL = PokemonPropertyExtractor { pokemon, properties -> properties.level = pokemon.level }
@JvmField
val GENDER = PokemonPropertyExtractor { pokemon, properties -> properties.gender = pokemon.gender }
@JvmField
val FRIENDSHIP = PokemonPropertyExtractor { pokemon, properties -> properties.friendship = pokemon.friendship }
@JvmField
val POKEBALL = PokemonPropertyExtractor { pokemon, properties -> properties.pokeball = pokemon.caughtBall.name.toString() }
@JvmField
val NATURE = PokemonPropertyExtractor { pokemon, properties -> properties.nature = pokemon.nature.name.toString() }
@JvmField
val ABILITY = PokemonPropertyExtractor { pokemon, properties -> properties.ability = pokemon.ability.name }
val ALL = mutableListOf<PokemonPropertyExtractor>()
@JvmField
val ALL = arrayOf(SPECIES, FORM, SHINY, ASPECTS, LEVEL, GENDER, FRIENDSHIP, POKEBALL, NATURE, ABILITY)
val SPECIES = add { pokemon, properties -> properties.species = pokemon.species.resourceIdentifier.toString() }
@JvmField
val FORM = add { pokemon, properties -> properties.form = pokemon.form.formOnlyShowdownId() }
@JvmField
val SHINY = add { pokemon, properties -> properties.shiny = pokemon.shiny }
@JvmField
val ASPECTS = add { pokemon, properties -> properties.aspects = pokemon.aspects }
@JvmField
val LEVEL = add { pokemon, properties -> properties.level = pokemon.level }
@JvmField
val GENDER = add { pokemon, properties -> properties.gender = pokemon.gender }
@JvmField
val FRIENDSHIP = add { pokemon, properties -> properties.friendship = pokemon.friendship }
@JvmField
val POKEBALL = add { pokemon, properties -> properties.pokeball = pokemon.caughtBall.name.toString() }
@JvmField
val NATURE = add { pokemon, properties -> properties.nature = pokemon.nature.name.toString() }
@JvmField
val ABILITY = add { pokemon, properties -> properties.ability = pokemon.ability.name }
@JvmField
val NICKNAME = add { pokemon, properties -> properties.nickname = pokemon.nickname }
@JvmField
val STATUS = add { pokemon, properties -> properties.status = pokemon.status?.status?.showdownName }
fun add(extractor: PokemonPropertyExtractor): PokemonPropertyExtractor {
ALL.add(extractor)
return extractor
}
}
operator fun invoke(pokemon: Pokemon, properties: PokemonProperties)
@@ -115,12 +115,14 @@ object PokemonSpecies : JsonDataRegistry<Species> {
SpeciesAdditions.observable.subscribe {
this.species.forEach(Species::initialize)
this.species.forEach(Species::resolveEvolutionMoves)
Cobblemon.showdownThread.queue { ShowdownService.get().registerSpecies() }
// Reload this with the mod
CobblemonEmptyHeldItemManager.load()
CobblemonHeldItemManager.load()
Cobblemon.LOGGER.info("Loaded {} Pokémon species", this.speciesByIdentifier.size)
this.observable.emit(this)
Cobblemon.showdownThread.queue {
it.registerSpecies()
it.indicateSpeciesInitialized()
// Reload this with the mod
CobblemonHeldItemManager.load()
Cobblemon.LOGGER.info("Loaded {} Pokémon species", this.speciesByIdentifier.size)
this.observable.emit(this)
}
}
}
@@ -236,7 +238,7 @@ object PokemonSpecies : JsonDataRegistry<Species> {
val heightm = form?.height ?: species.height
val weightkg = form?.weight ?: species.weight
// This is ugly, but we already have it hardcoded in the mod anyway
val maxHp = if (species.showdownId() == "shedinja") 1 else null
val maxHP = if (species.showdownId() == "shedinja") 1 else null
val canGigantamax: String? = if (form?.gigantamaxMove != null) form.gigantamaxMove.name else null
val cannotDynamax = form?.dynamaxBlocked ?: species.dynamaxBlocked
// ToDo battleOnly
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common.api.pokemon.stats
import com.cobblemon.mod.common.api.tags.CobblemonItemTags
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
/**
@@ -53,9 +54,24 @@ interface EvCalculator {
object Generation8EvCalculator : EvCalculator {
private val powerItems = mapOf(
Stats.SPEED to CobblemonItemTags.POWER_ANKLET,
Stats.SPECIAL_DEFENCE to CobblemonItemTags.POWER_BAND,
Stats.DEFENCE to CobblemonItemTags.POWER_BELT,
Stats.ATTACK to CobblemonItemTags.POWER_BRACER,
Stats.SPECIAL_ATTACK to CobblemonItemTags.POWER_LENS,
Stats.HP to CobblemonItemTags.POWER_WEIGHT
)
override fun calculate(battlePokemon: BattlePokemon, opponentPokemon: BattlePokemon): Map<Stat, Int> {
// ToDo Once held items and EV related items are implemented update this
return opponentPokemon.originalPokemon.form.evYield
val heldItem = battlePokemon.effectedPokemon.heldItemNoCopy()
val evYield = mutableMapOf<Stat, Int>()
for ((stat, value) in opponentPokemon.originalPokemon.form.evYield) {
val boost = if (!heldItem.isEmpty && heldItem.isIn(powerItems[stat])) 8 else 0
evYield[stat] = evYield.getOrDefault(stat, 0) + value + boost
}
return evYield
}
}
@@ -37,6 +37,11 @@ interface Stat {
*/
val type: Type
/**
* The name used by Showdown to store the stats (attack is 'atk', for example)
*/
val showdownId: String
/**
* Represents the type of this stat.
*/
@@ -18,16 +18,16 @@ import net.minecraft.util.Identifier
* An enumeration of the default implemented [Stat]s.
* Contains all the traditional stats in official Pokémon games.
*/
enum class Stats(override val identifier: Identifier, override val displayName: Text, override val type: Stat.Type) : Stat {
enum class Stats(override val identifier: Identifier, override val displayName: Text, override val type: Stat.Type, override val showdownId: String) : Stat {
HP(cobblemonResource("hp"), lang("stat.hp.name"), Stat.Type.PERMANENT),
ATTACK(cobblemonResource("attack"), lang("stat.attack.name"), Stat.Type.PERMANENT),
DEFENCE(cobblemonResource("defence"), lang("stat.defence.name"), Stat.Type.PERMANENT),
SPECIAL_ATTACK(cobblemonResource("special_attack"), lang("stat.special_attack.name"), Stat.Type.PERMANENT),
SPECIAL_DEFENCE(cobblemonResource("special_defence"), lang("stat.special_defence.name"), Stat.Type.PERMANENT),
SPEED(cobblemonResource("speed"), lang("stat.speed.name"), Stat.Type.PERMANENT),
EVASION(cobblemonResource("evasion"), lang("stat.evasion.name"), Stat.Type.BATTLE_ONLY),
ACCURACY(cobblemonResource("accuracy"), lang("stat.accuracy.name"), Stat.Type.BATTLE_ONLY);
HP(cobblemonResource("hp"), lang("stat.hp.name"), Stat.Type.PERMANENT, "hp"),
ATTACK(cobblemonResource("attack"), lang("stat.attack.name"), Stat.Type.PERMANENT, "atk"),
DEFENCE(cobblemonResource("defence"), lang("stat.defence.name"), Stat.Type.PERMANENT, "def"),
SPECIAL_ATTACK(cobblemonResource("special_attack"), lang("stat.special_attack.name"), Stat.Type.PERMANENT, "spa"),
SPECIAL_DEFENCE(cobblemonResource("special_defence"), lang("stat.special_defence.name"), Stat.Type.PERMANENT, "spd"),
SPEED(cobblemonResource("speed"), lang("stat.speed.name"), Stat.Type.PERMANENT, "spe"),
EVASION(cobblemonResource("evasion"), lang("stat.evasion.name"), Stat.Type.BATTLE_ONLY, "evasion"),
ACCURACY(cobblemonResource("accuracy"), lang("stat.accuracy.name"), Stat.Type.BATTLE_ONLY, "accuracy");
companion object {
@@ -14,9 +14,9 @@ import com.cobblemon.mod.common.api.spawning.mixins.CachedOnlyChunkAccessor
import com.cobblemon.mod.common.api.spawning.prospecting.SpawningProspector
import com.cobblemon.mod.common.api.spawning.spawner.Spawner
import com.cobblemon.mod.common.api.spawning.spawner.SpawningArea
import com.cobblemon.mod.common.api.tags.CobblemonBlockTags
import net.minecraft.block.Blocks
import net.minecraft.entity.LivingEntity
import net.minecraft.registry.tag.BlockTags
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Box
import net.minecraft.util.math.ChunkSectionPos.getSectionCoord
@@ -97,8 +97,7 @@ object CobblemonSpawningProspector : SpawningProspector {
skyLevel[x - area.baseX][z - area.baseZ] = y
}
// TODO don't just check solid, have some property somewhere modifiable that excludes some blocks from occluding
if (state.isSolid && !state.isIn(BlockTags.LEAVES)) {
if (state.fluidState.isEmpty && !state.isIn(CobblemonBlockTags.SEES_SKY)) {
canSeeSky = false
}
}
@@ -22,8 +22,6 @@ import net.minecraft.block.Block
* @since February 7th, 2022
*/
abstract class AreaTypeSpawningCondition<T : AreaSpawningContext> : SpawningCondition<T>() {
var minWidth: Int? = null
var maxWidth: Int? = null
var minHeight: Int? = null
var maxHeight: Int? = null
var neededNearbyBlocks: MutableList<RegistryLikeCondition<Block>>? = null
@@ -31,10 +29,6 @@ abstract class AreaTypeSpawningCondition<T : AreaSpawningContext> : SpawningCond
override fun fits(ctx: T, detail: SpawnDetail): Boolean {
if (!super.fits(ctx, detail)) {
return false
} else if (minWidth != null && ctx.width < minWidth!!) {
return false
} else if (maxWidth != null && ctx.width > maxWidth!!) {
return false
} else if (minHeight != null && ctx.height < minHeight!!) {
return false
} else if (maxHeight != null && ctx.height > maxHeight!!) {
@@ -49,8 +43,6 @@ abstract class AreaTypeSpawningCondition<T : AreaSpawningContext> : SpawningCond
override fun copyFrom(other: SpawningCondition<*>, merger: Merger) {
super.copyFrom(other, merger)
if (other is AreaTypeSpawningCondition) {
merger.mergeSingle(minWidth, other.minWidth)
merger.mergeSingle(maxWidth, other.maxWidth)
merger.mergeSingle(minHeight, other.minHeight)
merger.mergeSingle(maxHeight, other.maxHeight)
neededNearbyBlocks = merger.merge(neededNearbyBlocks, other.neededNearbyBlocks)?.toMutableList()
@@ -12,9 +12,7 @@ import com.cobblemon.mod.common.api.conditional.RegistryLikeCondition
import com.cobblemon.mod.common.api.spawning.context.GroundedSpawningContext
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.util.Merger
import com.cobblemon.mod.common.util.asResource
import net.minecraft.block.Block
import net.minecraft.util.Identifier
/**
* Base type for a spawning condition that applies to some kind of [GroundedSpawningContext]. This
@@ -29,6 +27,10 @@ abstract class GroundedTypeSpawningCondition<T : GroundedSpawningContext> : Area
override fun fits(ctx: T, detail: SpawnDetail): Boolean {
return if (!super.fits(ctx, detail)) {
false
} else if (minHeight != null && ctx.height < minHeight!!) {
return false
} else if (maxHeight != null && ctx.height > maxHeight!!) {
return false
} else !(neededBaseBlocks != null && neededBaseBlocks!!.none { it.fits(ctx.baseBlock.block, ctx.blockRegistry) })
}
@@ -30,6 +30,10 @@ abstract class SubmergedTypeSpawningCondition<T : SubmergedSpawningContext> : Ar
override fun fits(ctx: T, detail: SpawnDetail): Boolean {
return if (!super.fits(ctx, detail)) {
false
} else if (minHeight != null && ctx.height < minHeight!!) {
return false
} else if (maxHeight != null && ctx.height > maxHeight!!) {
return false
} else if (minDepth != null && ctx.depth < minDepth!!) {
false
} else if (maxDepth != null && ctx.depth > maxDepth!!) {
@@ -10,13 +10,14 @@ package com.cobblemon.mod.common.api.spawning.context
import com.cobblemon.mod.common.api.spawning.SpawnCause
import com.cobblemon.mod.common.api.spawning.WorldSlice
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import kotlin.math.ceil
import kotlin.math.floor
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.ChunkPos
import net.minecraft.world.World
/**
* A [SpawningContext] that is for a particular area, and therefore has spatial properties.
@@ -31,8 +32,6 @@ open class AreaSpawningContext(
override val light: Int,
override val canSeeSky: Boolean,
override val influences: MutableList<SpawningInfluence>,
/** Space horizontally (diameter) */
val width: Int,
/** Space above. */
val height: Int,
val nearbyBlocks: List<BlockState>,
@@ -43,4 +42,44 @@ open class AreaSpawningContext(
override fun getStructureCache(pos: BlockPos): StructureChunkCache {
return slice.getStructureCache(pos)
}
/**
* Returns true if the given block can be occupied by a spawn in this context.
* This is not considering the provided state as what the entity would be on top of,
* but rather the space its hitbox would fill.
*/
open fun isSafeSpace(world: ServerWorld, pos: BlockPos, state: BlockState): Boolean = !state.isFullCube(world, pos)
override fun postFilter(detail: SpawnDetail): Boolean {
if (!super.postFilter(detail)) {
return false
}
if (detail.width > 1 || detail.height > 1) {
val sizeX = detail.width.takeIf { it > 0 } ?: 1
val sizeY = detail.height.takeIf { it > 0 } ?: 1
val minX = floor(position.x + 0.5 - (sizeX - 1) / 2F).toInt() - 1
val maxX = ceil(position.x + 0.5 + (sizeX + 1) / 2F).toInt() + 1
val maxY = ceil(position.y + (sizeY + 1) / 2F).toInt() + 1
val minZ = floor(position.z + 0.5 - (sizeX - 1) / 2F).toInt() - 1
val maxZ = ceil(position.z + 0.5 + (sizeX + 1) / 2F).toInt() + 1
val mutable = BlockPos.Mutable()
for (x in minX until maxX) {
for (y in (position.y + 1)..maxY) {
for (z in minZ until maxZ) {
val state = world.getBlockState(mutable.set(x, y, z))
if (!isSafeSpace(world, mutable, state)) {
return false
}
}
}
}
}
return true
}
}
@@ -12,9 +12,9 @@ import com.cobblemon.mod.common.api.spawning.SpawnCause
import com.cobblemon.mod.common.api.spawning.WorldSlice
import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import net.minecraft.block.BlockState
import net.minecraft.registry.tag.FluidTags
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* A type of area based spawning context with a floor.
@@ -29,11 +29,10 @@ abstract class FlooredSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : AreaSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice) {
) : AreaSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice) {
/** The block that the spawning is occurring on. */
val baseBlock = slice.getBlockState(position.x, position.y, position.z)
}
@@ -51,11 +50,10 @@ open class GroundedSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice)
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice)
/**
* A spawning context that occurs at the bottom of a body of water.
@@ -70,11 +68,12 @@ open class SeafloorSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice)
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice) {
override fun isSafeSpace(world: ServerWorld, pos: BlockPos, state: BlockState) = state.fluidState.isIn(FluidTags.WATER)
}
/**
* A spawning context that occurs at the bottom of bodies of lava.
@@ -89,11 +88,12 @@ open class LavafloorSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice)
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice) {
override fun isSafeSpace(world: ServerWorld, pos: BlockPos, state: BlockState) = state.fluidState.isIn(FluidTags.LAVA)
}
open class SurfaceSpawningContext(
cause: SpawnCause,
@@ -102,9 +102,8 @@ open class SurfaceSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
val depth: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice)
) : FlooredSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice)
@@ -24,7 +24,6 @@ import net.minecraft.server.world.ServerWorld
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.ChunkPos
import net.minecraft.world.World
import net.minecraft.world.biome.Biome
import net.minecraft.world.gen.StructureAccessor
import net.minecraft.world.gen.structure.Structure
@@ -142,6 +141,13 @@ abstract class SpawningContext {
/** Returns true if none of the influences.affectSpawnable return false */
return influences.none { !it.affectSpawnable(detail, this) }
}
/**
* Filters a spawning detail by some extra, more expensive condition defined by the context itself.
* @return true if the [SpawnDetail] is acceptable by the context's own logic.
*/
open fun postFilter(detail: SpawnDetail): Boolean = true
open fun afterSpawn(entity: Entity) {
influences.forEach { it.affectSpawn(entity) }
}
@@ -14,7 +14,6 @@ import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import net.minecraft.block.BlockState
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* A type of area based spawning context with a fluid base block.
@@ -29,11 +28,12 @@ open class SubmergedSpawningContext(
light: Int,
canSeeSky: Boolean,
influences: MutableList<SpawningInfluence>,
width: Int,
height: Int,
val depth: Int,
nearbyBlocks: List<BlockState>,
slice: WorldSlice
) : AreaSpawningContext(cause, world, position, light, canSeeSky, influences, width, height, nearbyBlocks, slice) {
) : AreaSpawningContext(cause, world, position, light, canSeeSky, influences, height, nearbyBlocks, slice) {
val fluid = slice.getBlockState(position.x, position.y, position.z).fluidState
override fun isSafeSpace(world: ServerWorld, pos: BlockPos, state: BlockState) = state.fluidState.fluid == fluid.fluid
}
@@ -61,7 +61,6 @@ object GroundedSpawningContextCalculator : FlooredSpawningContextCalculator<Grou
light = getLight(input),
canSeeSky = getCanSeeSky(input),
influences = input.spawner.copyInfluences(),
width = getHorizontalSpace(input, surroundingCondition, config.maxHorizontalSpace, offsetY = 1),
height = getHeight(input, surroundingCondition, config.maxVerticalSpace, offsetY = 1),
slice = input.slice,
nearbyBlocks = getNearbyBlocks(input)
@@ -88,7 +87,6 @@ object SeafloorSpawningContextCalculator : FlooredSpawningContextCalculator<Seaf
light = getLight(input),
canSeeSky = getCanSeeSky(input),
influences = input.spawner.copyInfluences(),
width = getHorizontalSpace(input, surroundingCondition, config.maxHorizontalSpace, offsetY = 1),
height = getHeight(input, surroundingCondition, config.maxVerticalSpace, offsetY = 1),
slice = input.slice,
nearbyBlocks = getNearbyBlocks(input)
@@ -115,7 +113,6 @@ object LavafloorSpawningContextCalculator : FlooredSpawningContextCalculator<Lav
light = getLight(input),
canSeeSky = getCanSeeSky(input),
influences = input.spawner.copyInfluences(),
width = getHorizontalSpace(input, surroundingCondition, config.maxHorizontalSpace, offsetY = 1),
height = getHeight(input, surroundingCondition, config.maxVerticalSpace, offsetY = 1),
slice = input.slice,
nearbyBlocks = getNearbyBlocks(input)
@@ -143,7 +140,6 @@ object SurfaceSpawningContextCalculator : FlooredSpawningContextCalculator<Surfa
light = getLight(input),
canSeeSky = getCanSeeSky(input),
influences = input.spawner.copyInfluences(),
width = getHorizontalSpace(input, surroundingCondition, config.maxHorizontalSpace, offsetY = 1),
height = getHeight(input, surroundingCondition, config.maxVerticalSpace / 2, offsetY = 1),
depth = getDepth(input, baseCondition, config.maxVerticalSpace / 2),
slice = input.slice,
@@ -47,7 +47,6 @@ object SubmergedSpawningContextCalculator : AreaSpawningContextCalculator<Submer
light = getLight(input),
canSeeSky = getCanSeeSky(input),
influences = input.spawner.copyInfluences(),
width = getHorizontalSpace(input, fluidCondition, config.maxHorizontalSpace),
height = getHeight(input, fluidCondition, ceil(config.maxVerticalSpace / 2F)),
depth = getDepth(input, fluidCondition, ceil(config.maxVerticalSpace / 2F)),
slice = input.slice,
@@ -15,9 +15,11 @@ import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.spawning.context.SpawningContext
import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.pokemon.Pokemon
import com.cobblemon.mod.common.util.asIdentifierDefaultingNamespace
import com.cobblemon.mod.common.util.lang
import com.google.gson.annotations.SerializedName
import kotlin.math.ceil
import net.minecraft.text.MutableText
/**
@@ -38,6 +40,10 @@ class PokemonSpawnDetail : SpawnDetail() {
val drops: DropTable? = null
val heldItems: MutableList<PossibleHeldItem>? = null
private val pokemonExample: Pokemon by lazy { pokemon.create() }
// Calculate the size based off the hitbox unless it's been explicitly set
/* todo breadcrumbing, ai */
@@ -68,6 +74,14 @@ class PokemonSpawnDetail : SpawnDetail() {
species.secondaryType?.let { listOf(species.primaryType.name.lowercase(), it.name.lowercase()) }
?: listOf(species.primaryType.name.lowercase())
)
if (height == -1) {
height = ceil(pokemonExample.form.hitbox.height * pokemonExample.form.baseScale).toInt()
}
if (width == -1) {
width = ceil(pokemonExample.form.hitbox.width * pokemonExample.form.baseScale).toInt()
}
}
}
}
@@ -42,6 +42,8 @@ abstract class SpawnDetail : ModDependant {
var anticonditions = mutableListOf<SpawningCondition<*>>()
var compositeCondition: CompositeSpawningCondition? = null
var weightMultipliers = mutableListOf<WeightMultiplier>()
var width = -1
var height = -1
var weight = -1F
var percentage = -1F
@@ -63,7 +65,10 @@ abstract class SpawnDetail : ModDependant {
return false
} else if (compositeCondition?.satisfiedBy(ctx, this) == false) {
return false
} else if (!ctx.postFilter(this)) {
return false
}
return true
}
@@ -1,20 +0,0 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.spawning.influence
import com.cobblemon.mod.common.api.spawning.context.SpawningContext
import com.cobblemon.mod.common.api.spawning.detail.PokemonSpawnDetail
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules.DO_POKEMON_SPAWNING
open class GameRuleInfluence : SpawningInfluence {
override fun affectSpawnable(detail: SpawnDetail, ctx: SpawningContext): Boolean {
return detail !is PokemonSpawnDetail || ctx.world.gameRules.getBoolean(DO_POKEMON_SPAWNING)
}
}
@@ -21,7 +21,7 @@ import kotlin.reflect.full.createInstance
* A spawning selector that compiles a distinct list of all spawn details that
* are possible across the context list, chooses which context type to spawn based
* on a weighted selection of the number of spawns possible in it, performs a weighted
* selection of them of spawns in that context type, and then chooses which of its contexts
* selection of spawns in that context type, and then chooses which of its contexts
* to spawn them on based on their context-adjusted weights.
*
* The goal of this algorithm is to be kinder to spawns that are only possible
@@ -78,11 +78,12 @@ open class FlatContextWeightedSelector : SpawningSelector {
val possible = spawner.getMatchingSpawns(ctx)
if (possible.isNotEmpty()) {
val contextSelectionData = contextTypesToSpawns.getOrPut(contextType) { ContextSelectionData(mutableMapOf(), 0F) }
possible.forEach {
if (it.percentage > 0) {
// Only add to percentSum if this is the first time we've seen this SpawnDetail for this context
// type, otherwise the percentage will get amplified for every context the thing was possible,
// completely ruining the point of this pre-selection percentage.
if (it.percentage > 0 && !contextSelectionData.spawnsToContexts.containsKey(it)) {
contextSelectionData.percentSum += it.percentage
}
@@ -107,8 +108,8 @@ open class FlatContextWeightedSelector : SpawningSelector {
if (selectionData.isEmpty()) {
return null
}
// Which context should we use?
// Which context type should we use?
val contextSelectionData = selectionData.entries.toList().weightedSelection { getWeight(it.key) * it.value.size }!!.value
val spawnsToContexts = contextSelectionData.spawnsToContexts
@@ -0,0 +1,143 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.api.spawning.selection
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.spawning.context.RegisteredSpawningContext
import com.cobblemon.mod.common.api.spawning.context.SpawningContext
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.api.spawning.spawner.Spawner
import com.cobblemon.mod.common.util.weightedSelection
import kotlin.random.Random
/**
* A spawning selector that compiles a distinct list of all spawn details that
* are possible across any context type and performs a weighted selection of spawns.
*
* The goal of this algorithm is to be kinder to spawns that are only possible
* in very specific locational conditions or context types by not letting the scarcity
* of suitable locations hurt its chances of spawning. It differs from the
* [FlatContextWeightedSelector] because here a spawning context type only appearing once
* will not make it any less likely to be selected.
*
* When choosing which context a specific spawn detail will spawn at once that spawn detail
* has been chosen, it does a flat random across the possible contexts.
*
* At a glance:
* - Spawn detail selection is flat across context quantity
* - The popularity of specific context types has no bearing on the spawn chance.
*
* @author Hiroku
* @since July 10th, 2022
*/
open class FlatSelector : SpawningSelector {
open fun getWeight(contextType: RegisteredSpawningContext<*>) = contextType.getWeight()
protected class ContextSelectionData(
val spawnsToContexts: MutableMap<SpawnDetail, MutableList<SpawningContext>>,
var percentSum: Float
) {
val size: Int
get() = spawnsToContexts.size
}
protected fun getSelectionData(
spawner: Spawner,
contexts: List<SpawningContext>
): ContextSelectionData {
val spawnsToContexts: MutableMap<SpawnDetail, MutableList<SpawningContext>> = mutableMapOf()
var percentSum = 0F
contexts.forEach { ctx ->
spawner.getMatchingSpawns(ctx).forEach {
// Only add to percentSum if this is the first time we've seen this SpawnDetail, otherwise
// the percentage will get amplified for every context the thing was possible, completely
// ruining the point of this pre-selection percentage.
if (it.percentage > 0 && !spawnsToContexts.containsKey(it)) {
percentSum += it.percentage
}
val selectingSpawnInformation = spawnsToContexts.getOrPut(
it,
::mutableListOf
)
selectingSpawnInformation.add(ctx)
}
}
return ContextSelectionData(spawnsToContexts, percentSum)
}
override fun select(
spawner: Spawner,
contexts: List<SpawningContext>
): Pair<SpawningContext, SpawnDetail>? {
val selectionData = getSelectionData(spawner, contexts)
if (selectionData.size == 0) {
return null
}
val spawnsToContexts = selectionData.spawnsToContexts
var percentSum = selectionData.percentSum
// First pass is doing percentage checks.
if (percentSum > 0) {
if (percentSum > 100) {
Cobblemon.LOGGER.warn(
"""
A spawn list for ${spawner.name} exceeded 100% on percentage sums...
This means you don't understand how this option works.
""".trimIndent()
)
return null
}
/*
* It's [0, 1) and I want (0, 1]
* See half-open intervals here https://en.wikipedia.org/wiki/Interval_(mathematics)#Terminology
*/
val selectedPercentage = 100 - Random.Default.nextFloat() * 100
percentSum = 0F
for ((spawnDetail, info) in spawnsToContexts) {
if (spawnDetail.percentage > 0) {
percentSum += spawnDetail.percentage
if (percentSum >= selectedPercentage) {
return info.random() to spawnDetail
}
}
}
}
val selectedSpawn = spawnsToContexts.entries.toList().weightedSelection { it.key.weight }!!
return selectedSpawn.value.random() to selectedSpawn.key
}
override fun getTotalWeights(
spawner: Spawner,
contexts: List<SpawningContext>
): Map<SpawnDetail, Float> {
val selectionData = getSelectionData(spawner, contexts)
if (selectionData.size == 0) {
return mapOf()
}
val totalWeights = mutableMapOf<SpawnDetail, Float>()
for (spawnDetail in selectionData.spawnsToContexts.keys) {
totalWeights[spawnDetail] = spawnDetail.weight
}
return totalWeights
}
}
@@ -13,7 +13,7 @@ import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.api.spawning.spawner.Spawner
/**
* Interface responsible for taking all of the potential spawns across many contexts, and applying some kind of
* Interface responsible for taking all the potential spawns across many contexts, and applying some kind of
* selection process to choose one. It is also responsible for generating a name to percentage probability for the given
* spawn information for checking spawns under specific conditions.
*
@@ -30,6 +30,7 @@ import net.minecraft.util.math.Vec3d
import net.minecraft.world.World
import net.minecraft.world.chunk.Chunk
import net.minecraft.world.chunk.ChunkStatus
import com.cobblemon.mod.common.world.gamerules.CobblemonGameRules.DO_POKEMON_SPAWNING
/**
* A type of [TickingSpawner] that operates within some area. When this spawner type
@@ -60,6 +61,9 @@ abstract class AreaSpawner(
override fun run(cause: SpawnCause): Pair<SpawningContext, SpawnDetail>? {
val area = getArea(cause)
if (area?.world?.gameRules?.getBoolean(DO_POKEMON_SPAWNING) == false) {
return null
}
val constrainedArea = if (area != null) constrainArea(area) else null
if (constrainedArea != null) {
val numberNearby = constrainedArea.world.getEntitiesByClass(
@@ -11,7 +11,6 @@ package com.cobblemon.mod.common.api.spawning.spawner
import com.cobblemon.mod.common.api.spawning.CobblemonSpawnPools
import com.cobblemon.mod.common.api.spawning.SpawnerManager
import com.cobblemon.mod.common.api.spawning.detail.SpawnPool
import com.cobblemon.mod.common.api.spawning.influence.GameRuleInfluence
import com.cobblemon.mod.common.api.spawning.influence.PlayerLevelRangeInfluence
import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import net.minecraft.server.network.ServerPlayerEntity
@@ -26,7 +25,7 @@ import net.minecraft.server.network.ServerPlayerEntity
*/
object PlayerSpawnerFactory {
var spawns: SpawnPool = CobblemonSpawnPools.WORLD_SPAWN_POOL
var influenceBuilders = mutableListOf<(player: ServerPlayerEntity) -> SpawningInfluence?>({ PlayerLevelRangeInfluence(it, variation = 5) }, { GameRuleInfluence() })
var influenceBuilders = mutableListOf<(player: ServerPlayerEntity) -> SpawningInfluence?>({ PlayerLevelRangeInfluence(it, variation = 5) })
fun create(spawnerManager: SpawnerManager, player: ServerPlayerEntity): PlayerSpawner {
val influences = influenceBuilders.mapNotNull { it(player) }
@@ -34,4 +33,4 @@ object PlayerSpawnerFactory {
it.influences.addAll(influences)
}
}
}
}
@@ -15,7 +15,7 @@ import com.cobblemon.mod.common.api.spawning.detail.SpawnAction
import com.cobblemon.mod.common.api.spawning.detail.SpawnDetail
import com.cobblemon.mod.common.api.spawning.detail.SpawnPool
import com.cobblemon.mod.common.api.spawning.influence.SpawningInfluence
import com.cobblemon.mod.common.api.spawning.selection.FlatContextWeightedSelector
import com.cobblemon.mod.common.api.spawning.selection.FlatSelector
import com.cobblemon.mod.common.api.spawning.selection.SpawningSelector
import net.minecraft.entity.Entity
@@ -32,7 +32,7 @@ abstract class TickingSpawner(
var spawns: SpawnPool,
val manager: SpawnerManager
) : Spawner {
private var selector: SpawningSelector = FlatContextWeightedSelector()
private var selector: SpawningSelector = FlatSelector()
override val influences = mutableListOf<SpawningInfluence>()
override fun canSpawn() = active
@@ -121,8 +121,12 @@ class ReforgedConversion(val base: Path) : CobblemonConverter<NbtCompound> {
evs[Stats.SPECIAL_DEFENCE] = nbt.getInt("EVSpecialDefense")
evs[Stats.SPEED] = nbt.getInt("EVSpeed")
result.evs = evs
result.ivs = ivs
ivs.forEach { stat ->
result.setIV(stat.key, stat.value)
}
evs.forEach { stat ->
result.setEV(stat.key, stat.value)
}
for (move in nbt.getList("Moveset", 10)) {
val compound = move as NbtCompound
@@ -247,9 +247,6 @@ open class PartyStore(override val uuid: UUID) : PokemonStore<PartyPosition>() {
fun toBattleTeam(clone: Boolean = false, checkHealth: Boolean = true, leadingPokemon: UUID? = null) = mapNotNull {
// TODO Other 'able to battle' checks
if (checkHealth && it.currentHealth <= 0) {
return@mapNotNull null
}
return@mapNotNull if (clone) {
BattlePokemon.safeCopyOf(it)
} else {
@@ -24,10 +24,15 @@ class JsonPlayerDataStoreFactory : PlayerDataStoreFactory {
fun setup(server: MinecraftServer) {
adapter.setup(server);
}
override fun load(uuid: UUID): PlayerData {
if(cache.contains(uuid))
return cache[uuid]!!;
return adapter.load(uuid);
return if(cache.contains(uuid))
cache[uuid]!!;
else {
val data = adapter.load(uuid);
cache[uuid] = data
data
}
}
override fun save(data: PlayerData) {
@@ -9,75 +9,34 @@
package com.cobblemon.mod.common.api.tags
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.registry.Registry
import net.minecraft.registry.Registries
import net.minecraft.registry.RegistryKeys
import net.minecraft.registry.tag.TagKey
/**
* A collection of the Cobblemon [TagKey]s related to the [Registry.BLOCK].
* A collection of the Cobblemon [TagKey]s related to the [Registries.BLOCK].
*
* @author Licious
* @since October 29th, 2022
*/
@Suppress("HasPlatformType", "unused")
object CobblemonBlockTags {
@JvmField
val APRICORN_LEAVES = createTag("apricorn_leaves")
@JvmField
val APRICORN_LOGS = createTag("apricorn_logs")
@JvmField
val APRICORN_SAPLINGS = createTag("apricorn_saplings")
@JvmField
val APRICORNS = createTag("apricorns")
@JvmField
val DRIPSTONE_GROWABLE = createTag("dripstone_growable")
@JvmField
val DRIPSTONE_REPLACEABLES = createTag("dripstone_replaceables")
// ToDo remove in 1.3
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val FENCE_GATES = createTag("fence_gates")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val FENCES = createTag("fences")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val LEAVES = createTag("leaves")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val LOGS = createTag("logs")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val LOGS_THAT_BURN = createTag("logs_that_burn")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val PLANKS = createTag("planks")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val SAPLINGS = createTag("saplings")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val STANDING_SIGNS = createTag("standing_signs")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WALL_SIGNS = createTag("wall_signs")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WOODEN_BUTTONS = createTag("wooden_buttons")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WOODEN_FENCES = createTag("wooden_fences")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WOODEN_PRESSURE_PLATES = createTag("wooden_pressure_plates")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WOODEN_SLABS = createTag("wooden_slabs")
@Deprecated(message = "This tag no longer exists", level = DeprecationLevel.ERROR)
@JvmField
val WOODEN_STAIRS = createTag("wooden_stairs")
@JvmField val APRICORN_LEAVES = createTag("apricorn_leaves")
@JvmField val APRICORN_LOGS = createTag("apricorn_logs")
@JvmField val APRICORN_SAPLINGS = createTag("apricorn_saplings")
@JvmField val APRICORNS = createTag("apricorns")
@JvmField val BERRY_SOIL = createTag("berry_soil")
@JvmField val CROPS = createTag("crops")
@JvmField val DRIPSTONE_GROWABLE = createTag("dripstone_growable")
@JvmField val DRIPSTONE_REPLACEABLES = createTag("dripstone_replaceables")
@JvmField val FLOWERS = createTag("flowers")
@JvmField val MEDICINAL_LEEK_PLANTABLE = createTag("medicinal_leek_plantable")
@JvmField val MINTS = createTag("mints")
@JvmField val ROOTS_SPREADABLE = createTag("roots_spreadable")
@JvmField val SMALL_FLOWERS = createTag("small_flowers")
@JvmField val SEES_SKY = createTag("sees_sky")
private fun createTag(name: String) = TagKey.of(RegistryKeys.BLOCK, cobblemonResource(name))
}
}
@@ -38,6 +38,22 @@ object CobblemonItemTags {
@JvmField
val LUCKY_EGG = create("held/lucky_egg")
@JvmField
val DESTINY_KNOT = create("held/destiny_knot")
@JvmField
val EVERSTONE = create("held/everstone")
@JvmField
val POWER_ANKLET = create("held/power_anklet")
@JvmField
val POWER_BAND = create("held/power_band")
@JvmField
val POWER_BELT = create("held/power_belt")
@JvmField
val POWER_BRACER = create("held/power_bracer")
@JvmField
val POWER_LENS = create("held/power_lens")
@JvmField
val POWER_WEIGHT = create("held/power_weight")
@JvmField
val EVOLUTION_STONES = create("evolution_stones")
@JvmField
val EVOLUTION_ITEMS = create("evolution_items")
@@ -0,0 +1,64 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.PrioritizedList
import com.cobblemon.mod.common.api.data.DataRegistry
import com.cobblemon.mod.common.api.reactive.SimpleObservable
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.cobblemon.mod.common.item.battle.BagItem
import com.cobblemon.mod.common.item.battle.BagItemConvertible
import com.cobblemon.mod.common.util.cobblemonResource
import java.io.File
import net.minecraft.item.ItemStack
import net.minecraft.resource.ResourceManager
import net.minecraft.resource.ResourceType
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Identifier
/**
* A registry for [BagItem]s that could be parsed from [ItemStack]s. This registry is used as the resource loading
* mechanism for bag item scripts, but add to [bagItems] to map from stacks to [BagItem]s.
*
* @author Hiroku
* @since June 26th, 2023
*/
object BagItems : DataRegistry {
override val id = cobblemonResource("bag_items")
override val type = ResourceType.SERVER_DATA
override val observable = SimpleObservable<BagItems>()
override fun sync(player: ServerPlayerEntity) {}
val bagItems = PrioritizedList<BagItemConvertible>()
internal val bagItemsScripts = mutableMapOf<String, String>() // itemId to JavaScript
init {
observable.subscribe {
Cobblemon.showdownThread.queue(ShowdownService::registerBagItems)
}
}
fun getConvertibleForStack(stack: ItemStack): BagItemConvertible? {
return bagItems.firstOrNull { it.getBagItem(stack) != null }
}
override fun reload(manager: ResourceManager) {
manager.findResources("bag_items") { it.path.endsWith(".js") }.forEach { (identifier, resource) ->
resource.inputStream.use { stream ->
stream.bufferedReader().use { reader ->
val resolvedIdentifier = Identifier(identifier.namespace, File(identifier.path).nameWithoutExtension)
val js = reader.readText()
bagItemsScripts[resolvedIdentifier.path] = js
}
}
}
this.observable.emit(this)
}
}
@@ -21,24 +21,27 @@ import com.cobblemon.mod.common.entity.pokemon.PokemonEntity
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.party
import java.util.Optional
import java.util.UUID
import net.minecraft.entity.Entity
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.MutableText
import net.minecraft.text.Text
import java.util.*
import kotlin.collections.HashMap
object BattleBuilder {
@JvmOverloads
fun pvp1v1(
player1: ServerPlayerEntity,
player2: ServerPlayerEntity,
leadingPokemonPlayer1: UUID? = null,
leadingPokemonPlayer2: UUID? = null,
battleFormat: BattleFormat = BattleFormat.GEN_9_SINGLES,
cloneParties: Boolean = false,
healFirst: Boolean = false,
partyAccessor: (ServerPlayerEntity) -> PartyStore = { it.party() }
): BattleStartResult {
val team1 = partyAccessor(player1).toBattleTeam(clone = cloneParties, checkHealth = !healFirst)
val team2 = partyAccessor(player2).toBattleTeam(clone = cloneParties, checkHealth = !healFirst)
val team1 = partyAccessor(player1).toBattleTeam(clone = cloneParties, checkHealth = !healFirst, leadingPokemonPlayer1)
val team2 = partyAccessor(player2).toBattleTeam(clone = cloneParties, checkHealth = !healFirst, leadingPokemonPlayer2)
val player1Actor = PlayerBattleActor(player1.uuid, team1)
val player2Actor = PlayerBattleActor(player2.uuid, team2)
@@ -89,6 +92,7 @@ object BattleBuilder {
* @param fleeDistance How far away the player must get to flee the Pokémon. If the value is -1, it cannot be fled.
* @param party The party of the player to use for the battle. This does not need to be their actual party. Defaults to it though.
*/
@JvmOverloads
fun pve(
player: ServerPlayerEntity,
pokemonEntity: PokemonEntity,
@@ -16,9 +16,9 @@ import com.cobblemon.mod.common.api.pokemon.helditem.HeldItemProvider
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.api.pokemon.status.Statuses
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.cobblemon.mod.common.net.messages.client.battle.BattleChallengeExpiredPacket
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.google.gson.GsonBuilder
import java.time.Instant
import java.util.Optional
@@ -31,6 +31,7 @@ object BattleRegistry {
class BattleChallenge(
val challengeId: UUID,
val challengedPlayerUUID: UUID,
val selectedPokemonId: UUID,
var expiryTimeSeconds: Int = 60
) {
val challengedTime = Instant.now()
@@ -199,7 +200,7 @@ object BattleRegistry {
}
// Compiles the request and sends it off
ShowdownService.get().startBattle(battle, messages.toTypedArray())
ShowdownService.service.startBattle(battle, messages.toTypedArray())
CobblemonEvents.BATTLE_STARTED_POST.post(BattleStartedPostEvent(battle))
return battle
}
@@ -213,7 +214,7 @@ object BattleRegistry {
}
fun getBattleByParticipatingPlayer(serverPlayerEntity: ServerPlayerEntity) : PokemonBattle? {
return battleMap.values.find { it.actors.any { it.isForPlayer(serverPlayerEntity) } }
return battleMap.values.find { it.getActor(serverPlayerEntity) != null }
}
fun tick() {
@@ -8,6 +8,8 @@
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon
import com.cobblemon.mod.common.item.battle.BagItem
import com.cobblemon.mod.common.net.IntSize
import com.cobblemon.mod.common.util.readSizedInt
import com.cobblemon.mod.common.util.writeSizedInt
@@ -67,8 +69,9 @@ enum class ShowdownActionResponseType(val loader: (PacketByteBuf) -> ShowdownAct
SWITCH({ SwitchActionResponse(UUID.randomUUID()) }),
MOVE({ MoveActionResponse("", null) }),
DEFAULT({ DefaultActionResponse() }),
BALL({ BallActionResponse() }),
PASS({ PassActionResponse });
FORCE_PASS({ ForcePassActionResponse() }),
PASS({ PassActionResponse }),
HEAL_ITEM({ HealItemActionResponse("potion") });
}
abstract class ShowdownActionResponse(val type: ShowdownActionResponseType) {
@@ -141,6 +144,27 @@ data class MoveActionResponse(var moveName: String, var targetPnx: String? = nul
}
}
data class HealItemActionResponse(var item: String) : ShowdownActionResponse(ShowdownActionResponseType.FORCE_PASS) {
override fun saveToBuffer(buffer: PacketByteBuf) {
super.saveToBuffer(buffer)
buffer.writeString(item)
}
override fun loadFromBuffer(buffer: PacketByteBuf): ShowdownActionResponse {
super.loadFromBuffer(buffer)
item = buffer.readString()
return this
}
override fun isValid(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?, forceSwitch: Boolean): Boolean {
return !forceSwitch
}
override fun toShowdownString(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?): String {
return "healitem ${activeBattlePokemon.getPNX()} $item"
}
}
data class SwitchActionResponse(var newPokemonId: UUID) : ShowdownActionResponse(ShowdownActionResponseType.SWITCH) {
override fun saveToBuffer(buffer: PacketByteBuf) {
super.saveToBuffer(buffer)
@@ -168,6 +192,7 @@ data class SwitchActionResponse(var newPokemonId: UUID) : ShowdownActionResponse
return "switch ${activeBattlePokemon.actor.pokemonList.indexOfFirst { it.uuid == newPokemonId } + 1}"
}
}
class DefaultActionResponse: ShowdownActionResponse(ShowdownActionResponseType.DEFAULT) {
override fun isValid(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?, forceSwitch: Boolean) = true
override fun toShowdownString(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?) = "default"
@@ -177,7 +202,11 @@ object PassActionResponse : ShowdownActionResponse(ShowdownActionResponseType.PA
override fun isValid(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?, forceSwitch: Boolean) = true
override fun toShowdownString(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?) = "pass"
}
class BallActionResponse() : ShowdownActionResponse(ShowdownActionResponseType.BALL) {
/**
* Only meant to be used when the player is capturing or using an item - they are forced to pass
*/
class ForcePassActionResponse : ShowdownActionResponse(ShowdownActionResponseType.FORCE_PASS) {
override fun isValid(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?, forceSwitch: Boolean): Boolean {
if (forceSwitch) {
return false
@@ -185,11 +214,32 @@ class BallActionResponse() : ShowdownActionResponse(ShowdownActionResponseType.B
return false
}
return activeBattlePokemon.actor.expectingCaptureActions-- > 0
return activeBattlePokemon.actor.expectingPassActions.size > 0
}
override fun toShowdownString(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?) = "pass"
}
class BagItemActionResponse(val bagItem: BagItem, val target: BattlePokemon, val data: String? = null): ShowdownActionResponse(ShowdownActionResponseType.FORCE_PASS) {
override fun isValid(
activeBattlePokemon: ActiveBattlePokemon,
showdownMoveSet: ShowdownMoveset?,
forceSwitch: Boolean
): Boolean {
if (forceSwitch) {
return false
} else if (showdownMoveSet == null) {
return false
}
return activeBattlePokemon.actor.expectingPassActions.size > 0
}
override fun toShowdownString(activeBattlePokemon: ActiveBattlePokemon, showdownMoveSet: ShowdownMoveset?): String {
return "useitem ${target.uuid} ${bagItem.itemName} ${bagItem.getShowdownInput(target.actor, target, data)}"
}
}
class ShowdownMoveset {
lateinit var moves: List<InBattleMove>
var trapped = false
@@ -240,6 +290,7 @@ class ShowdownPokemon {
lateinit var baseAbility: String
lateinit var pokeball: String
lateinit var ability: String
var reviving: Boolean = false
val uuid: UUID by lazy { UUID.fromString(details.split(",")[1].trim()) }
fun saveToBuffer(buffer: PacketByteBuf) {
@@ -247,6 +298,7 @@ class ShowdownPokemon {
buffer.writeString(details)
buffer.writeString(condition)
buffer.writeBoolean(active)
buffer.writeBoolean(reviving)
buffer.writeSizedInt(IntSize.U_BYTE, moves.size)
moves.forEach(buffer::writeString)
buffer.writeString(baseAbility)
@@ -259,6 +311,7 @@ class ShowdownPokemon {
details = buffer.readString()
condition = buffer.readString()
active = buffer.readBoolean()
reviving = buffer.readBoolean()
repeat(times = buffer.readSizedInt(IntSize.U_BYTE)) {
moves.add(buffer.readString())
}
@@ -9,6 +9,7 @@
package com.cobblemon.mod.common.battles
import com.cobblemon.mod.common.Cobblemon.LOGGER
import com.cobblemon.mod.common.CobblemonSounds
import com.cobblemon.mod.common.api.battles.interpreter.*
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
@@ -34,12 +35,7 @@ import com.cobblemon.mod.common.pokemon.evolution.progress.DamageTakenEvolutionP
import com.cobblemon.mod.common.pokemon.evolution.progress.RecoilEvolutionProgress
import com.cobblemon.mod.common.pokemon.evolution.progress.UseMoveEvolutionProgress
import com.cobblemon.mod.common.pokemon.status.PersistentStatus
import com.cobblemon.mod.common.util.asTranslated
import com.cobblemon.mod.common.util.battleLang
import com.cobblemon.mod.common.util.getPlayer
import com.cobblemon.mod.common.util.lang
import com.cobblemon.mod.common.util.runOnServer
import com.cobblemon.mod.common.util.swap
import com.cobblemon.mod.common.util.*
import java.util.UUID
import java.util.concurrent.CompletableFuture
import kotlin.math.roundToInt
@@ -74,6 +70,7 @@ object ShowdownInterpreter {
updateInstructions["|win|"] = this::handleWinInstruction
updateInstructions["|move|"] = this::handleMoveInstruction
updateInstructions["|cant|"] = this::handleCantInstruction
updateInstructions["|bagitem|"] = this::handleBagItemInstruction
updateInstructions["|-supereffective|"] = this::handleSuperEffectiveInstruction
updateInstructions["|-resisted|"] = this::handleResistInstruction
updateInstructions["|-crit"] = this::handleCritInstruction
@@ -155,7 +152,7 @@ object ShowdownInterpreter {
val boostBucket = if (isBoost) BattleContext.Type.BOOST else BattleContext.Type.UNBOOST
val context = getContextFromAction(message, boostBucket, battle)
// TODO: replace with context that tracks detailed information such as # of stages
repeat(stages) {pokemon.contextManager.add(context)}
repeat(stages) { pokemon.contextManager.add(context) }
battle.minorBattleActions[pokemon.uuid] = message
}
}
@@ -533,6 +530,24 @@ object ShowdownInterpreter {
}
}
/**
* Format:
* |bagitem|POKEMON|ITEMNAME
*
* POKEMON had ITEMNAME used on it from the 'bag'.
*/
private fun handleBagItemInstruction(battle: PokemonBattle, message: BattleMessage, remainingLines: MutableList<String>) {
battle.dispatchGo {
val pokemon = message.pokemonByUuid(0, battle)!!
val item = message.argumentAt(1)!!
val ownerName = pokemon.actor.getName()
val itemName = item.asTranslated()
battle.broadcastChatMessage(battleLang("bagitem.use", ownerName, itemName, pokemon.getName()))
}
}
/**
* Format:
* |win|USER
@@ -800,7 +815,7 @@ object ShowdownInterpreter {
private fun handleRechargeInstructions(battle: PokemonBattle, message: BattleMessage, remainingLines: MutableList<String>){
battle.dispatchWaiting(2F){
val pokemon = message.getBattlePokemon(0, battle) ?: return@dispatchWaiting
battle.broadcastChatMessage(battleLang("recharge", pokemon.getName() ?: ""))
battle.broadcastChatMessage(battleLang("recharge", pokemon.getName()))
battle.minorBattleActions[pokemon.uuid] = message
}
}
@@ -1210,11 +1225,12 @@ object ShowdownInterpreter {
val request = BattleRegistry.gson.fromJson(message.rawMessage.split("|request|")[1], ShowdownActionRequest::class.java)
if (battle.started) {
battle.dispatchGo {
// This request won't be acted on until the start of next turn
battleActor.sendUpdate(BattleQueueRequestPacket(request))
battleActor.request = request
battleActor.responses.clear()
// We need to send this out because 'upkeep' isn't received until the request is handled since the turn won't swap
if (request.forceSwitch.withIndex().any { it.value && battleActor.activePokemon.getOrNull(it.index)?.isGone() == false }) {
if (request.forceSwitch.contains(true)) {
battle.doWhenClear {
battleActor.mustChoose = true
battleActor.sendUpdate(BattleMakeChoicePacket())
@@ -1336,8 +1352,7 @@ object ShowdownInterpreter {
* The specified Pokémon POKEMON has taken damage, and is now at HP STATUS
*/
fun handleDamageInstruction(battle: PokemonBattle, actor: BattleActor, publicMessage: BattleMessage, privateMessage: BattleMessage) {
val (pnx, _) = publicMessage.pnxAndUuid(0) ?: return
val battlePokemon = privateMessage.getBattlePokemon(0, battle) ?: return
val battlePokemon = publicMessage.getBattlePokemon(0, battle) ?: return
if (privateMessage.optionalArgument("from")?.equals("recoil", true) == true) {
battlePokemon.effectedPokemon.let { pokemon ->
val recoilProgress = RecoilEvolutionProgress()
@@ -1403,7 +1418,8 @@ object ShowdownInterpreter {
GO
}
}
battle.sendSidedUpdate(actor, BattleHealthChangePacket(pnx, remainingHealth.toFloat()), BattleHealthChangePacket(pnx, newHealthRatio))
privateMessage.pnxAndUuid(0)?.let { (pnx, _) -> battle.sendSidedUpdate(actor, BattleHealthChangePacket(pnx, remainingHealth.toFloat()), BattleHealthChangePacket(pnx, newHealthRatio)) }
battle.minorBattleActions[battlePokemon.uuid] = privateMessage
WaitDispatch(1F)
}
@@ -1499,6 +1515,9 @@ object ShowdownInterpreter {
battlePokemon.heldItemManager.handleEndInstruction(battlePokemon, battle, message)
battle.minorBattleActions[battlePokemon.uuid] = message
battlePokemon.contextManager.remove(item.id, BattleContext.Type.ITEM)
if (message.hasOptionalArgument("eat")) {
battlePokemon.entity?.playSound(CobblemonSounds.BERRY_EAT, 1F, 1F)
}
}
}
@@ -1509,7 +1528,7 @@ object ShowdownInterpreter {
* The specified Pokémon POKEMON has healed damage, and is now at HP STATUS.
*/
private fun handleHealInstruction(battle: PokemonBattle, actor: BattleActor, publicMessage: BattleMessage, privateMessage: BattleMessage) {
val (pnx, _) = privateMessage.pnxAndUuid(0) ?: return
val pnx = privateMessage.pnxAndUuid(0)?.first
val battlePokemon = privateMessage.getBattlePokemon(0, battle) ?: return
val rawHpAndStatus = privateMessage.argumentAt(1)?.split(" ") ?: return
val rawHpRatio = rawHpAndStatus.getOrNull(0) ?: return
@@ -1520,7 +1539,9 @@ object ShowdownInterpreter {
broadcastOptionalAbility(battle, effect, pokemonName)
battle.dispatchWaiting {
battle.sendSidedUpdate(actor, BattleHealthChangePacket(pnx, newHealth.toFloat()), BattleHealthChangePacket(pnx, newHealthRatio))
if (pnx != null) {
battle.sendSidedUpdate(actor, BattleHealthChangePacket(pnx, newHealth.toFloat()), BattleHealthChangePacket(pnx, newHealthRatio))
}
val silent = privateMessage.hasOptionalArgument("silent")
if (!silent) {
val lang = when {
@@ -1547,7 +1568,9 @@ object ShowdownInterpreter {
}
}
}
else -> battleLang("heal.generic", battlePokemon.getName())
else -> {
battleLang("heal.generic", battlePokemon.getName())
}
}
battle.broadcastChatMessage(lang)
}
@@ -1559,7 +1582,9 @@ object ShowdownInterpreter {
val status = Statuses.getStatus(rawStatus) ?: return@dispatchWaiting
if (status is PersistentStatus) {
battlePokemon.effectedPokemon.applyStatus(status)
battle.sendUpdate(BattlePersistentStatusPacket(pnx, status))
if (pnx != null) {
battle.sendUpdate(BattlePersistentStatusPacket(pnx, status))
}
if (!silent) {
status.applyMessage.let { battle.broadcastChatMessage(it.asTranslated(battlePokemon.getName())) }
}
@@ -1593,7 +1618,7 @@ object ShowdownInterpreter {
/**
* Format:
* |-clearallboost
* |-clearallboost|
*
* Clears all boosts from all Pokémon on both sides.
*/
@@ -17,19 +17,19 @@ class ShowdownThread : Thread("Cobblemon Showdown") {
private val latch = CountDownLatch(1)
private val whenReady : Queue<Runnable> = LinkedList()
private val whenReady : Queue<(ShowdownService) -> Unit> = LinkedList()
fun launch() {
this.start()
this.latch.await()
for (action in whenReady) {
action.run()
action(ShowdownService.service)
}
}
fun queue(action: Runnable) {
fun queue(action: (ShowdownService) -> Unit) {
if (this.latch.count == 0L) {
action.run()
action(ShowdownService.service)
} else {
this.whenReady.add(action)
}
@@ -37,7 +37,7 @@ class ShowdownThread : Thread("Cobblemon Showdown") {
override fun run() {
LOGGER.info("Starting showdown service...")
ShowdownService.get().openConnection()
ShowdownService.service.openConnection()
LOGGER.info("Showdown has been started!")
this.latch.countDown()
}
@@ -8,6 +8,7 @@
package com.cobblemon.mod.common.battles.pokemon
import com.bedrockk.molang.runtime.struct.VariableStruct
import com.cobblemon.mod.common.api.battles.model.actor.BattleActor
import com.cobblemon.mod.common.api.moves.MoveSet
import com.cobblemon.mod.common.api.pokemon.helditem.HeldItemManager
@@ -89,4 +90,8 @@ open class BattlePokemon(
fun isSentOut() = actor.battle.activePokemon.any { it.battlePokemon == this }
fun canBeSentOut() = !isSentOut() && !willBeSwitchedIn && health > 0
fun writeVariables(struct: VariableStruct) {
effectedPokemon.writeVariables(struct)
}
}
@@ -10,9 +10,8 @@ package com.cobblemon.mod.common.battles.runner
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.battles.runner.graal.GraalShowdownService
import com.cobblemon.mod.common.battles.runner.socket.SocketShowdownService
import com.google.gson.JsonArray
import java.util.*
import java.util.UUID
/**
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service.
@@ -32,13 +31,11 @@ interface ShowdownService {
fun getMoves(): JsonArray
fun getItemIds(): JsonArray
fun registerSpecies()
fun registerBagItems()
fun indicateSpeciesInitialized() {}
companion object {
private var service: ShowdownService? = null
fun get(): ShowdownService {
if (service == null) service = GraalShowdownService()
return service!!
}
val service: ShowdownService by lazy { GraalShowdownService() }
}
}
@@ -11,16 +11,28 @@ package com.cobblemon.mod.common.battles.runner.graal
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.battles.BagItems
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.google.gson.Gson
import com.google.gson.JsonArray
import java.io.File
import java.io.IOException
import java.net.URI
import java.nio.file.AccessMode
import java.nio.file.DirectoryStream
import java.nio.file.LinkOption
import java.nio.file.OpenOption
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.FileAttribute
import java.util.UUID
import org.graalvm.polyglot.Context
import org.graalvm.polyglot.HostAccess
import org.graalvm.polyglot.HostAccess.Export
import org.graalvm.polyglot.PolyglotAccess
import org.graalvm.polyglot.Value
import java.io.File
import java.util.*
import org.graalvm.polyglot.io.FileSystem
/**
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service via
@@ -49,13 +61,38 @@ class GraalShowdownService : ShowdownService {
}
private fun createContext() {
val access = HostAccess.newBuilder(HostAccess.ALL).build()
val wd = Paths.get("./showdown")
val access = HostAccess.newBuilder(HostAccess.EXPLICIT)
.allowIterableAccess(true)
.allowArrayAccess(true)
.allowListAccess(true)
.allowMapAccess(true)
.build()
context = Context.newBuilder("js")
.allowIO(true)
.fileSystem(object : FileSystem
{
val default = FileSystem.newDefaultFileSystem()
override fun parsePath(uri: URI) = default.parsePath(uri)
override fun parsePath(path: String) = default.parsePath(path)
override fun createDirectory(dir: Path, vararg attrs: FileAttribute<*>) = default.createDirectory(dir, *attrs)
override fun delete(path: Path) = default.delete(path)
override fun newByteChannel(path: Path, options: MutableSet<out OpenOption>, vararg attrs: FileAttribute<*>) = default.newByteChannel(path, options, *attrs)
override fun newDirectoryStream(dir: Path, filter: DirectoryStream.Filter<in Path>) = default.newDirectoryStream(dir, filter)
override fun toAbsolutePath(path: Path) = default.toAbsolutePath(path)
override fun toRealPath(path: Path, vararg linkOptions: LinkOption) = default.toRealPath(path, *linkOptions)
override fun readAttributes(path: Path, attributes: String, vararg options: LinkOption) = default.readAttributes(path, attributes, *options)
override fun checkAccess(path: Path, modes: MutableSet<out AccessMode>, vararg linkOptions: LinkOption) {
if (!path.toRealPath(LinkOption.NOFOLLOW_LINKS).startsWith(wd.toRealPath(LinkOption.NOFOLLOW_LINKS))) {
Cobblemon.LOGGER.error("Hacked JS files in datapacks or some weird file system setup that Hiroku failed to anticipate.")
throw IOException("Someone has put hacked JS files into datapacks because file access is being attempted outside of controlled folders.")
}
}
}
)
.allowExperimentalOptions(true)
.allowPolyglotAccess(PolyglotAccess.ALL)
.allowHostAccess(access)
.allowAllAccess(true)
.allowCreateThread(true)
.logHandler(GraalLogger)
.option("engine.WarnInterpreterOnly", "false")
@@ -130,14 +167,28 @@ class GraalShowdownService : ShowdownService {
receiveSpeciesDataFn.execute(jsArray)
}
override fun indicateSpeciesInitialized() {
val afterCobbledSpeciesInitFn = this.context.getBindings("js").getMember("afterCobbledSpeciesInit")
afterCobbledSpeciesInitFn.execute()
}
override fun registerBagItems() {
val receiveBagItemDataFn = this.context.getBindings("js").getMember("receiveBagItemData")
for ((itemId, js) in BagItems.bagItemsScripts) {
receiveBagItemDataFn.execute(itemId, js.replace("\n", " "))
}
}
private fun sendToShowdown(battleId: UUID, messages: Array<String>) {
sendBattleMessageFunction.execute(battleId.toString(), messages)
}
@Export
fun sendFromShowdown(battleId: String, message: String) {
ShowdownInterpreter.interpretMessage(UUID.fromString(battleId), message)
}
@Export
fun log(message: String) {
Cobblemon.LOGGER.info(message)
}
@@ -11,6 +11,7 @@ package com.cobblemon.mod.common.battles.runner.socket
import com.cobblemon.mod.common.Cobblemon
import com.cobblemon.mod.common.api.battles.model.PokemonBattle
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.battles.BagItems
import com.cobblemon.mod.common.battles.ShowdownInterpreter
import com.cobblemon.mod.common.battles.runner.ShowdownService
import com.cobblemon.mod.common.pokemon.FormData
@@ -23,7 +24,7 @@ import java.io.OutputStreamWriter
import java.net.InetAddress
import java.net.Socket
import java.nio.charset.Charset
import java.util.*
import java.util.UUID
/**
* Mediator service for communicating between the Cobblemon Minecraft mod and Cobblemon showdown service via
@@ -60,7 +61,7 @@ class SocketShowdownService(val host: String = "localhost", val port: Int = 1846
override fun startBattle(battle: PokemonBattle, messages: Array<String>) {
writer.write(">startbattle ${battle.battleId}\n")
writer.flush()
acknowledge { Cobblemon.LOGGER.error("Failed to start battle!") }
send(battle.battleId, messages)
}
@@ -102,7 +103,7 @@ class SocketShowdownService(val host: String = "localhost", val port: Int = 1846
}
override fun getAbilityIds(): JsonArray {
writer.write(">getCobbledAbilityIds\n")
writer.write(">getCobbledAbilityIds")
writer.flush()
val response = readMessage()
return gson.fromJson(response, JsonArray::class.java)
@@ -116,7 +117,7 @@ class SocketShowdownService(val host: String = "localhost", val port: Int = 1846
}
override fun getItemIds(): JsonArray {
writer.write(">getCobbledItemIds\n")
writer.write(">getCobbledItemIds")
writer.flush()
val response = readMessage()
return gson.fromJson(response, JsonArray::class.java)
@@ -124,14 +125,17 @@ class SocketShowdownService(val host: String = "localhost", val port: Int = 1846
private fun sendSpeciesData(species: Species, form: FormData?) {
writer.write(">receiveSpeciesData ${gson.toJson(PokemonSpecies.ShowdownSpecies(species, form))}\n")
writer.flush()
val ack = CharArray(3)
reader.read(ack) // Wait for showdown to acknowledge.
assert(String(ack) == "ACK")
acknowledge()
}
private fun sendBagItem(itemId: String, js: String) {
writer.write(">receiveBagItemData $itemId $js")
acknowledge { Cobblemon.LOGGER.error("Failed to send bag item to Showdown: $itemId") }
}
override fun registerSpecies() {
writer.write(">resetSpeciesData\n")
acknowledge()
PokemonSpecies.species.forEach { species ->
sendSpeciesData(species, null)
species.forms.forEach { form ->
@@ -141,4 +145,25 @@ class SocketShowdownService(val host: String = "localhost", val port: Int = 1846
}
}
}
fun acknowledge(ifFails: () -> Unit = {}) {
writer.flush()
val ack = CharArray(3)
reader.read(ack)
if (String(ack) != "ACK") {
ifFails()
}
}
override fun registerBagItems() {
for ((itemId, js) in BagItems.bagItemsScripts) {
sendBagItem(itemId, js.replace("\n", " "))
}
}
override fun indicateSpeciesInitialized() {
writer.write(">afterCobbledSpeciesInit")
acknowledge()
}
}
@@ -0,0 +1,56 @@
/*
* Copyright (C) 2023 Cobblemon Contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.cobblemon.mod.common.berry
import com.cobblemon.mod.common.api.berry.GrowthFactor
import com.cobblemon.mod.common.util.cobblemonResource
import net.minecraft.block.BlockState
import net.minecraft.predicate.NumberRange
import net.minecraft.util.math.BlockPos
import net.minecraft.world.WorldView
import net.minecraft.world.biome.Biome
/**
* A [GrowthFactor] that is active based on the downfall property of a [Biome].
*
* @property range The range of possible [Biome.getDownfall] values.
* @property bonusYield The range of possible bonus values.
*
* @author Licious
* @since December 2nd, 2022
*/
class BiomeDownfallGrowthFactor(
val range: NumberRange.FloatRange,
val bonusYield: IntRange
) : GrowthFactor {
override fun validateArguments() {
if (this.bonusYield.first < 0 || this.bonusYield.last < 0) {
throw IllegalArgumentException("$ID bonusYield must be a positive range")
}
}
override fun isValid(world: WorldView, state: BlockState, pos: BlockPos): Boolean {
val biome = world.getBiome(pos).value()
return this.range.test(biome.weather.downfall.toDouble())
}
override fun yield() = this.bonusYield.random()
override fun minYield() = this.bonusYield.first
override fun maxYield() = this.bonusYield.last
companion object {
val ID = cobblemonResource("biome_downfall")
}
}
Loaded 100 of 1295 files, more files were not shown because too many files have changed in this diff. Show more