Add standalone lobby House selector and key-backed Mentat welcome
This commit is contained in:
parent
49a0a1d571
commit
51f67bd1ba
3 changed files with 568 additions and 5 deletions
|
|
@ -0,0 +1,5 @@
|
|||
package com.dunerealms.gui;
|
||||
final class DepartureWindow {
|
||||
private DepartureWindow(){}
|
||||
static long remaining(long epochSeconds){return 900-Math.floorMod(epochSeconds,900);}
|
||||
}
|
||||
129
DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java
Normal file
129
DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
package com.dunerealms.gui;
|
||||
|
||||
import com.example.dunegui.MenuSession;
|
||||
import com.example.dunegui.NativeMenus;
|
||||
import com.google.gson.*;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.boss.*;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.inventory.*;
|
||||
import org.bukkit.event.player.*;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import java.io.File;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Lobby presentation only. Character authority and committed keys remain central. */
|
||||
public final class DuneGUI extends JavaPlugin implements Listener,CommandExecutor {
|
||||
private HouseBridge bridge;
|
||||
private final Map<UUID,UUID> requests=new HashMap<>();
|
||||
private final Map<UUID,JsonObject> records=new HashMap<>();
|
||||
private BossBar departure;
|
||||
private NamespacedKey registrar;
|
||||
static final int[] CENTRES={10,13,16,29,33};
|
||||
static final String[] IDS={"atreides","harkonnen","corrino","ordos","fremen"};
|
||||
private static final Set<String> HOUSE_IDS=Set.of(IDS);
|
||||
private static final class Screen implements InventoryHolder {
|
||||
final UUID owner;final MenuSession gate;final Map<Integer,Runnable> actions=new HashMap<>();Inventory inventory;
|
||||
Screen(Player player){owner=player.getUniqueId();gate=new MenuSession(owner);}
|
||||
public Inventory getInventory(){return inventory;}
|
||||
}
|
||||
@Override public void onEnable(){
|
||||
bridge=new HouseBridge(new File(getDataFolder().getParentFile(),"DuneEss/website-bridge.yml"));
|
||||
registrar=new NamespacedKey(this,"house_registrar");
|
||||
for(String command:List.of("house","mentat","drgui"))Objects.requireNonNull(getCommand(command)).setExecutor(this);
|
||||
getServer().getPluginManager().registerEvents(this,this);
|
||||
departure=Bukkit.createBossBar("Spacing Guild · next Imperial departure",BarColor.YELLOW,BarStyle.SOLID);
|
||||
Bukkit.getScheduler().runTaskTimer(this,this::tick,20L,20L);
|
||||
Bukkit.getScheduler().runTaskLater(this,this::ensureRegistrar,40L);
|
||||
getLogger().info("House selector and Mentat screens enabled; central J.A.R.V.I.S. bridge; no Core/Lobby replacement.");
|
||||
}
|
||||
@Override public void onDisable(){requests.clear();records.clear();if(departure!=null)departure.removeAll();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Screen)p.closeInventory();}
|
||||
private boolean lobby(Player p){return p.getWorld().getName().equals("guild_lobby");}
|
||||
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
|
||||
if(!(sender instanceof Player p))return true;if(!lobby(p)){p.sendMessage("This service is available in the Spacing Guild lobby.");return true;}
|
||||
fetch(p,null,0,null,data->{if(command.getName().equals("mentat")&&selection(data)!=null)mentat(p,data);else select(p,data,null);});return true;
|
||||
}
|
||||
private void fetch(Player p,String house,int version,UUID requestId,Consumer<JsonObject> callback){
|
||||
UUID owner=p.getUniqueId();if(requests.containsKey(owner)){p.sendMessage("The House register is processing your request.");return;}
|
||||
UUID operation=UUID.randomUUID();requests.put(owner,operation);p.closeInventory();p.sendMessage(Component.text(house==null?"Reading your House key…":"Confirming your House key…",NamedTextColor.GOLD));
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this,()->{
|
||||
JsonObject result=null;String error=null;
|
||||
try{result=bridge.request(owner,house,version,requestId);}catch(Exception unavailable){error=unavailable instanceof java.io.IOException?unavailable.getMessage():"The House register is unavailable. Please retry.";}
|
||||
JsonObject received=result;String failure=error;if(!isEnabled())return;
|
||||
Bukkit.getScheduler().runTask(this,()->{if(!operation.equals(requests.get(owner)))return;requests.remove(owner);if(!p.isOnline()||!lobby(p))return;
|
||||
if(received==null){p.sendMessage(Component.text(failure,NamedTextColor.RED));return;}
|
||||
records.put(owner,received);callback.accept(received);
|
||||
});
|
||||
});
|
||||
}
|
||||
static String selection(JsonObject data){if(!data.has("selection")||data.get("selection").isJsonNull())return null;String value=data.get("selection").getAsString();return HOUSE_IDS.contains(value)?value:null;}
|
||||
private String houseName(JsonObject data,String id){for(var entry:data.getAsJsonArray("choices")){var h=entry.getAsJsonObject();if(h.get("id").getAsString().equals(id))return h.get("name").getAsString();}throw new IllegalArgumentException("Unknown House");}
|
||||
private void select(Player p,JsonObject data,String picked){
|
||||
String current=selection(data),chosen=picked!=null?picked:current;
|
||||
if(NativeMenus.isBedrock(p)){
|
||||
List<NativeMenus.Choice> choices=new ArrayList<>();
|
||||
for(var entry:data.getAsJsonArray("choices")){var house=entry.getAsJsonObject();String id=house.get("id").getAsString();if(!HOUSE_IDS.contains(id))continue;
|
||||
choices.add(new NativeMenus.Choice(house.get("name").getAsString()+(id.equals(current)?" · Your House":""),"Review and confirm allegiance",()->confirmForm(p,data,id),"https://www.dunerealms.com/assets/seals/"+house.get("seal").getAsString()));
|
||||
}
|
||||
NativeMenus.show(this,p,"Choose your House","Declare your allegiance. Review a House before confirming.",choices);return;
|
||||
}
|
||||
Screen screen=screen(p,"Choose your House",0xE300+(chosen==null?0:Arrays.asList(IDS).indexOf(chosen)+1));
|
||||
for(int i=0;i<IDS.length;i++){String id=IDS[i];int centre=CENTRES[i];boolean selected=id.equals(chosen);
|
||||
var item=icon(p,houseName(data,id),selected?"Selected · confirm below":"Click to select this House","drgui_transparent",Material.PAPER);
|
||||
for(int row=i<3?-1:0;row<=1;row++)for(int col=-1;col<=1;col++){int slot=centre+row*9+col;screen.inventory.setItem(slot,item.clone());screen.actions.put(slot,()->select(p,data,id));}
|
||||
}
|
||||
button(screen,p,45,"Close","Return to the lobby",Material.ARROW,p::closeInventory);
|
||||
if(chosen!=null)button(screen,p,53,"Confirm "+houseName(data,chosen),"Write your confirmed House key",Material.LIME_DYE,()->confirm(p,data,chosen));
|
||||
screen.actions.put(46,screen.actions.get(45));if(chosen!=null)screen.actions.put(52,screen.actions.get(53));
|
||||
p.openInventory(screen.inventory);expire(screen);
|
||||
}
|
||||
private void confirmForm(Player p,JsonObject data,String id){NativeMenus.show(this,p,"Confirm House · "+houseName(data,id),"Confirm your allegiance to "+houseName(data,id)+". This initial selection does not grant an elected office.",List.of(new NativeMenus.Choice("Confirm House","Save through J.A.R.V.I.S.",()->confirm(p,data,id)),new NativeMenus.Choice("Back","Review all five Houses",()->select(p,data,id))));}
|
||||
private void confirm(Player p,JsonObject data,String id){
|
||||
if(id.equals(selection(data))&&data.has("keyId")&&!data.get("keyId").isJsonNull()){mentat(p,data);return;}
|
||||
fetch(p,id,data.get("version").getAsInt(),UUID.randomUUID(),saved->{p.sendMessage(Component.text("House allegiance confirmed in J.A.R.V.I.S.",NamedTextColor.GREEN));mentat(p,saved);});
|
||||
}
|
||||
private void mentat(Player p,JsonObject data){
|
||||
String house=selection(data);if(house==null){select(p,data,null);return;}
|
||||
JsonObject mentor=data.getAsJsonObject("mentat");String name=mentor.get("name").getAsString();int index=Arrays.asList(IDS).indexOf(house);
|
||||
if(NativeMenus.isBedrock(p)){NativeMenus.show(this,p,"Your Mentat · "+name,houseName(data,house)+"\nYour House briefing is ready.",List.of(new NativeMenus.Choice("Open Mentat Report","Open your website mission journal",()->report(p),"https://www.dunerealms.com/assets/gui/mentat-"+house+"-v1.png"),new NativeMenus.Choice("Return to lobby","Continue your journey",p::closeInventory)));return;}
|
||||
Screen screen=screen(p,"Your Mentat · "+name,0xE310+index);
|
||||
screen.inventory.setItem(13,icon(p,name,houseName(data,house),"drgui_transparent",Material.PLAYER_HEAD));
|
||||
button(screen,p,38,"Open Mentat Report","Personal level, Reputation and active quests",Material.WRITABLE_BOOK,()->report(p));
|
||||
button(screen,p,42,"Return to lobby","Continue your journey",Material.COMPASS,p::closeInventory);
|
||||
button(screen,p,45,"Your House",houseName(data,house),Material.ARROW,()->select(p,data,house));
|
||||
for(int slot:new int[]{37,39})screen.actions.put(slot,screen.actions.get(38));for(int slot:new int[]{41,43})screen.actions.put(slot,screen.actions.get(42));screen.actions.put(46,screen.actions.get(45));
|
||||
p.openInventory(screen.inventory);expire(screen);
|
||||
}
|
||||
private void report(Player p){p.closeInventory();p.sendMessage(Component.text("Open your Mentat Report →",NamedTextColor.GOLD).clickEvent(net.kyori.adventure.text.event.ClickEvent.openUrl("https://clans.dunerealms.com/#quests/quests")));}
|
||||
private Screen screen(Player p,String title,int glyph){Screen s=new Screen(p);Component heading=p.hasResourcePack()?Component.text("\uE32F"+(char)glyph,NamedTextColor.WHITE).font(Key.key("dunerealms:house_selector")):Component.text(title,NamedTextColor.GOLD);s.inventory=Bukkit.createInventory(s,54,heading);return s;}
|
||||
private ItemStack icon(Player p,String title,String description,String model,Material fallback){ItemStack item=new ItemStack(p.hasResourcePack()?Material.PAPER:fallback);var meta=item.getItemMeta();meta.displayName(Component.text(title,NamedTextColor.GOLD));meta.lore(List.of(Component.text(description,NamedTextColor.GRAY)));if(p.hasResourcePack())meta.setItemModel(new NamespacedKey("dunerealms",model));item.setItemMeta(meta);return item;}
|
||||
private void button(Screen s,Player p,int slot,String title,String description,Material material,Runnable action){s.inventory.setItem(slot,icon(p,title,description,"drgui_transparent",material));s.actions.put(slot,action);}
|
||||
private void expire(Screen screen){Bukkit.getScheduler().runTaskLater(this,screen.gate::expire,2400L);}
|
||||
@EventHandler public void click(InventoryClickEvent event){if(!(event.getView().getTopInventory().getHolder() instanceof Screen s))return;event.setCancelled(true);
|
||||
if(!(event.getWhoClicked() instanceof Player p)||!p.getUniqueId().equals(s.owner)||event.getClickedInventory()!=s.inventory||event.getClick()!=ClickType.LEFT)return;
|
||||
Runnable action=s.actions.get(event.getRawSlot());if(action==null||!s.gate.claim(p.getUniqueId()))return;
|
||||
Bukkit.getScheduler().runTask(this,()->{if(p.isOnline()&&lobby(p)&&p.getOpenInventory().getTopInventory()==s.inventory)action.run();});
|
||||
}
|
||||
@EventHandler public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Screen)e.setCancelled(true);}
|
||||
@EventHandler public void close(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Screen s)s.gate.expire();}
|
||||
@EventHandler public void quit(PlayerQuitEvent e){requests.remove(e.getPlayer().getUniqueId());records.remove(e.getPlayer().getUniqueId());departure.removePlayer(e.getPlayer());}
|
||||
private void ensureRegistrar(){World world=Bukkit.getWorld("guild_lobby");if(world==null)return;Location at=world.getSpawnLocation().clone().add(2,0,0);at.getChunk().load();
|
||||
for(Entity entity:world.getEntities())if(entity.getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return;
|
||||
Villager npc=world.spawn(at,Villager.class);npc.setAI(false);npc.setInvulnerable(true);npc.setPersistent(true);npc.setSilent(true);npc.setCollidable(false);npc.setProfession(Villager.Profession.LIBRARIAN);npc.customName(Component.text("House Registrar · Choose your House",NamedTextColor.GOLD));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(registrar,PersistentDataType.BYTE,(byte)1);
|
||||
}
|
||||
@EventHandler public void npc(PlayerInteractEntityEvent e){if(!e.getRightClicked().getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return;e.setCancelled(true);if(e.getHand()!=EquipmentSlot.HAND||!lobby(e.getPlayer()))return;fetch(e.getPlayer(),null,0,null,data->{if(selection(data)!=null)mentat(e.getPlayer(),data);else select(e.getPlayer(),data,null);});}
|
||||
private void tick(){
|
||||
long remaining=DepartureWindow.remaining(Instant.now().getEpochSecond());departure.setTitle("Spacing Guild · Imperial departure window in "+String.format(Locale.ROOT,"%02d:%02d",remaining/60,remaining%60));departure.setProgress(remaining/900.0);
|
||||
for(World world:Bukkit.getWorlds())if(world.getName().equals("guild_lobby")){var battle=world.getEnderDragonBattle();if(battle!=null&&battle.getBossBar()!=null){battle.getBossBar().setVisible(false);battle.getBossBar().removeAll();}}
|
||||
for(Player p:Bukkit.getOnlinePlayers())if(lobby(p)){if(!departure.getPlayers().contains(p))departure.addPlayer(p);}else departure.removePlayer(p);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package com.dunerealms.gui;
|
||||
|
||||
import com.google.gson.*;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.net.http.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Uses the existing private game bridge credential. Never logs it or returns codes. */
|
||||
final class HouseBridge {
|
||||
private final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
|
||||
private final File config;
|
||||
HouseBridge(File config){this.config=config;}
|
||||
JsonObject request(UUID player,String faction,int version,UUID requestId) throws Exception {
|
||||
var settings=YamlConfiguration.loadConfiguration(config);
|
||||
String origin=settings.getString("origin",""),secret=settings.getString("secret","");
|
||||
if(!origin.equals("https://cp.dunerealms.com")||secret.length()<32)throw new IOException("House bridge unavailable");
|
||||
JsonObject data=new JsonObject();data.addProperty("action",faction==null?"read":"choose");data.addProperty("uuid",player.toString());
|
||||
if(faction!=null){data.addProperty("faction",faction);data.addProperty("version",version);data.addProperty("confirmed",true);data.addProperty("requestId",requestId.toString());}
|
||||
var req=HttpRequest.newBuilder(URI.create(origin+"/internal/game/house")).timeout(Duration.ofSeconds(10)).header("Authorization","Bearer "+secret).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(data.toString())).build();
|
||||
var response=http.send(req,HttpResponse.BodyHandlers.ofInputStream());
|
||||
byte[] body;try(var in=response.body()){body=in.readNBytes(32769);}
|
||||
if(body.length>32768)throw new IOException("House response too large");
|
||||
JsonObject result=JsonParser.parseString(new String(body,StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
if(response.statusCode()!=200)throw new IOException(response.statusCode()==403?"Link your personal Minecraft account at cp.dunerealms.com first.":response.statusCode()==409?"Your House record changed. Reopen the menu.":"The House register is temporarily unavailable. Please retry.");
|
||||
if(!result.has("ok")||!result.get("ok").getAsBoolean()||!result.has("choices")||result.getAsJsonArray("choices").size()!=5)throw new IOException("Invalid House response");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff