Update JSON out

This commit is contained in:
bigJIU 2023-04-10 16:18:13 +08:00
parent 8d3b99ad69
commit 86292e77dc
13 changed files with 100 additions and 40 deletions

1
.gitignore vendored
View File

@ -36,3 +36,4 @@ __pycache__/IDManager.cpython-39.pyc
*.pyc *.pyc
questionare.csv questionare.csv
log.txt log.txt
*.json

2
.idea/MarioWeb.iml generated
View File

@ -5,7 +5,7 @@
</component> </component>
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" /> <content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="VisMOO" jdkType="Python SDK" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
<component name="TemplatesService"> <component name="TemplatesService">

2
.idea/misc.xml generated
View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="VisMOO" project-jdk-type="Python SDK" /> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
</project> </project>

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -7,5 +7,6 @@
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="top.jfunc.json.fastjson" level="project" />
</component> </component>
</module> </module>

Binary file not shown.

View File

@ -5,6 +5,7 @@ import java.util.ArrayList;
import agents.HumanAgent; import agents.HumanAgent;
import agents.ReplayAgent; import agents.ReplayAgent;
import com.alibaba.fastjson.JSON;
import engine.core.MarioAgentEvent; import engine.core.MarioAgentEvent;
import engine.core.MarioGame; import engine.core.MarioGame;
import engine.core.MarioResult; import engine.core.MarioResult;
@ -25,7 +26,7 @@ public class Play {
//FIXME: Debug Use //FIXME: Debug Use
//game = new MarioGame(); //game = new MarioGame();
// playJavaGame(); //System.out.println(playJavaGame());
System.out.println("Java: Play Java Main Function Done"); System.out.println("Java: Play Java Main Function Done");
} }
public static boolean initialGame(){ public static boolean initialGame(){
@ -37,7 +38,7 @@ public class Play {
return true; return true;
} }
public static byte[] playJavaGame(){ public static String playJavaGame(){
game.setLives(3); game.setLives(3);
String levelPath = "./levels/group0/lvl1.lvl"; // For local String levelPath = "./levels/group0/lvl1.lvl"; // For local
@ -47,11 +48,14 @@ public class Play {
MarioResult tmpResult = game.playGame(new HumanAgent(false),getLevel(levelPath), 10, repPath,30); MarioResult tmpResult = game.playGame(new HumanAgent(false),getLevel(levelPath), 10, repPath,30);
//Replay //Replay
//MarioResult tmpResult = game.playGame(Replay.getRepAgentFromFile(repPath),getLevel(levelPath), 30, repPath,30); //MarioResult tmpResult = game.playGame(Replay.getRepAgentFromFile(repPath),getLevel(levelPath), 30, repPath,30);
return Replay.serializeAgentEvents(tmpResult.getAgentEvents()); //return Replay.serializeAgentEvents(tmpResult.getAgentEvents());
String jsonString = Replay.serializeGameResult(tmpResult);
return jsonString;//Replay.serializeAgentEvents(tmpResult.getAgentEvents());
} }
public static byte[] playGameMain(String levelName, int lives, boolean control,int time,int col){ public static MarioResult playGameMain(String levelName, int lives, boolean control,int time,int col){
String levelPath = String.format("/app/levels/%s.lvl", levelName); // For web String levelPath = String.format("/app/levels/%s.lvl", levelName); // For web
String repPath = String.format("/files/%s_sav.rep", levelName); // For web String repPath = String.format("/files/%s_sav.rep", levelName); // For web
@ -61,10 +65,12 @@ public class Play {
game.setLives(lives); game.setLives(lives);
MarioResult tmpResult = game.playGame(new HumanAgent(control),getLevel(levelPath), time, repPath,col); MarioResult tmpResult = game.playGame(new HumanAgent(control),getLevel(levelPath), time, repPath,col);
return Replay.serializeAgentEvents(tmpResult.getAgentEvents()); //return Replay.serializeAgentEvents(tmpResult.getAgentEvents());
//return Replay.serializeGameResult(tmpResult);
return tmpResult;
} }
public static byte[] playGameMain(String levelName){ public static MarioResult playGameMain(String levelName){
return playGameMain(levelName, 5, false,30,16); return playGameMain(levelName, 5, false,30,16);
} }
@ -81,4 +87,15 @@ public class Play {
public static void stopReplay(){ public static void stopReplay(){
game.stopGame(); game.stopGame();
} }
public static byte[] serializeActionFromJson(String jsonString){
MarioResult marioResult= JSON.parseObject(jsonString,MarioResult.class);
ArrayList<MarioAgentEvent> events = marioResult.getAgentEvents();
byte[] content = new byte[events.size()];
for (int i = 0; i < events.size(); i++) {
boolean[] action = events.get(i).getActions();
content[i] = Replay.serializeAction(action);
}
return content;
}
} }

View File

@ -5,12 +5,14 @@ import java.util.ArrayList;
import engine.helper.EventType; import engine.helper.EventType;
import engine.helper.GameStatus; import engine.helper.GameStatus;
import engine.helper.SpriteType; import engine.helper.SpriteType;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.JSONObject;
public class MarioResult { public class MarioResult {
private MarioWorld world; private MarioWorld world;
private ArrayList<MarioEvent> gameEvents; private ArrayList<MarioEvent> gameEvents;
private ArrayList<MarioAgentEvent> agentEvents; private ArrayList<MarioAgentEvent> agentEvents;
public MarioResult(){}
/** /**
* Create a mario result object * Create a mario result object
* *
@ -18,6 +20,7 @@ public class MarioResult {
* @param gameEvents the events that happens in the playthrough of the game * @param gameEvents the events that happens in the playthrough of the game
* @param agentEvents the events that happens in the playthrough of the game * @param agentEvents the events that happens in the playthrough of the game
*/ */
public MarioResult(MarioWorld world, ArrayList<MarioEvent> gameEvents, ArrayList<MarioAgentEvent> agentEvents) { public MarioResult(MarioWorld world, ArrayList<MarioEvent> gameEvents, ArrayList<MarioAgentEvent> agentEvents) {
this.world = world; this.world = world;
this.gameEvents = gameEvents; this.gameEvents = gameEvents;

View File

@ -1,7 +1,12 @@
package engine.helper; package engine.helper;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import agents.ReplayAgent; import agents.ReplayAgent;
import engine.core.MarioAgentEvent; import engine.core.MarioAgentEvent;
import engine.core.MarioResult;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -34,6 +39,11 @@ public class Replay {
return content; return content;
} }
public static String serializeGameResult(MarioResult marioResult) {
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(marioResult);
return jsonObject.toJSONString();
}
public static void saveReplay(String filepath, ArrayList<MarioAgentEvent> events) { public static void saveReplay(String filepath, ArrayList<MarioAgentEvent> events) {
try { try {
byte[] content = serializeAgentEvents(events); byte[] content = serializeAgentEvents(events);
@ -61,4 +71,5 @@ public class Replay {
} }
return action; return action;
} }
} }

44
main.py
View File

@ -9,14 +9,15 @@ from flask import Flask, render_template, request, redirect, url_for, session
import logging import logging
# 设置logging模块 # 设置logging模块
logging.basicConfig(filename='log.txt', level=logging.DEBUG) # logging.basicConfig(filename='log.txt', level=logging.DEBUG)
# 将print输出重定向到logging模块 # 将print输出重定向到logging模块
print = logging.getLogger().info # print = logging.getLogger().info
app = Flask(__name__, static_folder='') app = Flask(__name__, static_folder='')
idm = idManager() idm = idManager()
app.secret_key = 'asdfasdfawefaewvaf' app.secret_key = 'asdfasdfawefaewvaf'
replayDataPath = "reps/" replayDataPath = "reps/"
jsonDataPath = "jsons/"
evalDataPath = "evals/" evalDataPath = "evals/"
questionarePath = "data/questionare.csv" questionarePath = "data/questionare.csv"
@ -97,8 +98,9 @@ def gameplay(id):
def getJSONData(id): def getJSONData(id):
if request.method == 'POST': if request.method == 'POST':
print("POST Game") print("POST Game")
resultList = list(request.form)[0].split(",") resultList = list(request.form)[0].split("@@@")
saveFile(replayDataPath, id + "_" + resultList[0][:-2], resultList[1:]) saveJsonFile(jsonDataPath, id + "_" + resultList[0], resultList[1])
saveRepFile(replayDataPath, id + "_" + resultList[0], resultList[1])
return "return!" return "return!"
@ -151,8 +153,9 @@ def gameplay2(id):
def getJSONData2(id): def getJSONData2(id):
if request.method == 'POST': if request.method == 'POST':
print("POST Game") print("POST Game")
resultList = list(request.form)[0].split(",") resultList = list(request.form)[0].split("@@@")
saveFile(replayDataPath, id+"_" + resultList[0][:-2], resultList[1:]) saveJsonFile(jsonDataPath, id + "_" + resultList[0], resultList[1])
saveRepFile(replayDataPath, id + "_" + resultList[0], resultList[1])
return "return!" return "return!"
@ -214,14 +217,39 @@ def over():
# ""]) # ""])
# return redirect(url_for("over", id=id)) # return redirect(url_for("over", id=id))
def saveFile(path, filename, content): def saveRepFile(path, filename, content):
cp = list(map(int, content)) o_dict = json.loads(content)
action_dict = o_dict["elementData1"][1:]
actionList = []
for actions in action_dict:
try:
alist = actions["actions0"]
actionsInput = [alist["0"], alist["1"], alist["2"], alist["3"], alist["4"], alist["5"], alist["6"]]
actionList.append(serializeAction(actionsInput))
except Exception: continue
cp = list(map(int, actionList))
file_dir = os.path.join(os.getcwd(), path) file_dir = os.path.join(os.getcwd(), path)
file_path = os.path.join(file_dir, filename + ".rep") file_path = os.path.join(file_dir, filename + ".rep")
with open(file_path, 'wb') as f: with open(file_path, 'wb') as f:
f.write(b''.join(struct.pack('B', c) for c in cp)) f.write(b''.join(struct.pack('B', c) for c in cp))
def serializeAction(actions):
res = 0
for i in range(5):
if not actions[i]:
tmp = 1 << i
res += tmp
return res
def saveJsonFile(path, filename, content):
file_dir = os.path.join(os.getcwd(), path)
file_path = os.path.join(file_dir, filename + ".json")
with open(file_path, 'w') as f:
f.write(content)
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=False) app.run(host='0.0.0.0', port=80, debug=False)
# app.run() # app.run()

View File

@ -332,18 +332,12 @@
}); });
cheerpjCreateDisplay(500, 500, divElement); cheerpjCreateDisplay(500, 500, divElement);
cheerpjRunMain("Play", "/app/Mario-AI-Interface.jar", "0", "f_l"); cheerpjRunMain("Play", "/app/Mario-AI-Interface.jar", "0", "f_l");
GameLoad().then(function () { GameLoad().then(function () {
$("#windowshow:visible").hide(); $("#windowshow:visible").hide();
{#console.log("Cheerpj Initialize Succeed!", control);#} {#console.log("Cheerpj Initialize Succeed!", control);#}
document.getElementById("loading").style.visibility = 'hidden'; document.getElementById("loading").style.visibility = 'hidden';
}) })
@ -370,9 +364,6 @@
}else { }else {
$("#top:hidden").show(); $("#top:hidden").show();
} }
} }
</script> </script>

View File

@ -26,13 +26,19 @@ function PlayLevel(level,control){
console.log("HTML:Start PlayLevel cjCall") console.log("HTML:Start PlayLevel cjCall")
var returnVal = cjCall("Play", "playGameMain", level, 5, control,30,16); var returnVal = cjCall("Play", "playGameMain", level, 5, control,30,16);
return returnVal.then(function(){ return returnVal.then(function(){
stringVal = toJSON(returnVal.value['agentEvents2'])
console.log("the return val is ready"); console.log("the return val is ready");
console.log(returnVal.value); console.log(stringVal);
PostToServer(window.location.href+"/data",level+returnVal.value); PostToServer(window.location.href+"/data",level+"@@@"+stringVal);
//Array.from() //Array.from()
}); });
} }
function toJSON(returnVal)
{
return JSON.stringify(returnVal)
}
function GameOver(){ function GameOver(){
if(alert("Game Over!")){ if(alert("Game Over!")){