Help needed in creating a simple paint application

I want to create a simple paint application using swings in java, i am able to draw different shapes using mouse but the problem is when i select some other shape it simply replaces the already drawn object with the new one but i want the already drawn object also, like appending, what should be done for this, any logic missing here or i should use some other approach?
Please help me
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bmp extends JFrame implements MouseListener, MouseMotionListener,
          ActionListener {
     int w, h;
     int xstart, ystart, xend, yend;
     JButton elipse = new JButton("--Elipse--");
     JButton rect = new JButton  ("Rectangle");
     JPanel mainframe = new JPanel();
     JPanel buttons = new JPanel();
     String selected="no";
     public void init() {
          //super("Bitmap Functions");
          // display.setLayout(new FlowLayout());
          buttons.setLayout(new BoxLayout(buttons,BoxLayout.Y_AXIS));
          buttons.add(Box.createRigidArea(new Dimension(15,15)));
          buttons.add(elipse);
          buttons.add(Box.createRigidArea(new Dimension(0,15)));
          buttons.add(rect);
          Container contentpane = getContentPane();
          contentpane.add(buttons, BorderLayout.WEST);
          //getContentPane().add(display, BorderLayout.WEST);
          addMouseListener(this); // listens for own mouse and
          addMouseMotionListener(this); // mouse-motion events
          setSize(1152, 834);
          elipse.addActionListener(this);
          rect.addActionListener(this);
          setVisible(true);
     public void mousePressed(MouseEvent event) {
          xstart = event.getX();
          ystart = event.getY();
     public void mouseReleased(MouseEvent event) {
          xend = event.getX();
          yend = event.getY();
          repaint();
     public void mouseEntered(MouseEvent event) {
          //repaint();
     public void mouseExited(MouseEvent event) {
          //repaint();
     public void mouseDragged(MouseEvent event) {
          xend = event.getX();
          yend = event.getY();
          repaint();
     public void mouseMoved(MouseEvent event) {
          //repaint();
     public static void main(String args[]) {
          bmp application = new bmp();
          application.init();
          application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     public void mouseClicked(MouseEvent arg0) {
     public void actionPerformed(ActionEvent event) {
          if (event.getSource() == elipse) {
               selected = "elipse";
               repaint();
          else if(event.getSource() == rect)
               selected = "rectangle";
               repaint();
     public void paint(Graphics g) {
          System.out.println(selected);
          super.paint(g); // clear the frame surface
          bmp b=new bmp();
          if (selected.equals("elipse"))
               w = xend - xstart;
               h = yend - ystart;
               if (w < 0)
                    w = w * -1;
               if (h < 0)
                    h = h * -1;
               g.drawOval(xstart, ystart, w, h);
          if (selected.equals("rectangle"))
               w = xend - xstart;
          h = yend - ystart;
          if (w < 0)
               w = w * -1;
          if (h < 0)
               h = h * -1;
          g.drawRect(xstart, ystart, w, h);
}

bvivek wrote:
..With this code, when i draw an elipse or line the image doesnt start from the point where i click the mouse. It added the MouseListener to the wrong thing.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener
       static BufferedImage image;
       Color color;
       Point start=new Point();
       Point end =new Point();
       JButton elipse=new JButton("Elipse");
       JButton rectangle=new JButton("Rectangle");
       JButton line=new JButton("Line");
       String selected;
       public test_bmp()
               color = Color.black;
               setBorder(BorderFactory.createLineBorder(Color.black));
       public void paintComponent(Graphics g)
               //super.paintComponent(g);
               g.drawImage(image, 0, 0, this);
               Graphics2D g2 = (Graphics2D)g;
               g2.setPaint(Color.black);
       if(selected=="elipse")
               g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
               System.out.println("paintComponent() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
               System.out.println("Start : "+start.x+","+start.y);
               System.out.println("End   : "+end.x+","+end.y);
       if(selected=="line")
               g2.drawLine(start.x,start.y,end.x,end.y);
       //Draw on Buffered image
       public void draw()
       Graphics2D g2 = image.createGraphics();
       g2.setPaint(color);
               System.out.println("draw");
       if(selected=="line")
               g2.drawLine(start.x, start.y, end.x, end.y);
       if(selected=="elipse")
               g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
               System.out.println("draw() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
               System.out.println("Start : "+start.x+","+start.y);
               System.out.println("End   : "+end.x+","+end.y);
       repaint();
       g2.dispose();
       public JPanel addButtons()
               JPanel buttonpanel=new JPanel();
               buttonpanel.setBackground(color.lightGray);
               buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
               elipse.addActionListener(this);
               rectangle.addActionListener(this);
               line.addActionListener(this);
               buttonpanel.add(elipse);
               buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
               buttonpanel.add(rectangle);
               buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
               buttonpanel.add(line);
               return buttonpanel;
       public static void main(String args[])
                test_bmp application=new test_bmp();
                //Main window
                JFrame frame=new JFrame("Whiteboard");
                frame.setLayout(new BorderLayout());
                frame.add(application.addButtons(),BorderLayout.WEST);
                frame.add(application);
                application.addMouseListener(application);
                application.addMouseMotionListener(application);
                //size of the window
                frame.setSize(600,400);
                frame.setLocation(0,0);
                frame.setVisible(true);
                int w = frame.getWidth();
            int h = frame.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(Color.white);
            g2.fillRect(0,0,w,h);
            g2.dispose();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       @Override
       public void mouseClicked(MouseEvent arg0) {
               // TODO Auto-generated method stub
       @Override
       public void mouseEntered(MouseEvent arg0) {
               // TODO Auto-generated method stub
       @Override
       public void mouseExited(MouseEvent arg0) {
               // TODO Auto-generated method stub
       @Override
       public void mousePressed(MouseEvent event)
               start = event.getPoint();
       @Override
       public void mouseReleased(MouseEvent event)
               end = event.getPoint();
               draw();
       @Override
       public void mouseDragged(MouseEvent e)
               end=e.getPoint();
               repaint();
       @Override
       public void mouseMoved(MouseEvent arg0) {
               // TODO Auto-generated method stub
       @Override
       public void actionPerformed(ActionEvent e)
               if(e.getSource()==elipse)
                       selected="elipse";
               if(e.getSource()==line)
                       selected="line";
               draw();
}

Similar Messages

  • Help needed in creating a Simple Service

    Hi, I'm a student studying java and would like to set up a simple SOAP service using J2EE and Apache Tomcat, but have fallen at the first hurdle it seems.
    Here's my problem:
    Whenever I try to use the SOAP admin tool to deploy a service, and I try to click on the "List" button, I get a compiler error when the browser is trying to compile "list.jsp".
    It says:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 4 in the jsp file: /admin/list.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    C:\Tomcat 4.1\work\Standalone\localhost\soap\admin\list_jsp.java:8: cannot resolve symbol
    symbol : class Constants
    location: package soap
    import org.apache.soap.Constants;
    ^
    C:\Tomcat 4.1\work\Standalone\localhost\soap\admin\list_jsp.java:9: package org.apache.soap.server does not exist
    import org.apache.soap.server.*;
    ^
    C:\Tomcat 4.1\work\Standalone\localhost\soap\admin\list_jsp.java:48: cannot resolve symbol
    symbol : variable Constants
    location: class org.apache.jsp.list_jsp
    String configFilename = config.getInitParameter(Constants.CONFIGFILENAME);
    I don't know why it can't find these class files, as I have definitely added the SOAP.jar file to my CLASSPATH.
    Can anybody help me please?
    Thanks

    Can you tell me which version of J2EE are you using ?
    -Arun

  • Urgent: need help in creation of a simple PCUI application

    Hi Experts,
        I am new to this PCUI. i need the help of urs.
    My requirement is
    >>>>To create a simple PCUI application.This contains a Search and Result list.
    >>>>Then i have to find the BSP coding or the HTML coding for the the PCUI
      application.
    >>>Can anyone please tell me the detailed steps for creating a simple PCUI application that displays the search and a result list???
    >>>Then how can i find the BSP coding or script(such as HTML,XML..) coding used for the  application.
    Pls help me , its urgent.... If anyone have any kind of useful documents pls mail me in my id <b>[email protected]</b>
    Thanks & Regards
    Sudhansu

    Hi Experts,
    I am new to this PCUI. i need the help of urs.
    My requirement is
    To create a simple PCUI application.This contains a Search and Result list.
    Then i have to find the BSP coding or the HTML coding for the the PCUI
    application.
    Can anyone please tell me the detailed steps for creating a simple PCUI application that displays the search and a result list???
    Then how can i find the BSP coding or script(such as HTML,XML..) coding used for the application.
    Pls help me , its urgent.... If anyone have any kind of useful documents pls mail me in my id [email protected]
    Thanks & Regards
    Preethika

  • Step by step instructions to create a Simple PCUI Application

    I am very new to PCUI and have been trying to get a simple application up and running for the last few days. There always seems to be some problem or the other. At times it gives a dump, at times it gives me a screen without the search request or search result area and when i get all of these done, my application just does not invoke the Query method.
    I would appreciate it if you could give me Step by Step instructions to create a simple PCUI application to search for some data from an existing database table and display it.
    Thanks in advance!!!

    Hi Mithun
    You can also download the PCUI Cookbook from:
    http://service.sap.com/instguides -> my SAP Business Suite Solutions -> my SAP CRM -> my SAP 2005. The title is PCUI Book for CRM 2005.
    The direct link is (which may change so I recommend that you follow the menu path) https://websmp209.sap-ag.de/~sapidb/011000358700001093962006E/PCUIBook50_06.pdf
    Refer the following weblog
    /people/vijaya.kumar/blog/2005/06/10/people-centric-user-interface-pcui--getting-started
    Hope this will help
    Regards,
    Rekha Dadwal
    <b>You gain a point for every point that you reward. So reward helpful answers generously</b>

  • How to create the simple EJB Applications.

    Hi
    I have asked about the what are the necessary softwares required for creating the Simple EJB Applications.
    I have
    Jdk 1.6,
    Netbeans 5.5,
    J2EE5 ,
    Apache Tomcat 5.5
    what are other necessary softwares?please tell me From where i get the source code samples?
    Please Tell me it is necessary for me..

    Hi U,
    Tomcat is only JSP/Servlet container -- no EJB support.
    Easiest is to download the Netbeans 6.1 bundle including Glassfish and JavaDB, thats all you need + JDK and Java EE of course.
    Glassfish has both web/JSP/Servlet-container and EJB-container, so Tomcat is not needed then.
    ( If for some reason you really want to use Tomcat, you can use it together with OpenEJB for example, to add EJB-support. )

  • Help needed to create desktop application background using javaFx.

    Hi,
    i need to create background for my desktop application in JavaFx. It have top side bottom menu bars to place icon buttons for my app. The whole scene need to resize. I had tried this using
    JavaFx composer. But my issue is like in java swing i can not able to create different panels and set different styles. Please help me on this issue.
    Thankyou.

    Hi mate take a rectangle and fill it to scene width !
    use fill gradient and bind it to your main scene.width
    for example :
    Rectangle {
    fill: color.Blue
    stroke: LinearGradient {
    startX: 125.0, startY: 0.0, endX: 225.0, endY: 0.0
    proportional: false
    stops: [
    Stop { offset: 0.0 color: Color.web("#1F6592") }
    Stop { offset: 1.0 color: Color.web("#80CAFA") }
    use appropriate start and offset then bind it to scene width and height.
    width : bind scene.width;
    height : bind scene.height ;

  • Help needed to create chartes in bw

    Hello
      i have charecter IO matid, salesorder, KF-IO price, quantity..
    I want a graphical representation in BEx.
    how can i do that?
    and
    BDS – Business Document Store --what it is? and where can i get the info on it?
    kasinath

    Hi kasinath,
    BDS is the storage place for all documents, like templates, iamges, documentation created for BW objects etc. BDS has its own user interface — Business Document Navigator (BDN) — which contains all essential BDS features. Check out:
    http://help.sap.com/saphelp_nw04/helpdata/en/dd/f5253715dfb808e10000009b38f889/content.htm
    You can create charts in the web reports. First you need to set up the BW query with the desired InfoObjects. The you need to open up the web application designer and create a web template with the chart icon. Assign your BEx query as the data provider for  this. Check out the following for more info:
    http://help.sap.com/saphelp_nw04/helpdata/en/44/b26a3b74a4fc31e10000000a114084/content.htm
    Hope this helps..please do not hesitate to assign points for all posts that have helped you.

  • Need to create a Web Dynpro Application for SRM Portal

    We need to recreate the start page for SRM Portal - (Supplier Self-Services) - without any images (as was delivered out of the box) - basically we need to break it down into 4 iViews:  All Purchase Orders; All Sched Agreement Releases; All Invoices and Credit Memos; and Account History.  All these iViews contains links.
    How would one create a Web Dynpro Application to create the above iViews?
    Regards,

    Hi zhang,
    take a look to this:
    KM:
    https://www.sdn.sap.com/irj/sdn/wiki?path=/display/kmc/resource%2band%2bcollection%2bversioning%2busing%2bkm%2bapis
    https://help.sap.com/javadocs/NW04S/SPS09/km/index.html
    Excel:
    /people/subramanian.venkateswaran2/blog/2006/10/02/enhanced-file-upload--uploading-and-processing-excel-sheets
    Hope this help you.
    Vito

  • Creating a simple image application in Apex

    select
    "IMAGE_ID",
    <img src="#OWNER#.deliver_thumbnail?p_image_id='||IMAGE_ID||'"/> thumbnail,
    "FILENAME" from "ORDIMAGE_IMAGES"
    where
    instr(upper("FILENAME"),upper(nvl(:P1_REPORT_SEARCH,"FILENAME"))) >
    Its is showing an error
    showing only the coding part when i run the application instead of showing image....
    can you please help me rectify the error
    Edited by: 880021 on 17-Aug-2011 20:58

    Creating a simple image application in Apex
    Create a new application from scratch. Name it ORDImages_images.
    Add a Report and Form Page based on your ORDImage_images table. Ensure that you select a Classic Report (i.e. not Interactive, which is the default). As expected, two pages are created.
    Continue to create the application and then run it.
    After the login page, there will be spurious entries for image and thumbnail.
    This is expected because of the ORDImage columns in the images table.
    Edit Page 1 and open the Images Region
    The Source entry is
    select
    "IMAGE_ID",
    "IMAGE",
    "THUMBNAIL",
    "FILENAME"
    from "ORDIMAGE_IMAGES"
    where
    instr(upper("FILENAME"),upper(nvl(:P1_REPORT_SEARCH,"FILENAME"))) > 0
    In SQL Developer, create the deliver_images_thumb procedure
    CREATE OR REPLACE PROCEDURE deliver_thumbnail(p_image_id IN NUMBER) IS
    l_thumbnail ORDSYS.ORDImage;
    BEGIN
    -- Fetch the thumbnail from the database
    SELECT thumbnail
    INTO l_thumbnail
    FROM ORDImage_images
    WHERE image_id = p_image_id;
    -- Check update time if browser sent If-Modified-Since header
    IF ordplsgwyutil.cache_is_valid( l_thumbnail.getUpdateTime() )THEN
    owa_util.status_line( ordplsgwyutil.http_status_not_modified );
    RETURN;
    END IF;
    -- Set the MIME type and deliver the image to the browser.
    owa_util.mime_header( l_thumbnail.mimeType, FALSE );
    ordplsgwyutil.set_last_modified( l_thumbnail.getUpdateTime() );
    owa_util.http_header_close();
    IF owa_util.get_cgi_env( 'REQUEST_METHOD' ) <> 'HEAD' THEN
    wpg_docload.download_file( l_thumbnail.source.localData );
    END IF;
    END;
    Then
    GRANT EXECUTE ON deliver_thumbnail TO PUBLIC;
    Return to Apex and change the Source entry to
    select
    "IMAGE_ID",
    '<img src="#OWNER#.deliver_thumbnail?p_image_id='||IMAGE_ID||'"/>' thumbnail,
    "FILENAME" from "ORDIMAGE_IMAGES"
    where
    instr(upper("FILENAME"),upper(nvl(:P1_REPORT_SEARCH,"FILENAME"))) > 0
    Apply changes and run the application
    You can now search on substrings of filenames. Note that the image_ID is not shown. To rectify this, Edit Page 1 and open Report in Regions.
    Edit the image_id and under Column Link, change the Link Text to #IMAGE_ID#. Also change the Heading in the Column Attributes to Image ID.
    Apply the changes and re-run.
    Clicking on the image_id link takes you to Page 2 – the form for that image.
    Page 2 is sparse so reveal the image_id by Editing Page 2 and opening the P2_IMAGE_ID Page Item. Change Display as Hidden to Text Field. Apply changes and re-run.
    In Page Items, open and delete the P2_THUMBNAIL item.
    Open the P2_IMAGE item.
    Under Name, change the Display As entry to Display Image (from the select list).
    Under Settings, change the Based On entry to BLOB Column returned by SQL Statement
    Enter
    SELECT i.image.source.localdata
    FROM ORDimage_images i
    WHERE image_id = :P2_IMAGE_ID
    as the SQL Statement
    Apply changes and re-run the application
    Making an image clickable
    Edit Page 1 and open Report in Regions. Edit THUMBNAIL and under Column Link, insert
    <img src="#OWNER#.deliver_thumbnail?p_image_id=#IMAGE_ID#"/>
    as Link Text.
    Select Page 2 as the Target Page in this Application.
    Finally, set Item 1's name to P2_IMAGE_ID and its Value to #IMAGE_ID#
    Removing the Spreadsheet link
    Under Report Attributes, set Enable CSV Output to No

  • Please help - need to do a simple animatic...

    Hi All.
    I need to put together a simple animatic sequence tomorrow for a production company. Mostly it'll consist of cross dissolves between drawings. Occasionally, though, I'll need to do a simple movement of a piece of a drawing (i.e. the person's head turns to the left or right). This, too, can be a cross dissolve, but would involve having just that portion of the drawing as a separate image with an alpha channel (I assume this is correct?).
    I'll be cutting in FCP.
    My question is, is creating the cutout image easiest in Photoshop? Do I need to concern myself with square vs. rectangular pixels?
    This will be a PAL project most likely.
    Thanks in advance for any help you can offer. It's most appreciated.
    travis

    You may want to try using these photoshop settings :
    width : 1024 pixels
    height : 576 pixels
    pixel aspect : square
    This will save you having to tick the anamorphic section in the browser each time you bring in a graphics file. FCP studio will just automatically scale the clip to fit your sequence when you drag it into the timeline. Also photoshop prefers you to work in square pixels and it will give you a slightly better preview image quality (though working with another pixel aspect ratio wont effect the ACTUAL quality of the file - just what you see in photoshop).
    As andy says - its difficult to tell which type of masking tool you will need without seeing actual examples of the images. Personally I feel that the of the in built photoshop tools - the poloygonal lassoo offers you the most control.
    Will you actually have to cut out the images though ?? If all that changes from one drawing to the next is the head turning - and the backgorund stays exactly the same and static, you should be able to just dissolve between the two with just the head turning and everything else in the image remaining uncnchanged and uninterrupted. A simplified example of this would be to genreate several lines of text in FCP. Drag the text into your timeline and copy and paste another instance of exactly the same text next to it. Change ONE line of text in the second instance to something completely different. Now dissolve between the two. All you should see change is the one line of text that you changed dissolving into the other.The rest of the text in the image should remain exactly the same. The same principle should apply to two drawings that are indentical in every respect but one e.g a head turning.
    Obviously if the drawings differ completely - then yes it will be far better for you to cut out the relevant sections in photoshop, save as a graphics file with an alpha/transparencey channel e.g PNG, then overlay the graphic over the original shot in the timeline and dissolve up to it at the correct point in the timeline.
    Hope any of this was of a little help
    All the best
    JB

  • Help needed . Creating DSN in Unix

    Hi The Oracle server is running on Unix platform. I need to connect the server from my client application which recoganises the DB using its DSN. Please help me in creating the DSN in the Unix environment.
    Any help will be Apreciated.
    Regards,
    Badhri([email protected])

    I'm a bit confused. You need to have an ODBC DSN on your client machine, not on your server machine. ODBC is generally a Windows-only technology-- at least the Oracle ODBC driver is available only on Windows. There are some third-parties that have created various Unix ODBC drivers, however.
    If you need to create a DSN on a Unix box, you must not be using the Oracle driver or the standard DSN configuration dialogs. You'd have to contact whatever third-party driver provider you're using to find out how they handle things.
    Justin

  • Help needed with creating Flash game

    Hello,
    I need to create Flash educational/quiz game for one of my clients. It would be based on concept like these ones for example:
    Example 1
    http://go.ucsusa.org/game/
    Example 2
    http://www.zdravlje.hr/igre/stop-aids/
    Note: when you open this link you will see two text boxs which you first must fill. On the left side text box "Upišite ime" means "Type your name" and right one "Upišite godinu svog rođenja" means "Year of birth"
    What is interesting about this type of games is that they are classic games (for example game Labirint where you have to find way out), but during play pop-up questions starts to appear to test end user knowledge abot certain topic (in example 2 topic is about AIDS/HIV). In case of my client, topic is about Eco environment.
    Here is where my trouble starts;) : I found many useful free tutorials how to create simple flash game (most interesting example I found is this one http://www.strille.net/tutorials/snake/index.php)  BUT I dont know how make that system of popup questions appear during game similar to Example 1 and Example 2?
    Any help is appreciated and thanks in advance for promt reply.
    Greetings,
    Adnan

    Update: I have just read all instructions in Snake tutorial which helped be better realize how Snake game works.
    a) This is what I plan to realize for my client:
    1. Snake game which end users will play and during play pop-up/quiz quesions will appear on topic Eco environment;
    2. For example when end user earns 50 points he must answer some of the random questions like "Q:How many ton of waste are produced by US livestock each year" with three answers A1: "1 milion" A2: "1 bilion" A3: "2 bilion" and after user scores 100 points then another question pops up and so on. This is all true if all answers are correct but in case he answer some question wrong than game can start from begining or another solution could be he looses -50 or -100 points.
    3. At the end, user which gains most points wins.
    b) This is what I have done till now:
    I have this file http://www.strille.net/tutorials/snake/snakeGameWithHighscore.zip which I partly understand how it works with my Flash knowladge.
    All functions and main game engine is in layer code:
    "// Snake Game by Strille, 2004, www.strille.net
    blockSize = 8;   // the block width/height in number of pixels
    gameHeight = 30; // the game height in number of blocks
    gameWidth  = 45; // the game width in number of blocks
    replaySpeed = 1;
    SNAKE_BLOCK = 1; // holds the number used to mark snake blocks in the map
    xVelocity = [-1, 0, 1, 0]; // x velocity when moving left, up, right, down
    yVelocity = [0, -1, 0, 1]; // y velocity when moving left, up, right, down
    keyListener = new Object(); // key listener
    keyListener.onKeyDown = function() {
        var keyCode = Key.getCode(); // get key code
        if (keyCode > 36 && keyCode < 41) { // arrow keys pressed (37 = left, 38 = up, 39 = right, 40 = down)...
            if (playRec) {
                if (keyCode == 37 && replaySpeed > 1) {
                    replaySpeed--;
                } else if (keyCode == 39 && replaySpeed < 10) {
                    replaySpeed++;
            } else if (game.onEnterFrame != undefined) { // only allow moves if the game is running, and is not paused
                if (keyCode-37 != turnQueue[0]) { // ...and it's different from the last key pressed
                    turnQueue.unshift(keyCode-37); // save the key (or rather direction) in the turnQueue
        } else if (keyCode == 32) { // start the game if it's not started (32 = SPACE)
            if (!gameRunning || playRec) {
                startGame(false);
        } else if (keyCode == 80) { // pause/unpause (80 = 'P')
            if (gameRunning && !playRec) {
                if (game.onEnterFrame) { // pause
                    delete game.onEnterFrame; // remove main loop
                    textMC.gotoAndStop("paused");
                } else { // exit pause mode
                    game.onEnterFrame = main; // start main loop
                    textMC.gotoAndStop("hide");
    Key.addListener(keyListener);
    function startGame(pRec) {
        x = int(gameWidth/2); // x start position in the middle
        y = gameHeight-2;     // y start position near the bottom
        map = new Array(); // create an array to store food and snake
        for (var n=0;n<gameWidth;n++) { // make map a 2 dimensional array
            map[n] = new Array();
        turnQueue = new Array(); // a queue to store key presses (so that x number of key presses during one frame are spread over x number of frames)
        game.createEmptyMovieClip("food", 1); // create MC to store the food
        game.createEmptyMovieClip("s", 2); // create MC to store the snake
        scoreTextField.text = "Score: 0"; // type out score info
        foodCounter = 0; // keeps track of the number of food movie clips
        snakeBlockCounter = 0; // keeps track of the snake blocks, increased on every frame
        currentDirection = 1; // holds the direction of movement (0 = left, 1 = up, 2 = right, 3 = down)
        snakeEraseCounter = -1; // increased on every frame, erases the snake tail (setting this to -3 will result in a 3 block long snake at the beginning)
        score = 0; // keeps track of the score
        ticks = lastRec = 0;
        recPos = recFoodPos = 0;
        playRec = pRec;
        if (!playRec) {
            textMC.gotoAndStop("hide"); // make sure no text is visible (like "game over ")
            highscores.enterHighscoreMC._visible = false;
            statusTextField.text = "";
            recTurn = "";
            recFrame = "";
            recFood = "";
            game.onEnterFrame = main; // start the main loop
        } else {
            if (loadedRecordingNumber != -1) {
                var n = getLoadedRecordingNumberHighscorePos(loadedRecordingNumber);
                statusTextField.text = "Viewing " + highscores[n].name.text + "'s game (score " + highscores[n].score.text + ")";
            } else {
                statusTextField.text = "Viewing your game";
            game.onEnterFrame = replayMain; // start the main loop
        placeFood("new"); // place a new food block
        gameRunning = true; // flag telling if the game is running. If true it does not necessarily mean that main is called (the game could be paused)
    function main() { // called on every frame if the game is running and it's not paused
        if (playRec) {
            if (ticks == lastRec+parseInt(recFrame.charAt(recPos*2)+recFrame.charAt(recPos*2+1), 36)) {
                currentDirection = parseInt(recTurn.charAt(recPos));
                lastRec = ticks;
                recPos++;
        } else if (turnQueue.length) { // if we have a turn to perform...
            var dir = turnQueue.pop(); // ...pick the next turn in the queue...
            if (dir % 2 != currentDirection % 2) { // not a 180 degree turn (annoying to be able to turn into the snake with one key press)
                currentDirection = dir; // change current direction to the new value
                recTurn += dir;
                var fn = ticks-lastRec;
                if (fn < 36) {
                    recFrame += " "+new Number(fn).toString(36);
                } else {
                    recFrame += new Number(fn).toString(36);
                lastRec = ticks;
        x += xVelocity[currentDirection]; // move the snake position in x
        y += yVelocity[currentDirection]; // move the snake position in y
        if (map[x][y] != SNAKE_BLOCK && x > -1 && x < gameWidth && y > -1 && y < gameHeight) { // make sure we are not hitting the snake or leaving the game area
            game.s.attachMovie("snakeMC", snakeBlockCounter, snakeBlockCounter, {_x: x*blockSize, _y: y*blockSize}); // attach a snake block movie clip
            snakeBlockCounter++; // increase the snake counter
            if (map[x][y]) { // if it's a not a vacant block then there is a food block on the position
                score += 10; // add points to score
                scoreTextField.text = "Score: " + score; // type out score info
                snakeEraseCounter -= 5; // make the snake not remove the tail for five loops
                placeFood(map[x][y]); // place the food movie clip which is referenced in the map map[x][y]
            map[x][y] = SNAKE_BLOCK; // set current position to occupied
            var tailMC = game.s[snakeEraseCounter]; // get "last" MC according to snakeEraseCounter (may not exist)
            if (tailMC) { // if the snake block exists
                delete map[tailMC._x/blockSize][tailMC._y/blockSize]; // delete the value in the array m
                tailMC.removeMovieClip(); // delete the MC
            snakeEraseCounter++; // increase erase snake counter   
        } else { // GAME OVER if it is on a snake block or outside of the map
            if (playRec) {
                startGame(true);
            } else {
                gameOver();
            return;
        ticks++;
    function replayMain() {
        for (var n=0;n<replaySpeed;n++) {
            main();
    function gameOver() {
        textMC.gotoAndStop("gameOver"); // show "game over" text
        delete game.onEnterFrame; // quit looping main function
        gameRunning = false; // the game is no longer running
        enterHighscore();
    function placeFood(foodMC) {
        if (playRec) {
            var xFood = parseInt(recFood.charAt(recFoodPos*3)+recFood.charAt(recFoodPos*3+1), 36);
            var yFood = parseInt(recFood.charAt(recFoodPos*3+2), 36);
            recFoodPos++;
        } else {
            do {
                var xFood = random(gameWidth);
                var yFood = random(gameHeight);
            } while (map[xFood][yFood]); // keep picking a spot until it's a vacant spot (we don't want to place the food on a position occupied by the snake)
            if (xFood < 36) {
                recFood += " "+new Number(xFood).toString(36);
            } else {
                recFood += new Number(xFood).toString(36);
            recFood += new Number(yFood).toString(36);
        if (foodMC == "new") { // create a new food movie clip
            foodMC = game.food.attachMovie("foodMC", foodCounter, foodCounter);
            foodCounter++;
        foodMC._x = xFood*blockSize; // place the food
        foodMC._y = yFood*blockSize; // place the food
        map[xFood][yFood] = foodMC; // save a reference to this food movie clip in the map
    //- Highscore functions
    loadHighscores();
    enterHighscoreKeyListener = new Object();
    enterHighscoreKeyListener.onKeyDown = function() {
        if (Key.getCode() == Key.ENTER) {
            playerName = highscores.enterHighscoreMC.nameTextField.text;
            if (playerName == undefined || playerName == "") {
                playerName = "no name";
            saveHighscore();
            Key.removeListener(enterHighscoreKeyListener);
            Key.addListener(keyListener);
            highscores.enterHighscoreMC._visible = false;
            loadedRecordingNumber = -1;
            startGame(true);
    function enterHighscore() {
        if (score >= lowestHighscore) {
            highscores.enterHighscoreMC._visible = true;
            highscores.enterHighscoreMC.focus();
            Key.removeListener(keyListener);
            Key.addListener(enterHighscoreKeyListener);
        } else {
            loadedRecordingNumber = -1;
            startGame(true);
    function getLoadedRecordingNumberHighscorePos(num) {
        for (var n=0;n<10;n++) {
            if (num == highscores[n].recFile) {
                return n;
    function loadHighscores() {
        vars = new LoadVars();
        vars.onLoad = function(success) {
            for (var n=0;n<10;n++) {
                var mc = highscores.attachMovie("highscoreLine", n, n);
                mc._x = 5;
                mc._y = 5+n*12;
                mc.place.text = (n+1) + ".";
                mc.name.text = this["name"+n];
                mc.score.text = this["score"+n];
                mc.recFile = parseInt(this["recFile"+n]);
            lowestHighscore = parseInt(this.score9);
            if (!gameRunning) {
                loadRecording(random(10));
            delete this;
        if (this._url.indexOf("http") != -1) {
            vars.load("highscores.txt?" + new Date().getTime());
        } else {
            vars.load("highscores.txt");
    function loadRecording(num) {
        vars = new LoadVars();
        vars.onLoad = function(success) {
            if (success && this.recTurn.length) {
                recTurn = this.recTurn;
                recFrame = this.recFrame;
                recFood = this.recFood;
                startGame(true);
            } else {
                loadRecording((num+1)%10);
                return;
            delete this;
        loadedRecordingNumber = num;
        if (this._url.indexOf("http") != -1) {
            vars.load("rec"+loadedRecordingNumber+".txt?" + new Date().getTime());
        } else {
            vars.load("rec"+loadedRecordingNumber+".txt");
    function saveHighscore() {
        sendVars = new LoadVars();
        for (var n in _root) {
            if (_root[n] != sendVars) {
                sendVars[n] = _root[n];
        returnVars = new LoadVars();
        returnVars.onLoad = function() {
            if (this.status == "ok") {
                loadHighscoresInterval = setInterval(function() {
                    loadHighscores();
                    clearInterval(loadHighscoresInterval);
                }, 1000);
            delete sendVars;
            delete this;
        sendVars.sendAndLoad("enterHighscore.php", returnVars, "POST");
    function startClicked() {
        if (!gameRunning || playRec) {
            if (highscores.enterHighscoreMC._visible) {
                Key.removeListener(enterHighscoreKeyListener);
                Key.addListener(keyListener);
                highscores.enterHighscoreMC._visible = false;
            startGame(false);
    function viewGame(lineMC) {
        loadRecording(lineMC.recFile);
        statusTextField.text = "Loading " + lineMC.name.text + "'s game...";
    Now what is left to do is somehow to iclude educational quiz in this game/code. First idea that came to me is same thing Ned suggested: to create some unique movie clip which would contain all data/questions lined up but main problem for me is how to "trigger" that movie clip to play only AFTER end user clicks on "Start game" or SPACE to restart? Not sure how to solve this issue?

  • Help need to create a query

    I need to fetch records from a table. Please help me to create a query
    The Tablename is Employee. It has the following records
    Department Empname Gender
    Finance Tom Male
    Finance Rick Male
    Finance Stacy Female
    Corporate Tom Male
    Corporate Rob Male
    I want to select the value of the Gender field from the Employee table corresponding to a Department
    If all the values in the Gender field are 'MALE' corresponding to 'finance' in the Department field, the value should be 'MALE'
    If there is a value 'FEMALE', the gender corresponding to the Empname 'TOM' should be considered as the gender

    Tables have rows - not records.
    Your question is a basic SQL language question - which means you do not know the SQL language. This forum is not a classroom for teaching you the SQL language.
    Use the following as the basic outline of how your SQL language statement need to look like for selecting the required from the table:
    SELECT
      <<sql projection goes here>>
    FROM <<table name goes here>>
    WHERE <<filter conditions go here>>
    {code}
    The SQL projection specifies the list of columns the SQL need to return to the caller.
    The filter condition is basic predicates and AND and OR  can be used for multiple predicates.
    Go to http://tahiti.oracle.com and look for the +SQL Reference Guide+ for the Oracle version you are using. The +SELECT+ statement syntax is covered in detail and sample statements are provided.
    And please do not expect this forum to be used as a classroom, or expect this forum to do your homework for a class.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help needed to create Quik Time VR movies, step by step

    Hello,
    thank you for your attenction.
    I need to create Quick time vr movies, and I need to know the exact sequance of steeps to do it, and if the starting point I use is correct.
    1) I shooted a sequence of photos with my digital camera (for example: www.stebianchi.com/quicktimevrhelp/still-photo.jpg).
    2) Then, with photoshop (CS4) I choose: Automate/photomerge and I select all them to joint them in a bigger 360° panoramic one (www.stebianchi.com/quicktimevrhelp/pan.jpg). If, untill here, all is correct, the first question: in photoshop Photomerge layout option, do I have to choose one voice "auto, perspective, cylindrical, spherical, etc..." rather than anoter one of these?
    3) from here, I really need your help.
    First of all: the great doubt:
    My photos can not cover a spherical panorama, they're only a "ring" around a center (and not a spherical texture). To cover all the surface (or almost all, ok...) of my ambient, do I have to use a wider lens on my camera or there is a different solution (for ex a vertical photomerge?).
    4) Done this, I think I shuold buy a software like Cubic converter, to set and export the QTVR movie. Right?
    Thanks a lot guys,
    all the best!
    Stefano

    You can call your local apple store(find one on the home page of apple.com) and they will give you instructions how to convert DVD to iPod. That is what they told me, but from what I heard, you may need more than Quicktime Pro. Just call and ask them, because if you make a manual of how to do it, it could help me a lot.
    (I'm looking for a good DVD converter, already know some, beside the internet download ones)

  • Help Needed in Creating Java Class and Java Stored Procedures

    Hi,
    Can anyone tell how can i create Java Class, Java Source and Java Resource in Oracle Database.
    I have seen the Documents. But i couldn't able to understand it correctly.
    I will be helpful when i get some Examples for creating a Java Class, Java Source and Stored Procedures with Java with details.
    Is that possible to Create a Java class in the oracle Database itself ?.
    Where are the files located for the existing Java Class ?..
    Help Needed Please.
    Thanks,
    Murali.v

    Hi Murali,
    Heres a thread which discussed uploading java source file instead of runnable code on to the database, which might be helpful :
    Configure deployment to a database to upload the java file instead of class
    The files for the java class you created in JDev project is located in the myworks folder in jdev, eg, <jdev_home>\jdev\mywork\Application1\Project1\src\project1
    Hope this helps,
    Sunil..

Maybe you are looking for

  • Particular web page will not load in safari or firefox

    when i try to load web site www.mapmyride.com, safari will not load the web page. I have tried other web sites and it works fine. It does not give any message to indicate that there's a problem. I can load the same web page on my iphone

  • Long standing bug in deployJava.js has not been fixed

    I thin it's outrageous that the bug reported here deployJava.js and HTTPS Problem has not been fixed. I can only assume that Oracle has abandoned Java.

  • Javascript in wiki's

    I am trying to edit source code and place javascript in the page of a wiki page and it strips away the code. Is this a security thing ? How do I enable this ? Anyone point me in a direction out there !!! cheers all !

  • Is there a fix for iphoto 11 book crashes

    I made the HUGE mistake of upgrading to iLife 11 and now iPhoto refuses to allow me to use the book makeing feature.  The second I attempt to make a book from an exsisting album or edit books from a current project, it crashes.  I have done all the u

  • Opening device /dev/sg3 failed - access denied to /dev/sg* device file

    Opening device /dev/sg3 failed - access denied to /dev/sg* device file (OB scsi device driver) Got this message when running an automated RMAN job. To my knowledge the only thing that has changed since being able to run RMAN jobs with OSB and not bei