Skip to content

Commit

Permalink
fix okay messages, fix and extend DeckJSONBuilder
Browse files Browse the repository at this point in the history
 - BackendBroadcaster

   - added switch to allow it to resend messages even when they're the same
     as the previous one - useful for sending repeating okay messages

 - DeckJSONBuilder

   - added character
   - keywords are now stored and sent properly, the same way as power tips
   - take empty name and descriptions into account
   - encode card type, rarity, color
   - add timesUpgraded
  • Loading branch information
avolny committed Apr 21, 2020
1 parent a95f89e commit d2737ae
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 56 deletions.
15 changes: 9 additions & 6 deletions src/main/java/str_exporter/BackendBroadcaster.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public class BackendBroadcaster {

public static final Logger logger = LogManager.getLogger(BackendBroadcaster.class.getName());

// private static final String EBS_URL = "https://localhost:8081";
private static final String EBS_URL = "https://slaytherelics.xyz:8081";
private static final String EBS_URL = "https://localhost:8081";
// private static final String EBS_URL = "https://slaytherelics.xyz:8081";

// private static final long CHECK_QUEUE_PERIOD_MILLIS = 100;
// private static BackendBroadcaster instance = new BackendBroadcaster();
Expand All @@ -29,9 +29,11 @@ public class BackendBroadcaster {
private ReentrantLock queueLock;
private Thread worker;
private long checkQueuePeriodMillis;
private boolean sendDuplicates;

public BackendBroadcaster(long checkQueuePeriodMillis) {
public BackendBroadcaster(long checkQueuePeriodMillis, boolean sendDuplicates) {
this.checkQueuePeriodMillis = checkQueuePeriodMillis;
this.sendDuplicates = sendDuplicates;
message = null;
lastMessage = null;
queueLock = new ReentrantLock();
Expand All @@ -52,6 +54,7 @@ public BackendBroadcaster(long checkQueuePeriodMillis) {
}

public void queueMessage(String msg) {
// queues only if the new message differs from the last one
queueLock.lock();
try {
if (message == null || !message.equals(msg)) {
Expand All @@ -68,7 +71,7 @@ private void readQueue() {
long ts = 0;
queueLock.lock();
try {
if (message != null && !message.equals(lastMessage)) {
if ((sendDuplicates || !message.equals(lastMessage)) && message != null) {
lastMessage = message;
msg = message;
ts = messageTimestamp;
Expand All @@ -90,7 +93,7 @@ private static String injectDelayToMessage(String msg, long delay) {
return msg.replace(DELAY_PLACEHOLDER, Long.toString(delay));
}

public void broadcastMessage(String msg) {
private void broadcastMessage(String msg) {

try {
URL url = new URL(EBS_URL);
Expand All @@ -113,7 +116,7 @@ public void broadcastMessage(String msg) {

if (!response.toString().equals("Success"))
logger.info("message not broadcasted succesfully, response: " + response.toString());
// logger.info("broadcasted message, response: " + response.toString());
logger.info("broadcasted message, response: " + response.toString());

} catch (Exception e) {
e.printStackTrace();
Expand Down
123 changes: 86 additions & 37 deletions src/main/java/str_exporter/DeckJSONBuilder.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package str_exporter;

import basemod.BaseMod;
import basemod.abstracts.CustomCard;
import basemod.abstracts.DynamicVariable;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
Expand All @@ -22,58 +21,76 @@ public class DeckJSONBuilder extends JSONMessageBuilder{

public static final Logger logger = LogManager.getLogger(TipsJSONBuilder.class.getName());

private ArrayList<String> keywords;

public DeckJSONBuilder(String login, String secret, String version) {
super(login, secret, version, 4);

keywords = new ArrayList<>();

TEXT = CardCrawlGame.languagePack.getUIString("TipHelper").TEXT;
}

@Override
protected void buildMessage(StringBuilder sb) {
String character = "";

if (CardCrawlGame.isInARun() && CardCrawlGame.dungeon != null && CardCrawlGame.dungeon.player != null) {
character = CardCrawlGame.dungeon.player.getClass().getSimpleName();
}

sb.append("{");
sb.append("\"c\":\"").append(character).append("\","); // character

keywords.clear();
StringBuilder sb_message = new StringBuilder();
boolean nonempty = buildCards(sb_message);
sb_message.append(nonempty ? ";": ";;;"); // ;;; delimits cards from keywords
buildKeywords(sb_message);

sb.append("\"k\":\""); // deck
sb.append(sb_message.toString());
sb.append(StringCompression.compress(sb_message.toString()));
sb.append("\"}");
}

private void buildKeywords(StringBuilder sb) {
HashSet<String> keywords = new HashSet<>();
Iterator<String> iter = keywords.iterator();

if (CardCrawlGame.isInARun()) {
CardGroup deck = CardCrawlGame.dungeon.player.masterDeck;
while(iter.hasNext()) {
sb.append(iter.next());

for (int i = 0; i < deck.group.size(); i++) {
for (String keyword : deck.group.get(i).keywords) {
keywords.add(keyword);
}
}
if(iter.hasNext())
sb.append(";;");
}
}

Iterator<String> iter = keywords.iterator();
private String getKeywordRepr(String word) {
StringBuilder sb = new StringBuilder();

while(iter.hasNext()) {
String word = iter.next();
if (word.equals("[R]") || word.equals("[G]") || word.equals("[B]") || word.equals("[W]") || word.equals("[E]")) {
sb.append(sanitize(word));
sb.append(' ');
sb.append(TEXT[0]); // word Energy
} else {
sb.append(sanitize(BaseMod.getKeywordTitle(word)));
}

if (word.equals("[R]") || word.equals("[G]") || word.equals("[B]") || word.equals("[W]") || word.equals("[E]")) {
sb.append(word);
sb.append(' ');
sb.append(TEXT[0]); // word Energy
} else {
sb.append(BaseMod.getKeywordTitle(word));
}
sb.append(";");
sb.append(sanitize(BaseMod.getKeywordDescription(word)));

sb.append(";");
sb.append(BaseMod.getKeywordDescription(word));
return sb.toString();
}

if(iter.hasNext())
sb.append(";;");
private int getKeywordIndex(String keyword) {
String keywordRepr = getKeywordRepr(keyword);

int index = keywords.indexOf(keywordRepr);

if (index >= 0)
return index;
else {
keywords.add(keywordRepr);
return keywords.size() - 1;
}
}

Expand All @@ -96,36 +113,67 @@ private boolean buildCards(StringBuilder sb) {
}

private void buildCard(StringBuilder sb, AbstractCard card) {

String name = sanitize(card.name);
String desc = parseDescription(card);
int timesUpgraded = card.timesUpgraded;
int cost = card.cost;

if (timesUpgraded > 0) {
name = colorizeString(name, "#g");
}
if (name.isEmpty())
name = "-";

if (desc.isEmpty())
desc = "-";

// if (timesUpgraded > 0) {
// name = colorizeString(name, "#g");
// }

// name ; type ; rarity ; color ; cost ; upgrades ; description ; img path ; keywords

sb.append(name);
sb.append(";");
sb.append(encodeCardType(card));
sb.append(";");
sb.append(encodeCardRarity(card));
sb.append(";");
sb.append(encodeCardColor(card));
sb.append(";");
sb.append(cost);
sb.append(";");
sb.append(timesUpgraded);
sb.append(';');
sb.append(desc);
sb.append(';');
sb.append(getImgPath(card));
}

private String getImgPath(AbstractCard card) {
if (card instanceof CustomCard) {
String[] parts = ((CustomCard) card).textureImg.split("/");

return parts[0] + "/" + parts[parts.length - 1];
if (card.keywords.size() == 0) {
sb.append('-');
} else {
// could remove text
return card.assetUrl + ".png";
Iterator<String> iter = card.keywords.iterator();

while(iter.hasNext()) {
sb.append(getKeywordIndex(iter.next()));

if (iter.hasNext())
sb.append(',');
}
}
}

private String encodeCardType(AbstractCard card) {
int ord = card.type.ordinal();
return ord > 4 ? card.type.toString() : Integer.toString(ord);
}

private String encodeCardRarity(AbstractCard card) {
int ord = card.rarity.ordinal();
return ord > 5 ? card.rarity.toString() : Integer.toString(ord);
}

private String encodeCardColor(AbstractCard card) {
int ord = card.color.ordinal();
return ord > 5 ? card.color.toString() : Integer.toString(ord);
}

private String sanitize(String s) {
return s.replaceAll(";", ":")
.replaceAll("\"", "\\\"")
Expand Down Expand Up @@ -220,4 +268,5 @@ private String parseDescription(AbstractCard card) {

return sb.toString();
}

}
16 changes: 8 additions & 8 deletions src/main/java/str_exporter/SlayTheRelicsExporter.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class SlayTheRelicsExporter implements

private TipsJSONBuilder tipsJsonBuilder;
private DeckJSONBuilder deckJsonBuilder;
private String okayJsonMessage;
private JSONMessageBuilder okayJsonBuilder;
private BackendBroadcaster tipsBroadcaster;
private BackendBroadcaster deckBroadcaster;
private BackendBroadcaster okayBroadcaster;
Expand Down Expand Up @@ -156,14 +156,13 @@ private void broadcast() {
@Override
public void receivePostInitialize() {

tipsBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS);
deckBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS);
okayBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS);
tipsBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS, false);
deckBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS, false);
okayBroadcaster = new BackendBroadcaster(BROADCAST_CHECK_QUEUE_PERIOD_MILLIS, true);
tipsJsonBuilder = new TipsJSONBuilder(login, secret, version);
deckJsonBuilder = new DeckJSONBuilder(login, secret, version);
okayJsonBuilder = new JSONMessageBuilder(login, secret, version, 5);

okayJsonMessage = new JSONMessageBuilder(login, secret, version, 5).buildJson();
okayJsonMessage = okayJsonMessage.replace(BackendBroadcaster.DELAY_PLACEHOLDER, "0");

ModPanel settingsPanel = new ModPanel();

Expand Down Expand Up @@ -210,9 +209,10 @@ public void receivePostRender(SpriteBatch spriteBatch) {

if (System.currentTimeMillis() - lastOkayBroadcast > MAX_OKAY_BROADCAST_PERIOD_MILLIS) {

String okayMsg = okayJsonBuilder.buildJson();
lastOkayBroadcast = System.currentTimeMillis();
okayBroadcaster.broadcastMessage(okayJsonMessage);
logger.info(okayJsonMessage);
okayBroadcaster.queueMessage(okayMsg);
logger.info(okayMsg);

}
}
Expand Down
14 changes: 9 additions & 5 deletions src/main/java/str_exporter/TipsJSONBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -378,17 +378,17 @@ private static String getImageCode(Texture img) {
private static String powerTipJson(String header, String body) {
return String.format(
"%s;%s",
sanitize(header),
sanitize(body)
sanitizeEmpty(sanitize(header)),
sanitizeEmpty(sanitize(body))
);
}

private static String powerTipJson(String header, String body, String img) {
return String.format(
"%s;%s;%s",
sanitize(header),
sanitize(body),
sanitize(img)
sanitizeEmpty(sanitize(header)),
sanitizeEmpty(sanitize(body)),
sanitizeEmpty(sanitize(img))
);
}

Expand All @@ -402,6 +402,10 @@ private static String sanitize(String str) {
return str;
}

private static String sanitizeEmpty(String str) {
return str.isEmpty() ? " " : str;
}

private boolean isInCombat() {
return CardCrawlGame.isInARun() && CardCrawlGame.dungeon != null && CardCrawlGame.dungeon.player != null &&
CardCrawlGame.dungeon.currMapNode != null &&
Expand Down

0 comments on commit d2737ae

Please sign in to comment.