Text Based Adventure (WIP)

by paulstamp1
♥0 | Line 376 | Modified 2013-02-20 22:37:55 | MIT License
play

ActionScript3 source code

/**
 * Copyright paulstamp1 ( http://wonderfl.net/user/paulstamp1 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/df3p
 */

package {
    import flash.system.Security;
    import flash.display.Sprite;
    public class FlashTest extends Sprite {
        
        
        public function FlashTest() {
            // write as3 code here..
            
            //setup            
            Security.allowDomain("*");
            Security.allowInsecureDomain("*");

            //game
            var tba:TextBasedAdventureGame = new TextBasedAdventureGame( this );
                      
            //scenes
            var openingScene:Scene = new Scene( "OpeningScene", "http://www.paulstamp.co.uk/images/image_1_full.jpg");
                openingScene.description = "You are by the water";                
            tba.addScene( openingScene );
            
            var secondScene:Scene = new Scene( "SecondScene", "http://www.paulstamp.co.uk/images/tile1.png");
                secondScene.description = "You are in a clearing";
            tba.addScene( secondScene );
            
            //Operations
            var moveToSecondScreen:IOperation = new NavigationOperation( tba, "SecondScene" );
            var feedBackMoveToSecondScreen:IOperation = new FeedbackOperation( tba, "You moved to a clearing" );
            var pissOff:IOperation = new FeedbackOperation( tba, "Piss right Off!" );
            
            //Options
            openingScene.addOption( new Option( [moveToSecondScreen], ["move"] ));
            openingScene.addOption( new Option( [feedBackMoveToSecondScreen], ["move"] ));
            secondScene.addOption( new Option( [pissOff], ["piss off"] ));
                    
            //start
            tba.setScene( "OpeningScene" );
        }
        

    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.ErrorEvent;
import flash.events.IOErrorEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import flash.display.Scene;
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.text.TextFormatAlign;
import flash.display.Sprite;
import flash.display.DisplayObjectContainer;

class TextBasedAdventureGame extends Sprite {
    
    private var _description:TextDescription;
    private var _input:TextInput;
    private var _sceneManager:SceneManager;
    private var _genericCommands:Array;
    private var _feedBack:TextFeedBack;
    private var _image:ImageViewer;
    
    public function TextBasedAdventureGame( parent:DisplayObjectContainer )    
    {
        parent.addChild( this );
        
        _genericCommands = [];
        
        //image
        _image = new ImageViewer( stage.stageWidth, stage.stageHeight - 180 );
        addChild( _image );
        
        //description
        _description = new TextDescription( stage.stageWidth, 60);
        _description.y = stage.stageHeight - 180;
        addChild( _description );
        
        //feedback
        _feedBack = new TextFeedBack( stage.stageWidth, 60 );
        _feedBack.y = stage.stageHeight - 120;
        addChild( _feedBack );
        
        //input
        _input = new TextInput( stage.stageWidth, 60 );
        _input.y = stage.stageHeight - 60;
        _input.addEventListener( CommandEvent.COMMAND_ENTERED, handleCommand );
        addChild( _input );
        
        //scene manager
        _sceneManager = new SceneManager( _image, _description );
           
        _description.print( "HELLO WORLD" );
    }
    
    public function addScene( value:Scene ):void
    {
        _sceneManager.addScene( value );
    }
    
    public function setScene( title:String ):void
    {
        _sceneManager.setScene( title );
    }

    private function handleCommand( event:CommandEvent ):void    
    {
        if( !_sceneManager.currentScene )
            return;            
        
        if( !_sceneManager.currentScene.handleCommand( event.command ))
        {
            handleGenericCommand( event );
        }        
    }
    
    public function displayFeedback( feedback:String ):void
    {
        _feedBack.print( feedback );
    }

    private function handleGenericCommand( event:CommandEvent ):void
    {
        
        for each( var option:Option in _genericCommands )
        {
            if( option.hasCommand( event.command ))
            {
                 option.run(); 
                 return;  
            }           
        }
        
        _feedBack.print( "Unrecognised command" );
    }

}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

import flash.display.DisplayObject;

class ImageViewer extends Sprite {
    
    public function ImageViewer( width:uint, heigt:uint )
    {
        this.graphics.beginFill( 0xFFFFFF);
        this.graphics.drawRect( 0,0, width, height );
        this.graphics.endFill();  
    }
    
    public function displayImage( image:DisplayObject ):void
    {
        while( this.numChildren > 0 )
            this.removeChildAt(0);    

        addChild( image );
    }
}


/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.display.Sprite;
import flash.text.TextField;

class TextDescription extends Sprite {
    
    private var _textField:TextField;   
    
    public function TextDescription( width:uint, height:uint )
    {
        _textField = new TextField();
        _textField.defaultTextFormat = new TextFormat( "_sans", 12, 0x56ffff, null, null, null, null, null, TextFormatAlign.CENTER  );
        _textField.width = width;
        _textField.height = height;
        _textField.selectable = false;        
        addChild( _textField );
        
        verticalAlignTextField( _textField );
        
        this.graphics.beginFill( 0x222222 );
        this.graphics.drawRect( 0,0, width, height );
        this.graphics.endFill();
    }
    
    public function print( value:String ):void
    {
        _textField.text = value;   
    }

    public function clear():void    
    {
        _textField.text = ""
    }
    
    public static function verticalAlignTextField(tf: TextField): void
    {
        tf.y += Math.round((tf.height - tf.textHeight) / 2);
    }    
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.display.Sprite;
import flash.text.TextField;

class TextFeedBack extends Sprite {
    
    private var _textField:TextField;   
    private var _lineCount:uint;
    
    public function TextFeedBack( width:uint, height:uint )
    {
        _textField = new TextField();
        _textField.defaultTextFormat = new TextFormat( "_sans", 12, 0x42c4aa, null, null, null, null, null, TextFormatAlign.LEFT  );
        _textField.width = width;
        _textField.height = height;
        _textField.text = "";
        _textField.x = 0;
        _textField.y = 0;
        _textField.selectable = false;        
        addChild( _textField );
               
        _lineCount = 0;
           
        this.graphics.beginFill( 0x333333 );
        this.graphics.drawRect( 0,0, width, height );
        this.graphics.endFill();
    }
    
    public function print( value:String ):void
    {       
        _lineCount++; 
        _textField.appendText( "\n" + _lineCount.toString() + " >> " + value );   
    }

    public function clear():void    
    {
        _textField.text = ""
    }
    
    public static function verticalAlignTextField(tf: TextField): void
    {
        tf.y += Math.round((tf.height - tf.textHeight) / 2);
    }    
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

import flash.display.Sprite;

class TextInput extends Sprite {
    
    private var _textField:TextField;
    
    public function TextInput( width:uint, height:uint )
    {
        _textField = new TextField();
        _textField.defaultTextFormat = new TextFormat( "_sans", 12, 0x0eef24 );
        _textField.width = width;
        _textField.height = height;
        _textField.type = TextFieldType.INPUT;              
        addChild( _textField );
        
        this.graphics.beginFill( 0x000000 );
        this.graphics.drawRect( 0,0, width, height );
        this.graphics.endFill();
        
        _textField.addEventListener(KeyboardEvent.KEY_DOWN, onInput);
    }
    
    private function onInput( event:KeyboardEvent ):void
    {
        if(event.charCode == 13)
        {                
           //infom
           this.dispatchEvent( new CommandEvent( _textField.text ) );
           
           //clear field
           _textField.text = "";
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class SceneManager {
    
    private var _scenes:Dictionary;
    private var _currentScene:Scene;
    private var _imageView:ImageViewer;
    private var _textDescription:TextDescription;
    
    public function SceneManager( imageView:ImageViewer, textDescription:TextDescription )
    {
        _textDescription = textDescription;
        _imageView = imageView;
        _scenes = new Dictionary();
    }
    
    public function addScene( value:Scene ):void
    {
       _scenes[ value.title ] = value;
    }
    
    public function setScene( title:String ):void
    {
        _currentScene = _scenes[ title ];
        _currentScene.displayImage( _imageView );
        _currentScene.displayDescription( _textDescription );
    }
    
    public function get currentScene():Scene
    {
        return _currentScene;
    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class Scene {
    
    public var description:String;
    public var title:String;
    public var image:Loader;
    
    private var _options:Array;
    private var _imageURL:String;
    private var _imageLoaded:Boolean;
    
    public function Scene( title:String, imageURL:String )
    {
        this.title = title;
        
        image = new Loader();        
        image.contentLoaderInfo.addEventListener( Event.COMPLETE, imageLoadedHandler );
        image.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, imageErrorHandler );
        image.contentLoaderInfo.addEventListener( ProgressEvent.PROGRESS, imageProgressHandler );
        image.contentLoaderInfo.addEventListener( SecurityErrorEvent.SECURITY_ERROR, imageSecurityErrorHandler );
        
        _imageURL = imageURL;
        _options = [];
    }    
    
    public function displayImage( imageView:ImageViewer ):void
    {        
       loadImage();
       imageView.displayImage( this.image );
    }
    
    public function displayDescription( textDescription:TextDescription ):void
    {
        textDescription.print( description );
    }

    private function loadImage():void
    {
        if( _imageLoaded )
            return;
              
        var loaderContext:LoaderContext = new LoaderContext();
            loaderContext.checkPolicyFile = true;     
        
        image.load(new URLRequest(_imageURL), loaderContext);
    }
    
    private function imageSecurityErrorHandler( event:SecurityErrorEvent ):void
    {
        throw new Error( "image security error" ); 
    }

    private function imageProgressHandler( event:ProgressEvent ):void
    {
        
    }
    
    private function imageErrorHandler( event:IOErrorEvent ):void
    {
        throw new Error( "Failed to load image" );    
    }
    
    private function imageLoadedHandler( event:Event ):void
    {        
        image.contentLoaderInfo.removeEventListener( Event.COMPLETE, imageLoadedHandler );
        _imageLoaded = true;
    }

    public function addOption( option:Option ):void
    {
        _options.push( option );
    }

    public function handleCommand( command:String ):Boolean
    {
        var ranCommand:Boolean;
        
        for each( var option:Option in _options )
        {             
           if( option.hasCommand( command ))
           {    
               option.run(); 
               ranCommand = true;              
           }

        }
                
        return ranCommand;
    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class Option {
    
    private var _commands:Array;
    private var _operations:Array;
    
    public function Option( operations:Array, commands:Array )
    {
        _operations = operations;
        _commands = commands;
    }
    
    public function addOperation( operation:IOperation ):void
    {
        _operations.push( operation );
    }

    public function addCommand( value:String ):void
    {
        _commands.push( value );
    }
    
    public function hasCommand( value:String ):Boolean
    {        
        return _commands.lastIndexOf( value ) != -1;
    }
    
    public function run():void
    {
        for each( var operation:IOperation in _operations )
        {
            operation.execute();
        }
    }
 }
 
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

interface IOperation {
    
    function execute():void;
}

////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class CommandEvent extends Event{
    
    public static const COMMAND_ENTERED:String = "CommandEntered";
    
    private var _command:String;
    
    public function CommandEvent( command:String ):void
    {
        _command = command;
        super( COMMAND_ENTERED, false, false );
    }
    
    public function get command():String
    {
        return _command;
    }
}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class NavigationOperation implements IOperation {
    
    private var _title:String;
    private var _tba:TextBasedAdventureGame;
    
    public function NavigationOperation( tba:TextBasedAdventureGame, title:String )
    {
        _tba = tba;
        _title = title;
    }

    public function execute():void
    {
        //do some shit
        _tba.setScene( _title );
    }

}

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

class FeedbackOperation implements IOperation {
    
    private var _tba:TextBasedAdventureGame;
    private var _feedback:String;
    
    public function FeedbackOperation( tba:TextBasedAdventureGame, feedback:String )
    {        
        _tba = tba;     
        _feedback = feedback;   
    }

    public function execute():void
    {
        //do some shit
        _tba.displayFeedback( _feedback );
    }

}

Forked