Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
SannikovDmitry committed Sep 2, 2018
2 parents 2ae7a77 + 05cdb5e commit 580a251
Show file tree
Hide file tree
Showing 5 changed files with 231 additions and 0 deletions.
9 changes: 9 additions & 0 deletions madcars/examples/Java/Bot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Интерфейс типового робота, получающего на вход конфигурацию и состояние мира в формате JSON,
* и отправляющего на выход своё решение на текущем шаге (тоже в JSON) *
*/
public interface Bot {
void onMatchStarted(MatchConfig matchConfig);
void onNextTick(TickState tickState);
void onParsingError(String message);
}
55 changes: 55 additions & 0 deletions madcars/examples/Java/JsonIO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import org.json.JSONObject;
import java.io.*;

/**
* Обертка, позволяющая считывать из потока ввода и писать в поток вывода JSON-объекты
* Для отладочных целей есть возможность читать команды не из STDIN, а из файла, например:
*
* <p>{@code gameMessage = JsonIO.readFromFile("messages.json")}</p>
*/

public class JsonIO {
private static FileInputStream fileStream;
private static InputStreamReader reader;
private static BufferedReader bufferedReader;

public static JSONObject readFromStdIn(){
return readFromStream(System.in);
}

public static JSONObject readFromFile(String fileName){
try {
if (fileStream == null)
fileStream = new FileInputStream(fileName);
return readFromStream(fileStream);
}
catch (FileNotFoundException e) {
return readFromStdIn();
}
}
private static JSONObject readFromStream(InputStream stream){
if (reader == null)
reader = new InputStreamReader(stream);

if (bufferedReader == null)
bufferedReader = new BufferedReader(reader);

try {
String line = bufferedReader.readLine();
return (line != null && line.length() != 0)
? new JSONObject(line)
: null;
}
catch (IOException e) {
return null;
}
}

public static void writeToStdOut(JSONObject object){
writeToStream(System.out, object);
}

private static void writeToStream(PrintStream stream, JSONObject object) {
stream.println(object.toString());
}
}
94 changes: 94 additions & 0 deletions madcars/examples/Java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import org.json.JSONObject;
import java.util.Random;

public class Main {
private static Bot robot;

public static void main(String[] args) {

JSONObject gameMessage;
while ((gameMessage = JsonIO.readFromStdIn()) != null) {
MessageType messageType;
try {
messageType = gameMessage.getEnum(MessageType.class, "type");
switch (messageType) {
case tick:
TickState tickState = new TickState(gameMessage.getJSONObject("params"));
robot().onNextTick(tickState);
break;

case new_match:
MatchConfig matchConfig = new MatchConfig(gameMessage.getJSONObject("params"));
robot().onMatchStarted(matchConfig);
break;
}
}
catch (Exception e){
robot().onParsingError(e.getMessage());
}
}
}

private static Bot robot() {

if (robot == null)
robot = new Bot() {
// todo заменить этот анонимный класс-заглушку реальным классом стратегии
static final int ON_AIR_PAUSE = 50;
final String commands[] = {"left", "stop", "right"};

int thisMathTick = 0;
int matchCounter = 0;
String debugMessage = "";

@Override
public void onMatchStarted(MatchConfig matchConfig){
thisMathTick = 0;
matchCounter ++;

debugMessage = String.format(".... Match #%d: lives=%d, ", matchCounter, matchConfig.myLives);
}

@Override
public void onNextTick(TickState tickState) {
thisMathTick++;

if (thisMathTick == 1)
debugMessage += String.format("my side=%s.... ", commands[1 - tickState.myCar.mirror]);

String cmd = thisMathTick <= ON_AIR_PAUSE ? "stop" : commands[new Random().nextInt(3)];
debugMessage += String.format("%d.%d: %s",matchCounter, thisMathTick, cmd);

new Answer(cmd, debugMessage).send();
debugMessage = "";
}

@Override
public void onParsingError(String message) {
debugMessage = message;
}
};
return robot;
}

public static class Answer {
String command;
String debug;

public String getCommand() { return command;}
public String getDebug() { return debug;}

Answer(String cmd, String dbg){
command = cmd;
debug = dbg;
}
void send(){
JSONObject json = new JSONObject(this);
JsonIO.writeToStdOut(json);
}
}
enum MessageType {
new_match,
tick
}
}
19 changes: 19 additions & 0 deletions madcars/examples/Java/MatchConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import org.json.JSONObject;

/**
* Параметры матча (характеристики машин, контуры карт и т.д.), присылаемые в начале каждого матча.
* Передается на вход обработчика {@code onMatchStarted} интерфейса {@link Bot}
*/

public class MatchConfig {
//todo добавить нужные поля и классы и реализовать десериализацию json-объекта
int myLives;
int enemyLives;
// ...

public MatchConfig(JSONObject params) {
myLives = params.getInt("my_lives");
enemyLives = params.getInt("enemy_lives");
// ...
}
}
54 changes: 54 additions & 0 deletions madcars/examples/Java/TickState.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import org.json.JSONArray;
import org.json.JSONObject;

/**
* Состояние мира, присылаемое сервером на каждом тике.
* Передается на вход обработчика {@code onNextTick} интерфейса {@link Bot}
*/

class TickState {
Car myCar;
Car enemyCar;
float deadLine;

public TickState(JSONObject params){
myCar = new Car(params.getJSONArray("my_car"));
enemyCar = new Car(params.getJSONArray("enemy_car"));

deadLine = params.getFloat("deadline_position");
}

class Car {
int mirror; // слева = +1, справа = -1

float x, y;
float angle;

WheelPair wheel = new WheelPair();

Car(JSONArray carParam){
JSONArray pos = carParam.getJSONArray(0);
x = pos.getFloat(0);
y = pos.getFloat(1);

angle = carParam.getFloat(1);
mirror = carParam.getInt(2);

wheel.rear = new Wheel(carParam.getJSONArray(3));
wheel.front = new Wheel(carParam.getJSONArray(4));
}
class WheelPair {
Wheel rear;
Wheel front;
}
class Wheel {
float x, y;
float angle;
Wheel (JSONArray wheelParam) {
x = wheelParam.getFloat(0);
y = wheelParam.getFloat(1);
angle = wheelParam.getFloat(2);
}
}
}
}

0 comments on commit 580a251

Please sign in to comment.