Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: Riven (posted 2014-07-23 21:07:15, viewed 59 times)

1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   240   241   242   243   244   245   246   247   248   249   250   251   252   253   254   255   256   257   258   259   260   261   262   263   264   265   266   267   268   269   270   271   272   273   274   275   276   277   278   279   280   281   282   283   284   285   286   287   288   289   290   291   292   293   294   295   296   297   298   299   300   301   302   303   304   305   306   307   308   309   310   311   312   313   314   315   316   317   318   319   320   321   322   323   324   325   326   327   328   329   330   331   332   333   334   335   336   337   338   339   340   341   342   343   344   345   346   347   348   349   350   351   352   353   354   355   356   357   358   359   360   361   362   363   364   365   366   367   368   369   370   371   372   373   374   375   376   377   378   379   380   381   382   383   384   385   386   387   388   389   390   391   392   393   394   395   396   397   398   399   400   401   402   403   404   405   406   407   408   409   410   411   412   413   414   415   416   417   418   419   420   421   422   423   424   425   426   427   428   429   430   431   432   433   434   435   436   437   438   439   440   441   442   443   444   445   446   447   448   449   450   451   452   453   454   455   456   457   458   459   460   461   462   463   464   465   466   467   468   469   470   471   472   473   474   475   476   477   478   479   480   481   482   483   484   485   486   487   488   489   490   491   492   493   494   495   496   497   498   499   500   501   502   503   504   505   506   507   508   509   510   511   512   513   514   515   516   517   518   519   520   521   522   523   524   525   526   527   528   529  
package net.indiespot.script.basic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;

public class BasicScript {
   public static final void main(String[] args) throws IOException {
      Block env = new Block();
      env.include("Func.script", readResource("/script2b.txt"));
      env.include("Work.script", readResource("/script2.txt"));
      env.compile();

      System.out.println("=--=");
      System.out.println(env.toString());
      System.out.println("=--=");

      Context context = new Context() {
         @Override
         public State exec(String[] code) {
            System.out.println(Arrays.toString(code));
            if(code[0].equals("AAA"))
               return State.YIELDED;
            return State.RUNNING;
         }

         @Override
         public boolean query(String name) {
            if("PINDA".equals(name)) {
               return true;
            }
            return false;
         }
      };

      {
         Eval stepper = env.eval(context, "sub");
         outer: while (true) {
            System.out.println("\t\t\t" + stepper.currentTrace());
            switch (stepper.tick()) {
            case TERMINATED:
               stepper = null;
               break outer;
            case HALTED:
               stepper = null;
               break outer;
            case YIELDED:
               System.out.println("...");
               break;
            default:
               break;
            }
         }
      }

      Eval stepper = env.eval(context);
      outer: while (true) {
         System.out.println("\t\t\t" + stepper.currentTrace());
         switch (stepper.tick()) {
         case TERMINATED:
            stepper = null;
            break outer;
         case HALTED:
            stepper = null;
            break outer;
         case YIELDED:
            System.out.println("...");
            break;
         default:
            break;
         }
      }
   }

   private static String readResource(String res) throws IOException {
      InputStream in = BasicScript.class.getResourceAsStream(res);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] buf = new byte[4 * 1024];
      while (true) {
         int got = in.read(buf);
         if(got == -1)
            break;
         baos.write(buf, 0, got);
      }
      byte[] raw = baos.toByteArray();
      return new String(raw, "ASCII");
   }

   private static class Trace {
      public final String file;
      public final int lineNr;

      public Trace(String file, int lineNr) {
         this.file = file;
         this.lineNr = lineNr;
      }

      @Override
      public String toString() {
         return file + ":" + lineNr;
      }
   }

   private static class Code {
      public final Trace trace;
      public Block parent;
      public Code linked;

      public Code(Trace trace, Block parent) {
         if(parent == null && trace.lineNr != 0)
            throw new IllegalStateException();
         this.trace = trace;
         this.parent = parent;
         if(parent != null)
            parent.codes.add(this);
      }

      void print(int indent, StringBuilder out) {
         out.append("\n").append("L").append(trace.lineNr);
         for(int i = 0; i <= indent; i++)
            out.append("\t");
      }
   }

   private static class Instruction extends Code {
      public final String text, type;
      public final String[] parts;

      public Instruction(Trace trace, Block parent, String text, String meta) {
         super(trace, parent);
         this.text = text;
         this.type = meta;
         this.parts = (text == null) ? null : text.split("\\s+");
      }

      void print(int indent, StringBuilder out) {
         super.print(indent, out);

         out.append(type).append("=[").append(text).append("]");
      }

      @Override
      public String toString() {
         return type + "[" + text + "]";
      }
   }

   private static class Block extends Code {
      public final String name;
      public final List<Code> codes;
      private String funcJumper;

      public Block() {
         this(new Trace("<file>", 0), null, "<root>");
      }

      Block(Trace trace, Block parent, String name) {
         super(trace, parent);
         this.name = (name == null || name.isEmpty()) ? "<anonymous>" : name;
         this.codes = new ArrayList<>();
      }

      public void include(String file, String script) {
         Block block = new Block(new Trace(file, 0), null, null);

         block.feed(script);

         for(Code code : block.codes) {
            code.parent = this;
            codes.add(code);
         }
      }

      public void feed(String eval) {
         int lineNr = trace.lineNr;
         for(String line : eval.replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n").split("\\n")) {
            this.feed(line, new Trace(trace.file, ++lineNr));
         }
      }

      public boolean feed(String line, Trace trace) {
         line = line.trim();
         if(line.isEmpty())
            return false;
         if(line.startsWith("#"))
            return false;

         if(!codes.isEmpty() && codes.get(codes.size() - 1) instanceof Block) {
            boolean isEnd = ((Block) codes.get(codes.size() - 1)).feed(line, trace);
            if(isEnd) {
               new Instruction(trace, this, null, "END");
               if(funcJumper != null) {
                  new Instruction(new Trace(null, 0), this, "" + funcJumper, "LABEL");
                  funcJumper = null;
               }
            }
         }
         else if(line.startsWith("BEGIN")) {
            String callName = line.substring("BEGIN".length()).trim();
            new Block(trace, this, callName);
         }
         else if(line.startsWith("FUNCTION")) {
            if(funcJumper != null)
               throw new IllegalStateException();
            funcJumper = "" + System.currentTimeMillis() + "" + System.nanoTime() + "";
            String callName = line.substring("FUNCTION".length()).trim();
            new Instruction(new Trace(null, 0), this, "GOTO " + funcJumper, "JUMP");
            new Block(trace, this, callName);
         }
         else if(line.equals("END")) {
            return true; // return control to parent block
         }
         else if(line.endsWith(":")) {
            String label = line.substring(0, line.length() - 1).trim();
            new Instruction(trace, this, label, "LABEL");
         }
         else if(line.startsWith("BREAK")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("REPEAT")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("GOTO")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("IF")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("CALL")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("HALT")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else if(line.startsWith("RAISE")) {
            new Instruction(trace, this, line, "JUMP");
         }
         else {
            new Instruction(trace, this, line, "CODE");
         }
         return false;
      }

      public void compile() {
         cleanupEnd();
         link();
      }

      public Eval eval(Context ctx) {
         return new Eval(ctx, null, this);
      }

      public Eval eval(Context ctx, String function) {
         Block func = this.findBlock(function);
         Eval top = new Eval(ctx, null, this);
         return new Eval(ctx, top, func);
      }

      private void cleanupEnd() {
         for(int i = codes.size() - 1; i >= 0; i--) {
            Code code = codes.get(i);

            if(code instanceof Instruction) {
               if(((Instruction) code).type.equals("END")) {
                  codes.remove(i);
               }
            }

            if(code instanceof Block) {
               ((Block) code).cleanupEnd();
            }
         }
      }

      private void link() {
         for(int i = 0; i < codes.size() - 1; i++) {
            codes.get(i).linked = codes.get(i + 1);
         }
         for(int i = codes.size() - 1; i >= 0; i--) {
            if(codes.get(i) instanceof Block) {
               ((Block) codes.get(i)).link();
            }
         }
      }

      void print(int indent, StringBuilder out) {
         super.print(indent, out);

         out.append("BLOCK '").append(name).append("'");
         for(Code code : codes) {
            if(code != null) {
               code.print(indent + 1, out);
            }
         }
      }

      Instruction findLabel(String name) {
         for(Code code : codes) {
            if(code instanceof Instruction) {
               if("LABEL".equals(((Instruction) code).type)) {
                  if(((Instruction) code).text.equals(name)) {
                     return (Instruction) code;
                  }
               }
            }
         }

         throw new NoSuchElementException("label: '" + name + "'");
      }

      Block findBlock(String name) {
         for(Code code : codes) {
            if(code instanceof Block) {
               if(((Block) code).name.equals(name)) {
                  return (Block) code;
               }
            }
         }

         if(parent != null) {
            return parent.findBlock(name);
         }

         throw new NoSuchElementException("block: '" + name + "'");
      }

      @Override
      public String toString() {
         StringBuilder out = new StringBuilder();
         this.print(0, out);
         return out.toString();
      }
   }

   private static enum State {
      RUNNING, TERMINATED, HALTED, RAISED, YIELDED
   }

   private static interface Context {
      public State exec(String[] code);

      public boolean query(String name);
   }

   private static class Eval {
      private final Context ctx;
      private final Eval parent;
      private Eval sub;
      private Block block;
      private Code exec;

      public Eval(Context ctx, Eval parent, Block block) {
         this.ctx = ctx;
         this.parent = parent;
         this.block = block;
      }

      public State tick() {
         if(sub != null) {
            State state = sub.tick();
            if(state == State.TERMINATED) {
               sub = null;
               state = State.RUNNING;
            }
            return state;
         }

         if(exec == null) {
            exec = block.codes.get(0);
         }
         else {
            exec = exec.linked;
            if(exec == null) {
               return State.TERMINATED;
            }
         }

         if(exec instanceof Block) {
            sub = new Eval(ctx, this, (Block) exec);
            return State.RUNNING;
         }

         return this.exec((Instruction) exec);
      }

      public Trace currentTrace() {
         if(sub != null)
            return sub.currentTrace();
         if(exec != null && exec.trace.lineNr > 0)
            return exec.trace;
         if(block != null && block.trace.lineNr > 0)
            return block.trace;
         return null;
      }

      private State exec(Instruction instruction) {
         if("JUMP".equals(instruction.type)) {
            if("IF".equals(instruction.parts[0])) {
               // IF <cond> CALL XY
               // IF <cond> CALL XY ELSE GOTO YZ
               // IF <cond> GOTO YZ
               // IF <cond> GOTO YZ ELSE CALL XY
               // IF <cond> REPEAT 
               // IF <cond> REPEAT ELSE BREAK

               int off = 2;
               String ifCond = instruction.parts[1];
               String ifCmd = instruction.parts[off + 0];
               String ifArg = hasArg(ifCmd) ? instruction.parts[off + 1] : null;
               boolean isCond = ctx.query(ifCond);

               off += hasArg(ifCmd) ? 2 : 1;
               boolean hasElse = instruction.parts.length > off;

               String elseCmd = null, elseArg = null;
               if(hasElse) {
                  if(!"ELSE".equals(instruction.parts[off]))
                     throw new IllegalStateException();
                  off += 1;
                  elseCmd = instruction.parts[off + 0];
                  elseArg = hasArg(elseCmd) ? instruction.parts[off + 1] : null;
                  off += hasArg(elseCmd) ? 2 : 1;

                  if(instruction.parts.length > off)
                     throw new IllegalStateException();
               }

               if(isCond)
                  return jump(ifCmd, ifArg);
               if(hasElse)
                  return jump(elseCmd, elseArg);
               return State.RUNNING;
            }
            else {
               String cmd = instruction.parts[0];
               String arg = hasArg(cmd) ? instruction.parts[1] : null;
               return jump(cmd, arg);
            }
         }
         else if("CODE".equals(instruction.type)) {
            return ctx.exec(instruction.parts);
         }
         else if("LABEL".equals(instruction.type)) {
            return State.RUNNING;
         }
         else {
            throw new UnsupportedOperationException(instruction.type);
         }
      }

      private State jump(String cmd, String arg) {
         switch (cmd) {
         case "REPEAT":
            exec = null;
            return State.RUNNING;
         case "BREAK":
            return State.TERMINATED;
         case "GOTO":
            exec = block.findLabel(arg);
            return State.RUNNING;
         case "CALL":
            sub = new Eval(ctx, this, block.findBlock(arg));
            return State.RUNNING;
         case "HALT":
            sub = null;
            return State.HALTED;
         case "RAISE":
            throw new IllegalStateException(raise(arg));
         default:
            throw new UnsupportedOperationException(cmd);
         }
      }

      private boolean hasArg(String cmd) {
         switch (cmd) {
         case "REPEAT":
         case "BREAK":
         case "HALT":
            return false;
         case "GOTO":
         case "CALL":
         case "RAISE":
            return true;
         default:
            throw new UnsupportedOperationException(cmd);
         }
      }

      private Exception raise(String arg) {
         final String classname = BasicScript.class.getName();

         List<StackTraceElement> trace = new ArrayList<>();
         Eval eval = this;

         do {
            trace.add(new StackTraceElement(classname, eval.block.name, eval.exec.trace.file, eval.exec.trace.lineNr));
            trace.add(new StackTraceElement(classname, eval.block.name, eval.block.trace.file, eval.block.trace.lineNr));
         }
         while ((eval = eval.parent) != null);

         // remove root
         {
            trace.remove(trace.size() - 1);
            trace.remove(trace.size() - 1);
         }

         // remove duplicate trace elements, if any
         for(int i = 1; i < trace.size(); i++) {
            StackTraceElement prev = trace.get(i - 1);
            StackTraceElement curr = trace.get(i);
            if(!curr.getClassName().equals(prev.getClassName()))
               continue;
            if(!curr.getFileName().equals(prev.getFileName()))
               continue;
            if(curr.getLineNumber() != prev.getLineNumber())
               continue;
            trace.remove(i--);
         }

         Exception e = new RuntimeException("RAISED: " + arg);
         e.setStackTrace(trace.toArray(new StackTraceElement[trace.size()]));
         return e;
      }
   }
}





Dump your java code here :



Special syntax:
  • To highlight a line (yellow background), prefix it with '@@'
  • To indicate that a line should be removed (red background), prefix it with '-'
  • To indicate that a line should be added (green background), prefix it with '+'
  • To post multiple snippets, seperate them by '~~~~'
  EOF
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (35 views)
2014-12-15 09:26:44

Mr.CodeIt (26 views)
2014-12-14 19:50:38

BurntPizza (60 views)
2014-12-09 22:41:13

BurntPizza (95 views)
2014-12-08 04:46:31

JscottyBieshaar (55 views)
2014-12-05 12:39:02

SHC (71 views)
2014-12-03 16:27:13

CopyableCougar4 (73 views)
2014-11-29 21:32:03

toopeicgaming1999 (133 views)
2014-11-26 15:22:04

toopeicgaming1999 (124 views)
2014-11-26 15:20:36

toopeicgaming1999 (34 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!