Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
- import java.awt.Color;
- import java.awt.Font;
- import java.io.*;
- import java.util.*;
- import java.util.regex.*;
- import java.lang.reflect.*;
- /**
- * Write a description of class Strategiewelt here.
- *
- * @author (your name)
- * @version (a version number or a date)
- */
- public class Strategiewelt extends SpinnenWelt
- {
- protected GreenfootImage scoreboard;
- protected int score;
- /**
- * Constructor for objects of class Strategiewelt.
- *
- */
- public Strategiewelt( int w, int h )
- {
- super( w, h );
- removeObjects( getObjects( null ) ); //Rahmen entfernen
- /*addObject( new StrategieSpinne( ), w / 2, h / 2 );
- fliegenSpawnen( 10 );*/
- }
- public Strategiewelt( int w, int h, int fliegen )
- {
- super( w, h );
- addObject( new StrategieSpinne( ), w / 2, h / 2 );
- fliegenSpawnen( fliegen );
- }
- public void fliegenSpawnen( int fliegen )
- {
- for( int i = 0; i < fliegen; i++ )
- {
- int x, y;
- do
- {
- x = Greenfoot.getRandomNumber( getWidth( ) );
- y = Greenfoot.getRandomNumber( getHeight( ) );
- }
- while( getObjectsAt( x, y, null ).size( ) > 0 );
- addObject( new Fliege( ), x, y );
- }
- }
- public void initScoreboard( )
- {
- scoreboard = new GreenfootImage( 400, 300 );
- scoreboard.setColor( new Color( 0, 255, 0, 100 ) );
- scoreboard.fillRect( 0, 0, 400, 300 );
- Font schrift = scoreboard.getFont( );
- schrift = schrift.deriveFont( 48 ); //Schriftgröße 48
- scoreboard.setFont( schrift );
- scoreboard.setColor( Color.WHITE );
- scoreboard.drawString( "Punkte :" + score, 0, 0 );
- }
- public void setzePunkte( int punkte )
- {
- }
- public void debug( String text )
- {
- if( true )
- {
- System.out.println( text );
- }
- }
- public void levelSpeichern( String name ) throws Exception
- {
- File f = new File( "levels/" + name + ".txt" );
- if( !f.exists( ) )
- f.createNewFile( );
- debug( "Schreibe Level in Datei " + f.getAbsolutePath( ) );
- FileWriter out = new FileWriter( f );
- /*Sehr einfache implementation, TODO:json, attribute
- * Speichert alle Actor Objekte oder deren Subklassen in der Welt in eine Datei, Attribute werden
- * völlig ignoriert. Pro Zeile ein Objekt, erste Zeile sind die Dimensionen der Welt im Format "Breite,Höhe"
- * Danach je Zeile ein Objekt, im Format: "Klassenname:X,Y,Rotation,ExportierteInformation1;ExportierteInformation2;...;ExportierteInformationN"
- *
- * zu ExportiertenInformationen:
- * 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.
- * Alle Elemente dieser Liste MÜSSEN in einen String umwandelbar sein! Es wird nur das gespeichert, was toString übergibt.
- * Die Elemete dieser Liste werden, falls vorhanden, durch Kommata getrennt in die Level-Datei geschrieben.
- * 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!
- *
- * TODO: evtl. an den Konstruktor übergeben, JSON?
- * TODO: ObjectOutputStream angucken
- */
- //Welt Dimensionen
- out.write( String.format( "%d,%d\n", getWidth( ), getHeight( ) ) );
- //Objekte
- Iterator<Actor> it = getObjects( Actor.class ).listIterator( );
- Actor aktuell;
- while( it.hasNext( ) )
- {
- aktuell = (Actor)it.next( );
- out.write( String.format( "%s,%d,%d,%d", aktuell.getClass( ).getName( ), aktuell.getX( ), aktuell.getY( ), aktuell.getRotation( ) ) );
- try
- {
- Method m = aktuell.getClass( ).getMethod( "onExport" );
- if( m.getReturnType( ) != List.class )
- throw new Exception( "Klasse " + aktuell.getClass( ).getName( ) + " muss java.util.List zurück geben!" );
- List args = (java.util.List)m.invoke( aktuell );
- out.write( "," + joinAndEncode( args, ";" ) );
- }
- catch( NoSuchMethodException e )
- {
- debug( "Klasse " + aktuell.getClass( ).getName( ) + " Exportiert keine Informationen." );
- }
- debug( String.format( "Schreibe %s auf Position (%d|%d)", aktuell.getClass( ).getName( ), aktuell.getX( ), aktuell.getY( ) ) );
- out.write( "\n" ); //Ende der Zeile
- }
- out.flush( ); //Schreibe in Datei
- out.close( ); //Schließe Handle
- }
- public void levelLaden( String name ) throws Exception
- {
- //Siehe levelSpeichern
- File f = new File( "levels/" + name + ".txt" ); //Handle erstellen
- if( !f.exists( ) )
- throw new Exception( "Level Datei " + f.getAbsolutePath( ) + " existiert nicht!" );
- debug( "Lade Level aus Datei " + f.getAbsolutePath( ) );
- FileReader fin = new FileReader( f );
- BufferedReader in = new BufferedReader( fin ); //BufferedReader um die Datei Zeile für Zeile lesen zu können
- String line = in.readLine( ); //erste Zeile
- Pattern p0 = Pattern.compile( "(\\d+),(\\d+)" );
- Matcher m0 = p0.matcher( line );
- if( !m0.matches( ) )
- throw new Exception( "Ungültige Level-Datei: " + f.getAbsolutePath( ) + ", Dimensionen sind ungültig in Zeile 1" );
- int weltBreite = Integer.parseInt( m0.group( 1 ) );
- int weltHoehe = Integer.parseInt( m0.group( 2 ) );
- if( weltBreite > getWidth( ) || weltHoehe > getHeight( ) )
- throw new Exception( "Welt zu klein! Mindestens eine Breite von " + weltBreite + " und eine Höhe von " + weltHoehe + " benötigt!" );
- int i = 1;
- while( ( line = in.readLine( ) ) != null ) //Solange es eine Zeile gibt
- {
- i++;
- Pattern p = Pattern.compile( "([A-Za-z0-9]+),(\\d+),(\\d+),(\\d+),?(.*)" );
- Matcher m = p.matcher( line );
- if( !m.matches( ) )
- throw new Exception( "Ungültige Level-Datei: " + f.getAbsolutePath( ) + ", Objekt Deklaration ungültig in Zeile " + i );
- String className = m.group( 1 );
- int coordX = Integer.parseInt( m.group( 2 ) );
- int coordY = Integer.parseInt( m.group( 3 ) );
- int rotation = Integer.parseInt( m.group( 4 ) );
- Class metaClass;
- try
- {
- metaClass = Class.forName( className );
- }
- catch( ClassNotFoundException e )
- {
- throw new Exception( "Level-Datei " + f.getAbsolutePath( ) + " enthält die unbekannte Klasse " + className );
- }
- Actor obj = (Actor)metaClass.newInstance( ); //Objekt erstellen
- addObject( obj, coordX, coordY ); //Objekt zur Welt hinzufügen
- obj.setRotation( rotation ); //Objekt drehen
- //Exportierte Daten an das Objekt weitergeben
- if( !m.group( 5 ).equals( "" ) )
- {
- List imported = splitAndDecode( m.group( 5 ), ";" );
- try
- {
- Method method = obj.getClass( ).getMethod( "onImport", List.class );
- method.invoke( obj, imported );
- }
- catch( NoSuchMethodException e )
- {
- debug( "Klasse " + className + " exportiert Informationen, hat aber keine onImport Methode oder onImport akzeptiert keine Liste als Parameter" );
- }
- }
- }
- debug( "Level erfolgreich geladen" );
- }
- public String joinAndEncode( Collection s, String delimiter )
- {
- StringBuffer buf = new StringBuffer();
- Iterator it = s.iterator();
- while( it.hasNext( ) )
- {
- buf.append( Base64Coder.encodeString( (String)it.next( ).toString( ) ) );
- if( it.hasNext( ) ) //Delimiter nur anhängen wenn weiteres objekt vorhanden
- buf.append( delimiter );
- }
- return buf.toString();
- }
- public List splitAndDecode( String s, String delimiter )
- {
- Vector v = new Vector( );
- String[] splitted = s.split( ";" );
- for( int i = 0; i < splitted.length; i++ )
- {
- v.add( Base64Coder.decodeString( splitted[i] ) );
- }
- return v;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement