Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.91 KB | None | 0 0
  1. import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.io.*;
  5. import java.util.*;
  6. import java.util.regex.*;
  7. import java.lang.reflect.*;
  8.  
  9. /**
  10.  * Write a description of class Strategiewelt here.
  11.  *
  12.  * @author (your name)
  13.  * @version (a version number or a date)
  14.  */
  15. public class Strategiewelt  extends SpinnenWelt
  16. {
  17.     protected GreenfootImage scoreboard;
  18.     protected int score;
  19.     /**
  20.      * Constructor for objects of class Strategiewelt.
  21.      *
  22.      */
  23.     public Strategiewelt( int w, int h )
  24.     {
  25.         super( w, h );
  26.         removeObjects( getObjects( null ) ); //Rahmen entfernen
  27.         /*addObject( new StrategieSpinne( ), w / 2, h / 2 );
  28.         fliegenSpawnen( 10 );*/
  29.     }
  30.    
  31.     public Strategiewelt( int w, int h, int fliegen )
  32.     {    
  33.         super( w, h );
  34.         addObject( new StrategieSpinne( ), w / 2, h / 2 );
  35.         fliegenSpawnen( fliegen );
  36.     }
  37.    
  38.     public void fliegenSpawnen( int fliegen )
  39.     {
  40.         for( int i = 0; i < fliegen; i++ )
  41.         {
  42.             int x, y;
  43.             do
  44.             {
  45.                 x = Greenfoot.getRandomNumber( getWidth( ) );
  46.                 y = Greenfoot.getRandomNumber( getHeight( ) );
  47.             }
  48.             while( getObjectsAt( x, y, null ).size( ) > 0 );
  49.             addObject( new Fliege( ), x, y );
  50.         }
  51.     }
  52.    
  53.     public void initScoreboard( )
  54.     {
  55.         scoreboard = new GreenfootImage( 400, 300 );
  56.        
  57.         scoreboard.setColor( new Color( 0, 255, 0, 100 ) );
  58.         scoreboard.fillRect( 0, 0, 400, 300 );
  59.        
  60.         Font schrift = scoreboard.getFont( );
  61.         schrift = schrift.deriveFont( 48 ); //Schriftgröße 48
  62.        
  63.         scoreboard.setFont( schrift );
  64.         scoreboard.setColor( Color.WHITE );
  65.        
  66.         scoreboard.drawString( "Punkte :" + score, 0, 0 );
  67.     }
  68.    
  69.     public void setzePunkte( int punkte )
  70.     {
  71.     }
  72.    
  73.     public void debug( String text )
  74.     {
  75.         if( true )
  76.         {
  77.             System.out.println( text );
  78.         }
  79.     }
  80.    
  81.     public void levelSpeichern( String name ) throws Exception
  82.     {
  83.         File f = new File( "levels/" + name + ".txt" );
  84.         if( !f.exists( ) )
  85.             f.createNewFile( );
  86.         debug( "Schreibe Level in Datei " + f.getAbsolutePath( ) );
  87.         FileWriter out = new FileWriter( f );
  88.         /*Sehr einfache implementation, TODO:json, attribute
  89.          * Speichert alle Actor Objekte oder deren Subklassen in der Welt in eine Datei, Attribute werden
  90.          * völlig ignoriert. Pro Zeile ein Objekt, erste Zeile sind die Dimensionen der Welt im Format "Breite,Höhe"
  91.          * Danach je Zeile ein Objekt, im Format: "Klassenname:X,Y,Rotation,ExportierteInformation1;ExportierteInformation2;...;ExportierteInformationN"
  92.          *
  93.          * zu ExportiertenInformationen:
  94.          * Klassen können Attribute oder andere variable Daten exportieren, dazu müssen sie eine öffentliche Methode "onExport" haben, die eine java.util.List zurück gibt.
  95.          * Alle Elemente dieser Liste MÜSSEN in einen String umwandelbar sein! Es wird nur das gespeichert, was toString übergibt.
  96.          * Die Elemete dieser Liste werden, falls vorhanden, durch Kommata getrennt in die Level-Datei geschrieben.
  97.          * Beim Laden des Levels wird nach der instanzierung der Klasse die Methode "onImport" aufgerufen und die Liste als Argument übergeben. ALLE Elemente dieser Liste sind dann Strings!
  98.          *
  99.          * TODO: evtl. an den Konstruktor übergeben, JSON?
  100.          * TODO: ObjectOutputStream angucken
  101.          */
  102.         //Welt Dimensionen
  103.         out.write( String.format( "%d,%d\n", getWidth( ), getHeight( ) ) );
  104.        
  105.         //Objekte
  106.         Iterator<Actor> it = getObjects( Actor.class ).listIterator( );
  107.         Actor aktuell;
  108.         while( it.hasNext( ) )
  109.         {
  110.             aktuell = (Actor)it.next( );
  111.             out.write( String.format( "%s,%d,%d,%d", aktuell.getClass( ).getName( ), aktuell.getX( ), aktuell.getY( ), aktuell.getRotation( ) ) );
  112.             try
  113.             {
  114.                 Method m = aktuell.getClass( ).getMethod( "onExport" );
  115.                 if( m.getReturnType( ) != List.class )
  116.                     throw new Exception( "Klasse " + aktuell.getClass( ).getName( ) + " muss java.util.List zurück geben!" );
  117.                 List args = (java.util.List)m.invoke( aktuell );
  118.                 out.write( "," + joinAndEncode( args, ";" ) );
  119.             }
  120.             catch( NoSuchMethodException e )
  121.             {
  122.                 debug( "Klasse " + aktuell.getClass( ).getName( ) + " Exportiert keine Informationen." );
  123.             }
  124.             debug( String.format( "Schreibe %s auf Position (%d|%d)", aktuell.getClass( ).getName( ), aktuell.getX( ), aktuell.getY( ) ) );
  125.             out.write( "\n" ); //Ende der Zeile
  126.         }
  127.         out.flush( ); //Schreibe in Datei
  128.         out.close( ); //Schließe Handle
  129.     }
  130.    
  131.     public void levelLaden( String name ) throws Exception
  132.     {
  133.         //Siehe levelSpeichern
  134.         File f = new File( "levels/" + name + ".txt" ); //Handle erstellen
  135.         if( !f.exists( ) )
  136.             throw new Exception( "Level Datei " + f.getAbsolutePath( ) + " existiert nicht!" );
  137.            
  138.         debug( "Lade Level aus Datei " + f.getAbsolutePath( ) );
  139.        
  140.         FileReader fin = new FileReader( f );
  141.         BufferedReader in = new BufferedReader( fin ); //BufferedReader um die Datei Zeile für Zeile lesen zu können
  142.        
  143.         String line = in.readLine( ); //erste Zeile
  144.        
  145.         Pattern p0 = Pattern.compile( "(\\d+),(\\d+)" );
  146.         Matcher m0 = p0.matcher( line );
  147.         if( !m0.matches( ) )
  148.             throw new Exception( "Ungültige Level-Datei: " + f.getAbsolutePath( ) + ", Dimensionen sind ungültig in Zeile 1" );
  149.         int weltBreite = Integer.parseInt( m0.group( 1 ) );
  150.         int weltHoehe  = Integer.parseInt( m0.group( 2 ) );
  151.         if( weltBreite > getWidth( ) || weltHoehe > getHeight( ) )
  152.             throw new Exception( "Welt zu klein! Mindestens eine Breite von " + weltBreite + " und eine Höhe von " + weltHoehe + " benötigt!" );
  153.            
  154.         int i = 1;
  155.         while( ( line = in.readLine( ) ) != null ) //Solange es eine Zeile gibt
  156.         {
  157.             i++;
  158.             Pattern p = Pattern.compile( "([A-Za-z0-9]+),(\\d+),(\\d+),(\\d+),?(.*)" );
  159.             Matcher m = p.matcher( line );
  160.             if( !m.matches( ) )
  161.                 throw new Exception( "Ungültige Level-Datei: " + f.getAbsolutePath( ) + ", Objekt Deklaration ungültig in Zeile " + i );
  162.             String className = m.group( 1 );
  163.             int coordX = Integer.parseInt( m.group( 2 ) );
  164.             int coordY = Integer.parseInt( m.group( 3 ) );
  165.             int rotation = Integer.parseInt( m.group( 4 ) );
  166.            
  167.             Class metaClass;
  168.             try
  169.             {
  170.                  metaClass = Class.forName( className );
  171.             }
  172.             catch( ClassNotFoundException e )
  173.             {
  174.                 throw new Exception( "Level-Datei " + f.getAbsolutePath( ) + " enthält die unbekannte Klasse " + className );
  175.             }
  176.            
  177.             Actor obj = (Actor)metaClass.newInstance( ); //Objekt erstellen
  178.             addObject( obj, coordX, coordY ); //Objekt zur Welt hinzufügen
  179.             obj.setRotation( rotation ); //Objekt drehen
  180.            
  181.             //Exportierte Daten an das Objekt weitergeben
  182.             if( !m.group( 5 ).equals( "" ) )
  183.             {
  184.                 List imported = splitAndDecode( m.group( 5 ), ";" );
  185.                 try
  186.                 {
  187.                     Method method = obj.getClass( ).getMethod( "onImport", List.class );
  188.                     method.invoke( obj, imported );
  189.                 }
  190.                 catch( NoSuchMethodException e )
  191.                 {
  192.                     debug( "Klasse " + className + " exportiert Informationen, hat aber keine onImport Methode oder onImport akzeptiert keine Liste als Parameter" );
  193.                 }
  194.             }
  195.         }
  196.         debug( "Level erfolgreich geladen" );
  197.     }
  198.    
  199.     public String joinAndEncode( Collection s, String delimiter )
  200.     {
  201.         StringBuffer buf = new StringBuffer();
  202.         Iterator it = s.iterator();
  203.         while( it.hasNext( ) )
  204.         {
  205.             buf.append( Base64Coder.encodeString( (String)it.next( ).toString( ) ) );
  206.             if( it.hasNext( ) ) //Delimiter nur anhängen wenn weiteres objekt vorhanden
  207.                 buf.append( delimiter );
  208.         }
  209.         return buf.toString();
  210.     }
  211.    
  212.     public List splitAndDecode( String s, String delimiter )
  213.     {
  214.         Vector v = new Vector( );
  215.         String[] splitted = s.split( ";" );
  216.         for( int i = 0; i < splitted.length; i++ )
  217.         {
  218.             v.add( Base64Coder.decodeString( splitted[i] ) );
  219.         }
  220.         return v;
  221.     }
  222.  
  223. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement