Simple Grid/Tile based layout

I am trying to create a simple game, where there is the human controlled character and some enemy placed in a maze. When you take one move, the enemy takes one move, until he reaches you or you reach the exit.
What I'm having trouble figuring out is how I can lay all this out.
What I'm envisioning is a 2 dimensional array, with each position either a 0 or 1 depending on if the user can move there or not.
Is there a way in java to implement a grid style playing field, such that the player moves from tile to tile, and incoporate collision detection with the use of the array values?
I could realy use some help here, I was thinking of using a layout manager, but I don't think the two ideas are compatible. Please help!

Assuming your not going to use a special-purpose gaming library, you'll probably have to build most from scratch.
A simple way of doing it would probably be to to create a 2-dimensional Tile array, in which Tile is a class you'll write yourself to hold all relevant information (painting info, wether it can be moved to, etc).
If you're going for a 'square' looking game (as opposed to isometric) you might be able to use GridLayout to some extent. But in that case (or when using any other layout manager) your Tiles will have to subclass Component. My guess is that it will quickly become more work to cram everything into Component-shape than it's worth...
Short skeleton-example of what I might do:
public class Game extends JFrame {
    private Tile[][] tiles;
    private Monster[] monster;
    private Player player;
    private GameCanvas canvas;
    public Game() {
        canvas = new GameCanvas();
        add(canvas);
        //other initialization, listeners, etc.
    //you could call something like this when you detect user input that implies a move
    private void move(int x, int y) {
        if (tiles[x][y].isPassable()) {
            player.moveTo(x, y);
            for (int i = 0; i < monsters.length; i++) {
                monsters.makeMove();
canvas.repaint();
} else {
//inform user that he can't move to (x, y)
private static class GameCanvas extends JPanel {
public void paintComponent(Graphics g) {
for (int i = 0; i < tiles.length; i ++) {
for (int j = 0; j < tiles[i].length; j++) {
//OtherPaintingInfo is stuff like coordinates, width, height, etc.
//All of that more or less depends on how you want tiles to look
tiles[i][j].paint(Graphics g, OtherPaintingInfo I);
//do something similar for monsters and player
private static class Tile {
boolean isPassable() { ... }
//Again, OtherPaintingInfo is just a placeholder for anything your impl. needs
void paint(Graphics g, OtherPaintingInfo I() { ... }

Similar Messages

  • How do I assign images to grid cells based on their random number value?

    Hello everyone!
         I need a good point (or shove) in the correct direction.
    Background
         I've created (with previous help from this forum) a 12 x 9 random number grid which cycles through the numbers 1 to 9 a total of twelve times each. I've then created a button which shuffles the current grid's cells each time it is clicked. I now want to use 9 images that I have imported as individual symbols into the library (I have given them each their own class titled "skin1," "skin2," ... "skin9") as cell labels or the equivalent. I have also set the images up as individual movie clips (using the .Sprite class as the extended base class but keeping the actual image class names in line with their object name, i.e. the "skin1" image is the "skin1.as" class).
    Question
         How do I assign these images to the grid cells based on their respective values (ranging from 1 to 9) and have them populate the grid each time I click the "shuffle" button? So for example, in my grid the numbers 1 through 9 randomly appear 12 times each. Every time the number 4 appears in a cell, I want it to be assigned to the image "skin4" (which is just a graphic that looks like a button and has a fancy number "4" printed on it). Below is a chunk of the code I am using to draw the grid cells with:
    // Creates a grid cell when called by generateGrid().
    private funciton drawCell(_numeral:int):Sprite
              This is the code I am currently implementing to populate the grids with (although I
              don't want to use text labels as I want to fill each grid with an image according
              to its numerical value (1 to 9).
         var _label:TextField = new TextField();
         _label.multiline = _label.wordWrap = false;
         _label.autoSize = "center";
         _label.text = String(_numeral);
         // Add numerical label to cell array.
         cellLabels.push(_label);
         var _s:Sprite = new Sprite();
         _s.graphics.lineStyle(2, 0x019000);
         _s.graphics.drawRect(30, 0, cellW, CellH);
         _s.addChild(_label);
         return _s;
         While the following isn't working code, it will hopefully demonstrate what I want to achieve inside this function so I don't have to use the above snippet for text labels:
         //This will "hopefully" create an array of all 9 images by calling their classes.      var _imageArray:Array = [skin1, skin2, skin3, skin4, skin5 , skin6, skin7, skin8, skin9];      // This is what I want to happen for each cell using the above image array:      for (i = 0; i < cells; i++)      {           if (_numeral == 1)           {                // Insert skin1 image for each instance of #1 in the grid.           }           if (_numeral == 2)           {                // Insert skin2 image for each instance of #2 in the grid.           }           ...           if (_numeral == 9)           {                // Insert skin9 image for each instance of #9 in the grid.           }      } 
         Again, I don't want to use text labels. I have a custom skin graphic that I want to go over each number on the grid based on its numerical value (1 to 9). Any help with this is much appreciated!

    kglad,
         Thank you for your help with this one. Using the code below, I have successfully populated my grid cells with the desired corresponding graphics. I noticed one thing though regarding my use of the shuffle button with this particular implementation: even though the numerical values residing in each cell get shuffled, the original images remain in the grid rather than being replaced by new ones. The first code snippet below is the revised cell drawing function including your help; the second snippet shows you my simple shuffle button function (where the problem lies, I think).
    Snippet #1:
         // Creates a grid cell when called by generateGrid().
         private function drawCell(_numeral:int):Sprite
              var _label:TextField = new TextField();
              _label.multiline = _label.wordWrap = false;
              _label.autoSize = "center";
              // Creates a label that represents the numerical value of the cell.
              cellLabels.push(_label);
              var _s:Sprite = new Sprite();
              _s.graphics.lineStyle(2, 0x019000);
              _s.graphics.drawRect(30, 0, cellW, cellH);
              // Physically adds the labels to the grid.
              _s.addChild(_label);
              // Assigns a graphic class to a cell based on its numerical value.
              var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
              // Undefined variable for holding graphic classes.
              var _image:* = new _classRef();
              // Lines the images up with the grid cells.
              _image.x = 30;
              // Physically adds a graphic on top of a cell label.
              _s.addChild(_image);
              return _s;
         So far so good (although I question needing text labels at all if they are just going to remain invisible underneath the images, but enough about that for now). This next part is the reason that the images won't shuffle with the cell values, I think.
    Snippet #2:
         // When shuffleButton is clicked, this event shuffles
         // the number array and fills the cellLabels with the new values.
         private function onButtonShuffleClick(e:MouseEvent):void
              // Shuffles the number array.
              shuffle(numbers);
              // Verifies the array has been shuffled.
              trace("After shuffle:", numbers);
              // Loop replaces old cellLabels with new number array values.
              for (var i:int = 0; i < cells; i++)
                   cellLabels[i].text = String(numbers[i]);
         As you can see, it never replaces the original images that populate the grid. I tried using the _s.removeChild(image) function but that didn't work, nor would copying/pasting some of the code from snippet #1 directly into this function as it would cause another instance of the images to be placed over top of the existing ones rather than actually swapping them out. Any continued help here is greatly appreciated!
         PS Is there a quicker method for posting code into these forums without having to type it all out by hand again (i.e. copy/paste or drag/drop from my .fla or Notepad file directly into this thread)?

  • Creating template areas when using CSS based layout

    Hi:
    I'm ransitioning to pure CSS based layouts. When I used tables for layouts I could select a table cell and make that an editable template region. But when I'm setting everything up in Divs, you can't "select" a div in Layout mode. Indeed, layout mode doesn't really work at all - things are shown all jumbled and you have to use Preview or open in a browser window to see how things will look. (I'm not using the grid - maybe I should?) Is there a way to select a div and make it an editable template region?
    I'm using GoLive CS2 on a Mac.
    Thanks!

    Is this affecting ALL text on that page?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "matthewtrefz" <[email protected]> wrote in
    message
    news:eo5o8v$aqa$[email protected]..
    > We have recently performed an upgrade to our site. The
    entire layout is
    > css
    > based. The problem we have run into is that Contribute
    users can no longer
    > select the content using the mouse. In fact the only way
    to edit the
    > content is
    > to use the arrow keys on the keyboard. Though it is
    possible to edit
    > content
    > this way it is very time consuming and confusing to most
    of our users.
    >
    > I have tired to edit pages based on a template, and
    pages not based on a
    > template and get the same issue.
    > What can I do to fix this problem?
    >
    > The web address is
    http://engineering.osu.edu
    >
    > Thanks,
    > Matthew
    >

  • Best way to do a tile-based map

    Hello everybody-
    This should be a simple thing but I just can't get it to work. I'm making a tile-based top-down online rpg (application, not applet), and I pretty much have most of it done except I can't get the map to display and scroll right. i will admit that java graphics isn't really my thing, but i just can't get it. Its been so frustrating that i actually quite develpment on my game and quit for awhile, but i decided to try again. What I have is an array if images that make up the map, and then i manipulate the array depending where the character is so i only draw the tiles necessary. what i want to do is to combine all the tiles i need for the particular position, draw that image to the screen (so i don't have to draw each tile individually to the screen). then i could move that large image depending where the character moved, and add tiles to it depending on which way the character moves. I just can't get it to work however. I've looked at double-bufferning posts and that gave me some ideas, but not enough for my particular situation. if anybody has any experience in this i would be more than greatful. thank you

    I know exactly what you are talking about, I had your problem a while back when I was doing mobile phone games.
    To reduce the number of cell draws needed, cells were only drawn when at the edges of the view area. (all other cells were maintained from the previously drawn frame.)
    It gets pretty complicated, but it will work - stick with it.
    I would post some code - but I don't have it anymore - and it was pretty specific to J2ME MIDP API (java mobile phone).
    p.s. When I did it, I had to include several additional optimisation, these made it incredibly complex :(
    I will try to describe it, but without pictures, It will probably be in vain. (don't worry if you don't understand it :P)
    here is the summary of the logic :-
    the backbuffer had dimensions SCREEN_WIDTH+CELL_WIDTH*2, SCREEN_HEIGHT+CELL_HEIGHT*2 (I effectively had a border that was CELL_WIDTH wide, and CELL_HEIGHT tall.)
    this meant new cells only had to be drawn every time the view area passed over a cell boundary.
    however, doing this, meant it was super smooth until it hit a cell boundary, at which point it had to draw all the cells in the newly exposed column and/or row - which caused a jerk.
    To get around this, I devised a speculative rendering, where by the next column/row was pre-rendered over a series of game frames.
    (each column/row had its own buffer into which the pre-rendering was done)
    On average 2-4 times as many edge cells had to be rendered than needed, but, because the camera moved slowly, this could be distributed over approx. 10 game frames.
    By distributing the rendering of the edge cells over a number of game frames, I hoped to remove the jerk experienced as the camera crossed a cell boundary.
    The system worked... ish... but I never finished it :(
    basically, these were crazy optimisations that were only necessary because I was developing for mobile phones.
    On mobile phones the speed of rendering is relative to the number of draw calls, NOT the actual area of the screen being repainted.
    e.g.
    fillRect(0,0,50,50)
    fillRect(0,50,50,50)
    will take almost twice as long as
    fillRect(0,0,100,100)
    even though you are only painting 1/2 the area.

  • Java.swing    is there anyway to use coordinate based layout in java

    i'm new to java and swing and all this gridlayout thing is starting to iritate me well not starting i'm fedup of that. i used to like my simple coordinate based layout system from wxpython, and even that of C# , so is there anyway to do that in Java. and whenever i try to add more than one wigit to the frame using frame.getcontentpane().add(wigit) one widit is displayed over the other, plus none of the methods for those wigits work, when i use setbounds i see no change in the wigits and so on. u can ask for my source code i can send it for u if u like.

    You can use absolutes, but your shouldn't.
    Try usign a combination of BoxLayouts and BorderLayouts and you should be able to do anything. Just realize that only one component can be placed in one location, and if you need more, then add a sub JPanel, and add more components there.
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

  • Add Array grid  report into Layout/tab ExtJS?

    How to add Array grid report into Layout/tab ExtJS?
    Array grid examples are from >
    http://apex.oracle.com/pls/apex/f?p=43040:4:467728553403435
    js>
    Ext.onReady(function(){
    4
    5var munkyData = [
    6
    7["7369","SMITH","CLERK","7902","17-DEC-80","800"," ","20"]
    8,["7499","ALLEN","SALESMAN","7698","20-FEB-81","1600","300","30"]
    9
    10,["7521","WARD","SALESMAN","7698","22-FEB-81","1250","500","30"]
    11
    12,["7566","JONES","MANAGER","7839","02-APR-81","2975"," ","20"]
    13
    14,["7654","MARTIN","SALESMAN","7698","28-SEP-81","1250","1400","30"]
    15
    16,["7698","BLAKE","MANAGER","7839","01-MAY-81","2850"," ","30"]
    17
    18,["7782","CLARK","MANAGER","7839","09-JUN-81","2450"," ","10"]
    19
    20,["7788","SCOTT","ANALYST","7566","09-DEC-82","3000"," ","20"]
    21
    22,["7839","KING","PRESIDENT"," ","17-NOV-81","5000"," ","10"]
    23
    24,["7844","TURNER","SALESMAN","7698","08-SEP-81","1500","0","30"]
    25
    26,["7876","ADAMS","CLERK","7788","12-JAN-83","1100"," ","20"]
    27
    28,["7900","JAMES","CLERK","7698","03-DEC-81","950"," ","30"]
    29
    30,["7902","FORD","ANALYST","7566","03-DEC-81","3000"," ","20"]
    31
    32,["7934","MILLER","CLERK","7782","23-JAN-82","1300"," ","10"]
    33
    34];
    35
    36var store = new Ext.data.SimpleStore({
    37 el: store,
    38 fields: [
    39 {name: 'empno', mapping: '0'},
    40 {name: 'ename', mapping: '1'},
    41 {name: 'job', mapping: '2'},
    42 {name: 'mgr', mapping: '3'},
    43 {name: 'hiredate', mapping: '4'},
    44 {name: 'sal', mapping: '5'},
    45 {name: 'comm', mapping: '6'},
    46 {name: 'deptno', mapping: '7'}
    47 ]
    48 });
    49
    50store.loadData(munkyData);
    51
    52var grid = new Ext.grid.GridPanel({
    53 el: grid,
    54 store: store,
    55 columns: [
    56 {id:'empno',header: "Employee",sortable:true, width:100,dataIndex:'empno'},
    57 {header: "Name", sortable:true,width:75, dataIndex:'ename'},
    58 {header: "Job", sortable:true, dataIndex:'job'},
    59 {header: "Manager", sortable:true,width:75, dataIndex:'mgr'},
    60 {header: "Hire Date", sortable:true,dataIndex:'hiredate'},
    61 {header: "Salary", sortable:true,width:50,dataIndex:'sal'},
    62 {header: "Commission", sortable:true,dataIndex:'comm'},
    63 {header: "Department", dataIndex:'deptno'}
    64 ],
    65 stripeRows: true,
    66 width:700,
    67 autoHeight:true,
    68 title:'Array Grid'
    69 , renderTo: 'munkyDiv'
    70 });
    71});
    any references?
    regards
    Gordan

    Hi Mark,
    thanks for reply, I was making example on
    http://apex.oracle.com/pls/otn/f?p=43048:22:2659745156195172
    using debug grid layout and put into REGION_05
    ...< div id = "munkyDiv" > #REGION_POSITION_O5# < / div>
    in this way I can add 1,2,3 or more reports as tab and grid.
    Simple example as first step is basic layout (integration ExtJS and Apex)>
    http://apex.oracle.com/pls/otn/f?p=43048:15
    username/pass EXTJS/EXTJS
    regards
    Gordan
    Edited by: useruseruser on Aug 8, 2010 2:51 PM
    Edited by: useruseruser on Aug 8, 2010 2:52 PM

  • Tile-based map and A-star help?

    I am working on a tower defense type game. A while ago I posted asking about maze logic and was kindly directed towards A-star pathfinding. It is perfect. I understand the concept and it makes sense. Now the problem I am having is how to do the tile-based map? I'm having a hard time wrapping my head around it. I just want to do a straight square map comprised of squares. I realize a 2D Array would probably be the best way just such as:
    int[][] map = new int[100][100]
    where there would be 100 x 100 tiles. I can then populate the array with numbers ie 0 = walkable, 1 = unwalkable. I can have my A* algorithm return the set of tiles to move to.
    My problem is that I don't want my game to be in pixels and I'm having a hard time understanding how to make the game appear tile based and large enough to be playable? ie. 1 tile = 30x30 pixels. If we are looking at it in terms of model and view, I understand the model part, but I am having a hard time translating to the view? How do I create a tile based view so that the user can only place towers on a tile(the mouse click location could be any point inside the tile)? Also, how would I keep the enemy units moving smoothly between tiles and not just jumping to the center of each tile?
    I got some great advice last time and any more advice or points in a good direction would be greatly appreciated.

    The reason to distribute your maze into nodes (tiles) is that pathfinding is slow, so you want to eliminate any notion of screen dimensions (pixels, inches, etc.) from A*. For all purposes, your maze is 100x100 pixels; any given object can choose between 100 horizontal and 100 vertical values.
    how would I keep the enemy units moving smoothly between tiles and not just jumping to the center of each tile?Although your units may only have 100x100 nodes to consider, you can still animate them walking between each adjacent node on the path. Remember that the pathfinding (per tier) will occur before anything actually moves.
    Still, this could look funny with only 100 nodes per axis. Units should use the shortest path that’s visible to them, and turning several degrees at each node will look choppy. So. I list three potential solutions here:
    &bull; Increase the number of nodes (the “accuracy”). Speed may be an issue.
    &bull; Use path smoothing algorithm. I haven’t seen your circumstance, but I would generally recommend this.
    &bull; Use multi-tiered/hierarchical pathfinding. This is probably more complex to implement.
    Note that although the second and third options are distinct, they may coincide (some smoothing algorithms use multiple tiers). Googling for ‘pathfinding smoothing’ returned many results; this one in particular looked useful: [Toward More Realistic Pathfinding|http://www.gamasutra.com/features/20010314/pinter_01.htm]
    How do I create a tile based view so that the user can only place towers on a tile(the mouse click location could be any point inside the tile)?If objects can be placed at arbitrary points, then A* needs to deem nodes impassable (your array’s 1) based on the objects placed in them. You have to be careful here and decide whether entire nodes should be ignored based on tower’s partial presence; for instance:
    |====|====|====|====|====|
    |====|====|====|===+|+++=|
    |====|====|====|===+|+++=|
    |====|====|====|====|====|
    |0~0=|====|====|====|====|pixels: = ; node dividers: | (and line breaks for vertical) ; tower: +
    The tower only covers ¼ of the node at (3, 3); should you eliminate it? Five solutions are obvious:
    • Ignore any node with any chunk of a tower in it.
    • Ignore any node entirely covered by a tower.
    • Ignore any node whose center is covered by a tower. This won’t work with multi-tiered pathfinding.
    • Ignore any node that has a tower covering any point the units are required to pass through. This will work with multi-tiered pathfinding.
    • Using multi-tiered pathfinding, consider only consider the sub-nodes that aren’t covered by a tower.
    I realize a 2D Array would probably be the best way just such as
    int[][] map = new int[100][100]
    For starters, if only want two values—passable and impassible—then a boolean would be better. But I would recommend against this. I’d bet you could write some OO code specific to your situation. You might want to use terrain costs, where nodes exist that A* would prefer over others.
    I hope I answered some of your questions. Let me know if you have more—or if I didn’t.
    Good luck.
    —Douglas

  • Simple Tap tile to open a folder?

    I would like to add a Simple Tap tile that opens a folder.  If I choose "Open a File" it won't let me pick a folder.  I can't type in the program box to add the command line switches to tell explorer.exe what folder to open.
    Suggestions?
    -Michele
    Solved!
    Go to Solution.

    It can be done, but it is tricky.  If you have any questions about these steps feel free to write back!
    1.  using windows explorer, create a shortcut to the folder you want (right-click, then choose "New", then "Shortcut"), e.g. "myshortcut.lnk".
    2.  create a SimpleTap tile to some existing document on your computer (it doesn't matter which document, you will be modifying it later)
    3.  using windows explorer, navigate to c:\users\USERNAME\appdata\roaming\lenovo\simpletap  (where USERNAME is the name of the user you log into on Windows).  Note that this folder may be hidden.
    4.  find the XML file that corresponds to the SimpleTap tile that you created in step 2 (you should be able to tell from the file name, and you can rename the file if you want).
    5.  using notepad, edit the XML file to modify the <path> section.  Point it to the shortcut lnk file you created in step 1.
    6.  save the file, then log off windows and log in again (to restart simpletap and load the modified XML file).
    Sorry this is so complicated, we didn't think of a case where someone would want to open a folder in SimpleTap, so we can address this in a future release.  But for now the steps I listed above should get you doing what you want to do.  Thanks for your feedback!

  • F4 Help in ALV GRID class based

    hi
    you have any idea about how to invoke the F4 help in ALV GRID Class based program.,
    if u have any other related document or program using F4 function in ALV GRId please send to me for reference
    Thanks & Regards
    K.G

    hi for what kind of fields you need to give f4.
    are they std or custom...
    please let me know about the fields..
    try to check my logic which i gave in the below post..
    it will give f4 help to the fields(if thet are standard table fieldS)
    Message was edited by: Vijay Babu Dudla

  • Tile Based Movement in AS3

    Hello i am still trying to create tile based movement. What i mean by that is the character can move smoothly but will always end up in the middle of a tile (just like the pokemon games). I have managed to make it work if the player uses only one key, however in combination with other keys it does not work. I was hoping someone could give me advise how to fix the code or perhaps some better/easier way to do it.
    Here is my code so far (this is only for left and right key) my character movieclip has the instance name char
    import flash.ui.Keyboard;
    import flash.events.KeyboardEvent;
    import flash.events.Event;
    import fl.transitions.easing.*;
    import com.greensock.*;
    var pixelsMoved:Number = 0;
    var pixelsLeft:Number = 0;
    var tweening:Boolean = false;
    var rightKeyDown:Boolean = false;
    var leftKeyDown:Boolean = false;
    addEventListener(Event.ENTER_FRAME,Loop);
    stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyPress);
    stage.addEventListener(KeyboardEvent.KEY_UP,KeyRelease);
    function Loop(event:Event):void
        if (tweening == false)
            if (rightKeyDown == true)
                char.x += 1;
                pixelsMoved += 1;
            else if (leftKeyDown == true)
                char.x -= 1;
                pixelsMoved += 1;
            if (pixelsMoved >= 25)
                pixelsMoved = 0;
                pixelsLeft = 25;
    function KeyPress(event:KeyboardEvent):void
        if (event.keyCode == Keyboard.RIGHT)
            rightKeyDown = true;
        if (event.keyCode == Keyboard.LEFT)
            leftKeyDown = true;
    function KeyRelease(event:KeyboardEvent):void
        pixelsLeft = 25 - pixelsMoved;
        if (event.keyCode == Keyboard.RIGHT)
            if (tweening == false)
                var moveRight:TweenLite = new TweenLite(char,pixelsLeft,{x:char.x + pixelsLeft,ease:None.easeNone,useFrames: true,onComplete: resetVars});
            rightKeyDown = false;
            tweening = true;
        if (event.keyCode == Keyboard.LEFT)
            if (tweening == false)
                var moveLeft:TweenLite = new TweenLite(char,pixelsLeft,{x:char.x - pixelsLeft,ease:None.easeNone,useFrames: true,onComplete: resetVars});
            leftKeyDown = false;
            tweening = true;
    function resetVars():void
        tweening = false;
        pixelsLeft = 0;
        pixelsMoved = 0;
    Any help is much apreciated!

    I am not sure I understand all the requirements. Also I guess you refer to pacman game - not pokemon.
    In any case, here is something that works pretty smooth at 60fps. Note there are no ENTER_FRAME handlers - all animations are handled by TweenLite.
    Just dump the code on a timeline in a new FLA - it is not meant to be injected into your existing code. So, this is just an independent fully functional concept. All objects are created dynamically by the script - you don't have to do anything to view/test this example.
    Read comments.
    import com.greensock.easing.Ease;
    import com.greensock.easing.Linear;
    import com.greensock.easing.Sine;
    import com.greensock.TweenLite;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.KeyboardEvent;
    import flash.geom.Point;
    import flash.ui.Keyboard;
    var board:Sprite;
    var tileSide:Number = 40;
    var numRows:int = 10;
    var numCols:int = 14;
    var char:Shape;
    var _currentKey:uint = 0;
    var tween:TweenLite;
    init();
    function init():void
              drawBoard();
              configStage();
    function configStage():void
              stage.scaleMode = StageScaleMode.NO_SCALE;
              stage.align = StageAlign.TOP_LEFT;
              stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
              stage.addEventListener(KeyboardEvent.KEY_UP, onKeyRelease);
    function onKeyRelease(e:KeyboardEvent):void
              // if the latest processed key was not release - we block the latest pressed key
              if (e.keyCode == _currentKey)
                        _currentKey = 0;
    function onKeyPress(e:KeyboardEvent):void
              currentKey = e.keyCode;
    function get tile():Shape
              var shape:Shape = new Shape();
              shape.cacheAsBitmap = true;
              var color:uint = 0x808080;
              var g:Graphics = shape.graphics;
              g.lineStyle(1, color);
              g.beginFill(0xEBEBEB);
              g.drawRect(-tileSide / 2, -tileSide / 2, tileSide, tileSide);
              return shape;
    function moveChar(targetX:int = 0, targetY:int = 0):void
              tween = TweenLite.to(char, 0.45, {x: targetX, y: targetY, ease: Linear.easeNone, onComplete: onTweenComplete});
    function onTweenComplete():void
               * need to do that
               * a. if key is kept pressed
               * c. to override situations when another key is pressed simulataneously
              currentKey = _currentKey;
    function set currentKey(value:uint):void
              var targetPosition:Number = 0;
               * key value is proccessed if
               * a. key is allowed - via switch
               * b. there is no key pressed before or ptreviously pressed key _currentKey is the same as new value
               * c. tween in not active
              if ((!_currentKey || _currentKey == value) && !tween._active)
                        switch (value)
                                  case Keyboard.RIGHT:
                                            targetPosition = char.x + tileSide;
                                            if (targetPosition < tileSide * numCols)
                                                      moveChar(targetPosition, char.y);
                                                      charRotation = 0;
                                            _currentKey = value;
                                            break;
                                  case Keyboard.LEFT:
                                            targetPosition = char.x - tileSide;
                                            if (targetPosition >= 0)
                                                      moveChar(targetPosition, char.y);
                                                      charRotation = 180;
                                            _currentKey = value;
                                            break;
                                  case Keyboard.UP:
                                            targetPosition = char.y - tileSide;
                                            if (targetPosition >= 0)
                                                      moveChar(char.x, targetPosition);
                                                      charRotation = -90;
                                            _currentKey = value;
                                            break;
                                  case Keyboard.DOWN:
                                            targetPosition = char.y + tileSide;
                                            if (targetPosition < tileSide * numRows)
                                                      moveChar(char.x, targetPosition);
                                                      charRotation = 90;
                                            _currentKey = value;
                                            break;
    function set charRotation(value:Number):void
              if (char.rotation == -180)
                        char.rotation = 180;
              if (char.rotation == 180 && value == -90)
                        char.rotation = -180;
              else if (char.rotation == -90 && value == 180)
                        value = -180;
              TweenLite.to(char, 0.2 * (Math.abs((char.rotation - value) / 90) || 1), {rotation: value});
    function drawBoard():void
              board = new Sprite();
              var numTiles:int = numRows * numCols;
              for (var i:int = 0; i < numTiles; i++)
                        var t:Shape = tile;
                        t.x = tileSide * (i % numCols);
                        t.y = tileSide * int(i / numCols);
                        board.addChild(t);
              board.addChild(addChar);
              addChild(board);
              board.x = board.y = 20 + tileSide / 2;
    function get addChar():Shape
              var radius:Number = tileSide / 2 - 4;
              char = new Shape();
              var g:Graphics = char.graphics;
              g.lineStyle(1);
              g.beginFill(0xff0000);
              g.drawCircle(0, 0, radius);
              g.endFill();
              g.lineStyle(2);
              g.moveTo(0, 0);
              g.lineTo(radius, 0);
              g.beginFill(0x000000);
              g.moveTo(radius, 0);
              g.lineTo(radius - 10, 4);
              g.lineTo(radius - 10, -4);
              g.endFill();
              tween = new TweenLite(char, 1, null);
              char.cacheAsBitmap = true;
              return char;

  • How to view semantic css based layouts in design view in dreamweaver?

    Hi all,
    I havent had a lot to do with CSS based layouts (tables have alwasy just worked for me fine) but I am wondering how do I view the semantic/css based layout in design view in Dreamweaver?
    As when I write the code, in design view its not showing me what the page will look like, I have to click on "Live View" to see what the page actually looks like.
    I guess I am asking is there a way to using WYSIWYG on css layouts in design view??? Just like I do table layouts (In design view I can grab the edge of the table and resize etc)?
    Any help would be great

    Lou yeah I don't think the term WYSIWYG really applys to dreamweaver anymore when building CSS layouts.
    The term "WYSIWYG" never applied to DW.  It was never such a thing, nor was any other HTML authoring, no matter what the marketing hype said.  It's not possible to deliver wysiwyg layouts when there are so many different browsers/platforms/versions to worry about.  This is particularly true when you go back to the era when WYSIWYG was actively used (but not with DW, which was not advertised in such a way) - Netscape 4, and IE5/Mac would alone be enough to destroy any layout....
    The view you are getting in Design view is happening because your CSS is misplaced BELOW the <body> tag - it should be in the head of the page (i.e., above </head>). Your CSS should never be placed within the body of the page.

  • How to animate from a png tile based image file

    Hi all,
    I would like to know is there any way to animate from a tile based .png image file? I have multiple images in 1 png file having slight changes in each image, which if cropped and put into layers one over the other, will give the feel of animation or a character moving or walking etc...
    I want to know can we do that kind of animation in flash as we do it in C++ or Java and how can we do it.
    Any help will be highly appreciated.
    Thank you
    Shanz - Iceheros

    I want to use action script to externally call/access  the png file with url request and url loader and animate the images from the tile based png image file.
    Anybody know how to do this in flash with as3.
    Here is the image for example:
    i want to animate this images and call it externally and access each tile 1 after another.
    Any Help???
    Thanks,
    Shanz - Iceheros

  • Effecient tile-based game setup

    Hello i am working on the engine for a tile based game, i have set up a two dimensional array with the number 1 representing a tile, and the number 0 representing an empty space. Currently i am using the following code which does work, but it is no very effecient because there are too many movieclips on the stage, which is causing my game to run at a lower framerate.
    function prepareGame():void
        for (var y:int = 0; y<mazeHeight; y++)
            for (var x:int = 0; x<mazeWidth; x++)
                if (myMaze[y][x] == 1)
                    var cell:MovieClip = new mc_tile();
                    cell.x = ts * x;
                    cell.y = ts * y;
                    addChild(cell);
    So my question is how do i optimize this code? If i could somehow make flash view all the movieclips as one big bitmap i guess that would solve the problem but i need some help.
    Any help is appreciated thank you!

    Here is an example of scrolling tiles (just paste the code on timeline).
    Background takes only stage dimensions but the impression is that it scrolls indefinitely.
    import flash.display.BitmapData;
    import flash.display.Graphics;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    var board:Sprite;
    var bitmapData:BitmapData;
    var appendBitmapData:BitmapData;
    var copyRect:Rectangle;
    var zeroPoint:Point = new Point();
    var targetPoint:Point;
    var speed:Number = -1;
    init();
    function init():void
              drawBoard();
              setGeometry();
              addEventListener(Event.ENTER_FRAME, animate);
    function drawBoard():void
              board = new Sprite();
              var tileInstance:Sprite = tile;
              bitmapData = new BitmapData(tileInstance.width, tileInstance.height);
              bitmapData.draw(tileInstance);
              var g:Graphics = board.graphics;
              g.beginBitmapFill(bitmapData, null, true);
              g.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
              addChild(board);
    function setGeometry():void
              appendBitmapData = new BitmapData(Math.abs(speed), bitmapData.height, true, 0x00000000);
              copyRect = new Rectangle(0, 0, Math.abs(speed), bitmapData.height);
              targetPoint = new Point(bitmapData.width - 1, 0);
    function animate(e:Event):void
              bitmapData.lock();
              appendBitmapData.copyPixels(bitmapData, copyRect, zeroPoint);
              bitmapData.scroll(speed, 0);
              bitmapData.copyPixels(appendBitmapData, copyRect, targetPoint);
              bitmapData.unlock();
    function get tile():Sprite
              var s:Sprite = new Sprite();
              var g:Graphics = s.graphics;
              g.lineStyle(2, 0x004000);
              g.beginFill(0x009700);
              g.drawRect(1, 1, 80, 50);
              return s;

  • Tile Based Collision Detection

    I am following Tonypa's Tile Based Tutorials and I have to
    say, they are great. He covers everything needed, except for one
    thing I am troubled on - Refering to Tutorial 9,
    http://www.tonypa.pri.ee/tbw/tut09.html,
    Stupid Enemy, instead of an enemy I want to make this a NPC who
    walks around in a village. So what do I do to make it so that I, or
    the char, doesn't walk right over the enemy/NPC? I am trying to
    develop an RPG, and it would look silly to have the character walk
    on top of the NPC. Can someone provided a snippet on how to make a
    collision detection with the NPC and not walk on top/under the NPC?
    One last favor to ask: What if I want to talk to the NPC if I
    am within a half tile? Would anyone be willing to share info on how
    this as well?
    Thanks a bunch in advance

    Ok, let me see if I get the read correct here: you have your scenery objects as tiles and when moving your players/NPC's through the scenery you are not scrolling the background as you go, but when you get to s certain point you want to scroll the tiles of the background also, so you can have new scenery cycle in as needed an still have the tiled background objects and new tiled background objects work for collision detection.
    If my take on your project is correct, then you have to make your tiles addressed with relative addressing formulas as you'll probably need to do with your sprites also.
    So the way this will go is that you have to make an offset and add them into your formula based on your character position. Then based on your character position you can choose to scroll your tiles left, right, up, down or what ever you choose to support. As a tile falls fully off the screen, you can dispose of it or cycle back through depending on how you implement your background.

  • Smooth walking on tile based map system

    Hello,
    I am developing a small game which requires the use of a map system. I chose to make that map system work upon a tile-based system. At the moment, each tile is 32x32, and I contain 24x20 tiles on my map.
    A walking system is also required for this game I'm developing, so I ran into some issues with making the loaded sprite walk "smoothly". At the moment, it jumps from tile to tile in order to walk. This makes it seem very unrealistic. I have tried many different ways to make the walking "smoother", but it requires me to change my tile's size in order to accommodate the sprite's size. This would not be an issue if I only used the same sprite in the game, but since I load different sprites which contain different measurements, I do not know how to make my walking system accommodate all of the sprites in order to make the walking realistic.
    I am not requesting any code whatsoever, simply ideas.
    Thank you

    If your image is opaque, then it may draw the edges around itself, but wouldn't this be a problem wether it were completely contained within a tile or not? If the image has transparency, then it doesn't matter if it's drawn as a rectangle, it would still appear to be contained only by its outline.
    If you're using a back-buffer (which I highly recommend if there is going to be animation or movement onscreen), then you may need to specify the type for the BufferedImage that you use as a buffer, I always use TYPE_INT_ARGB to make sure I have Alpha values (transparency).

Maybe you are looking for