I'm just starting learning Java after a few years of HTML/CSS coding so hopefully I'm not asking a old or stupid question here but any help explaining this problem would be very much appreciated.
I'm currently working through the Stanford CS106A online material and I've reached week 6, Assignment 2, Question 3 (http://see.stanford.edu/materials/icspmcs106a/13-assignment-2-simple-java.pdf).
As you can see it requires the placement of various objects on the screen to create the Graphics Hierarchy, as described. My plan was to use the centre coordinates to relatively place all the objects on the screen. However I've hit a problem that I can't seem to find an answer to. The course describes how Method Decomposition should allow each method to handle one problem (Single Responsibility Principle, I believe) so I have written the first part of my code as such:
//Import any libraries
import acm.program.*;
import acm.graphics.*;
public class GraphicsHierarchy extends GraphicsProgram {
//Define constants
static final int BOX_WIDTH = 200;
static final int BOX_HEIGHT = 75;
public void run() {
placeGRect();
}
//Find centre x & y
double centre_x = getWidth() / 2; //check this
double centre_y = getHeight() * 0.5;//and this
//placeGRect method
public void placeGRect() {
for (int count = 0; count < 4; count++) {
GRect box = new GRect (BOX_WIDTH, BOX_HEIGHT);
add(box);
switch (count) {
case 0:
box.setLocation(centre_x, 75);
break;
case 1:
box.setLocation((centre_x * 0.5), 250);
break;
case 2:
box.setLocation(centre_x, 250);
break;
case 3:
box.setLocation((centre_x * 1.5), 250);
break;
}
}
}
}
However this doesn't work due to the centre_x & centre_y producing zero values. I discovered this by changing the program to a ConsoleProgram and having the getWidth & getHeight lines inside the run() method (and println their values on screen), which then produced the required values but didn't pass them to the GRect method (so still didn't work). However if I have the getWidth/getHeight lines listed out of the run() then they don't produce any values for relative positioning.
My question is given that each method should handle one task and (as much as possible) methods should be defined out of the run() method, then how I can I get the getWidth/getHeight values to the placeGRect() method without having one big block of code within the run() method. Which I understand is bad practise.
I'm not after any code to solve this, I really need to understand the principles of this so I can write effective code in the future. I prefer understanding to parrot-fashion code copying.
Thanks in advance for any help.
In your specific example:
You have declared centre_x and centre_y as instance variables. When your program first creates an instance of GraphicsHierarchy the order of object creation is as such:
ClassLoader loads the class... static variables (BOX_WIDTH,BOX_HEIGHT) are assigned specified values;
Space is allocated on the heap for an instance of GraphicsHierarchy (enough space to hold the instance variables - a double for centre_x and a double for centre_y- including space for base class instance variables)
Instance variables are set to default values: centre_x = 0, centre_y = 0
The GraphicsHierarchy default constructor is called (which does nothing other than call the base class constructor - GraphicsProgram).
The base class will go through steps 1-4 and when it's finished execution returns to GraphicsHiearchy which now evaluates explicit instance variable initializers before executing any remaining constructor statements (which in the case of the default constructor, there are none).
(additional reference on this process http://java.dzone.com/articles/java-object-initialization)
Having said all of that, it would appear that when your class GraphicsHierarchy gets to step 5 and tries to assign values to centre_x and centre_y, the subsystem that getWidth and getHeight rely upon is not ready (i.e. a window or canvas has not been created yet, so the methods return 0). But when you moved your assignments inside run and getWidth/getHeight returned values, that would imply whatever method is calling run has first gone through the necessary window creation steps.
Etienne de Martel's suggestion is fine. It delays assignment of your centre values until right before they are needed. If you'd rather, you could create an init method and move the assignments inside the init method, and then call init as the first step of run
private void init() {
centre_x = getWidth / 2;
centre_y = getHeight * 0.5;
}
public void run() {
init();
placeGRect();
}
This is nearly the same thing as Martel's suggestion, although if you find later you have other initialization code that needs to happen, you can throw it in the same place.
As for crafting flexible code you might think about renaming placeGRect to placeGRects and passing in array of points (or Collection if you prefer) placeGRects(Point[] points)
(you can use Java.awt.Point or define your own Point class)
In this way, your placeGRects method is simplified. It no longer decides how many boxes to render (the array that is passed in does). It also doesn't determine where those new boxes are located (again the array of Point objects do). It simply loops through the size of the array, makes a new box, adds it, and sets the location.
private Point[] boxPoints;
public void run() {
init();
placeGRects(boxPoints);
}
public void placeGRects(Point[] points) {
for(int i=0;i<points.length;i++) {
GRect b = new GRect(BOX_WIDTH,BOX_HEIGHT);
add(b);
b.setLocation(points[i].x,points[i].y);
}
}
And you can put your Point array initialization inside your new init() method.
private void init() {
centre_x = getWidth / 2;
centre_y = getHeight * 0.5;
boxPoints = {new Point(centre_x, 75),new Point(centre_x * 0.5, 250)};
}
It makes your code easier to understand and modify when needed.
Perhaps I don't understand your question, but why not pass them as parameters?
protected void placeGRect(double centre_x, double centre_y) {
// ...
}
You can then call placeGRect like so:
public void run() {
placeGRect(getWidth() / 2, getHeight() * 0.5);
}
Very nice question! How to compose your methods is a matter of intuition rather than strict guidelines.
Certainly, methods should be focused on doing one thing and one thing only. Firstly, having short methods (even one-liners!) improves the understandability of the code. As a very rough example, think of this:
if (DateUtils.before(ticket.getExpirationDate(), new Date())) {
accept(ticket);
}
and then this
if (isNotExpired(ticket)) {
accept(ticket);
}
...
private boolean isNotExpired(Ticket t) {
return DateUtils.before(t.getExpirationDate(), now());
}
private Date now() {
return (new Date());
}
Pay attention to how the introduction of one line methods isNotExpired() and now() significantly improved your undestanding of what the code does.
Here's another example, this time that has to do with constructing objects:
Loan l1 = new Loan(15000, 36, f7.2, 2.5);
Loan l2 = new Loan(15000, 36, f7.2);
vs.
Loan l1 = Loan.newSubsidizedLoan(15000, 36, f7.2, 2.5);
Loan l2 = Loan.newNormalLoan(15000, 36, f7.2);
Note in this example how wrapping the constructors in two different methods significantly improves the documentation of code (without even needing to write comments);
If you are interested on the general topic of coding style, you should read this book.
Cheers
L.
Your code doesn't seem to include the getWidth() and getHeight() methods. Also, the following piece of code is totally wrong as a placement and should be placed in a constructor:
double centre_x = getWidth() / 2; //check this
double centre_y = getHeight() * 0.5;//and this
Should become
private double centre_x;
private double centre_y;
GraphicsHierarchy(){
centre_x = GraphicsHierarchy.BOX_WIDTH / 2;
centre_y = GraphicsHierarchy.BOX_HEIGHT * 0.5;
}
This code will at least compile, but consider the solution described below, which is even better.
Considering that you have defined BOX_WIDTH and BOX_HEIGHT as static variables, you can always find centre_x and centre_y. Therefore, you don't even need to define BOX_WIDTH and BOX_HEIGHT
You can define your class like this:
//Import any libraries
import acm.program.*;
import acm.graphics.*;
public class GraphicsHierarchy extends GraphicsProgram {
public void run() {
placeGRect();
}
//Define constants
public static final double CENTRE_X= 100.00;
public static final double CENTRE_Y = 37.50;
//placeGRect method
public void placeGRect() {
for (int count = 0; count < 4; count++) {
GRect box = new GRect (200, 75);
add(box);
switch (count) {
case 0:
box.setLocation(GraphicsHierarchy.CENTRE_X, 75);
break;
case 1:
box.setLocation((GraphicsHierarchy.CENTRE_X * 0.5), 250);
break;
case 2:
box.setLocation(GraphicsHierarchy.CENTRE_X, 250);
break;
case 3:
box.setLocation((GraphicsHierarchy.CENTRE_X * 1.5), 250);
break;
}
}
}
}
In my opinion, you can go even further by eliminating all computations and replace such stuff
GraphicsHierarchy.CENTRE_X * 1.5
with
150
Come on, have it easy on your Virtual Machine! Your class uses a whole load of static information, so there is no need for so much computation. But having a BOX_WIDTH and BOX_HEIGHT is completely useless as constants, as they are used only internally and only on one place. Calculating centre_x and centre_y out of the BOX_WIDTH and BOX_HEIGHT is also useless, as as they are final, you can easily do the computation yourself and reduce unnecessary creation of variables.
In addition, you don't use the centre_y value anywhere, so you should ditch it.
To further add some helpful advice, a decent IDE, like NetBeans, Eclipse, or IntellIJIDEA should have code completion and syntax highlighting and will help you immensely in becoming a better (or more knowledgable, which is even better) programmer.
Related
I'm not sure why but when I try to run this the only thing that shows is the last program I ran, I even added the serialVersionUID and it still wont show. Anyone have an i dea on why, maybe some setup problem on my eclipse or coomputer?
import java.awt.Graphics;
import javax.swing.JPanel;
public class Shapes extends JPanel {
private static final long serialVersionUID = 1L;
private int choice;
public Shapes(int userChoice) {
choice = userChoice;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; 1 < 10; i++) {
switch (choice) {
case 1:
g.drawRect(10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10);
case 2:
g.drawOval(10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10);
break;
}
}
}
}
First of all, you have no entry-point to your program. You can't just expect a program in Java, or basically any other compiled language to run without an entry point.
Inside your class, you need to have the following for the program to begin:
public static void main(String[] args) {
// Entry-point began. Put code in here.
}
Secondly, it is not a good practise (correct me if I'm wrong) to extend any of the JComponent derivatives. Without explaining again, a good reason can be found here:
Excerpt:
It makes it harder to change things later - if you've made a class public, swapping the superclass is going to break subclasses - it's a choice which, once you've made the code public, you're married to. So if you're not altering the real functionality to your superclass, you get much more freedom to change things later if you use, rather than extend the thing you need. Take, for example, subclassing JPanel - this is usually wrong; and if the subclass is public somewhere, you never get a chance to revisit that decision. If it's accessed as JComponent getThePanel() , you can still do it (hint: expose models for the components within as your API). This especially applies because your class is a Shape. So when Shape extends JPanel, every single shape will.
Object hierarchies don't scale (or making them scale later is much harder than planning ahead) - this is the classic "too many layers" problem. I'll go into this below, and how the AskTheOracle pattern can solve it (though it may offend OOP purists).
Especially since you are extending JPanel, and aren't even initialising a JFrame to begin with. Before starting out with Swing applications in Java, you should read the JavaDoc and Oracles examples beforehand...
JavaDoc: JFrame / JPanel
Example: How to make Frames.
So, revising on what I have said, a basic Swing class would look as follows:
import javax.swing.*;
public class Shapes {
public Shapes() {
JFrame frame = new JFrame();
JPanel window = new JPanel();
frame.setSize(600, 400); // Width: 600, Height: 400.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(window);
window.setLayout(new BorderLayout());
// Perform graphics drawing.
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
new Shapes();
}
}
OK, I'm in the process of making a simple java swing chess game. This question is more about OOP design then Java Swing.
I have the following:
I have a Panel class that implements JPanel.
I then have an abstract class Piece that extends from my Panel class
Then I have my classes for the different Pieces: Pawn, King, Bishop etc that extend from my Pieces class
In my main ChessGame Class:
I am using an array of Panel to store the layout of my board
So the array will store, Panel objects, for board places with no pieces on it.
And it will store, the subclasses such as Pawn, Queen, Bishop etc (board places with pieces)
So, the top left square (0,0) maps to myArray[0][0]
My problem is that, to check if the place is empty or has chess pieces in it I have to use:
if(panels[x][y] instanceof Piece){
((Piece)panels[x][y]).makeMove();
}
What I'm asking is this terrible design? I know I should try and stay away from instanceof.
What would be a better approach?
Thanks.
You shouldn't combine the Model code (Piece) with the view code (JPanels). If you ever want to change how the board is displayed you have to change how pieces are stored!
A better design might be to separate Piece from JPanels. Then you can use a single JPanel to display a matrix of Pieces : Pieces[8][8].
My problem is that, to check if the place is empty or has chess pieces in it I have to use:
If you use a matrix, you can just have a null cell or use the Null Object Pattern to have an "empty" piece.
EDIT
Each cell in the piece matrix is a square in the board so piece[0][0] would be the top corner of the board (A8).
To paint the board your paintComponent() method would have to iterate over this matrix and draw each cell appropriately. There are several ways to implement this:
You would need to do a similar instanceof check to draw each type of piece differently
Make a new intermediate "paint strategy" object using the strategy pattern. This may require a matrix of strategy objects instead of piece objects. You may still need to do instance of checks, but maybe only the once to create the strategy objects.
After considering your problem, and knowing the problem domain, I would actually suggest the following...
In your class Panel implement a function int hasMass() as follows...
public int hasMass() {
return 0;
}
In your class Piece override that function as follows...
public int hasMass() {
if (isWhite()) // white pieces are negative.
return -1;
return 1; // black pieces positive.
}
Now you can check if the square has a piece, whether another given piece could take it... (because they have opposite polarity)... e.g. mass + mass == 0 means a capture, != 0 means the panel was empty. And of course an absolute value of 2 (for mass) would mean the move was illegal.
OK, ill start by throwing away the option of setting null to indicate that place is empty (you can do it ofc but using the Empty class is just 'better' in a way).
So let's say you have array of Panels representing your game board:
Panel[][] board;
Now for ilustration, how your class hierarchy could look like:
abstract class Panel extends JPanel { ... }
class Empty extends Panel { ... }
abstract class Piece extends Panel { ... }
class Pawn extends Piece { ... }
...
My Panel class is my Empty class is it not?
Not sure if i understand you, but let's have a look on what extends means exactly: in the show nmodel every Piece is also a Panel or every Pawn is also a Piece, so every Pawn can do all the same things as Piece (for example, 4 is complex number as well as natural number or real number, so in a way, you could say that real numbers extend complex numbers, since every real number is also a complex number)
So now you can have some nice abstract getTexture() method declared in Panel implemenented in Empty class and in all Piece subclasses, and when drawing a Panel, you dont need to look if it is empty or not.
Instead of creating (I assume) almost identical classes for each piece (Rook, Pawn, Queen etc.), you could just keep the original Piece class, make it non abstract and add a PieceType field to it. PieceType is just an enum that tells what type of piece (if any) is placed there. Instead of using instanceof, now you can check using panels[i][j].getType() == PieceType.ROOK. At least that's what I'm doing in my implementation :)
I'm also using JLabel instead of JPanel for my 8x8 board.
Instead of splitting panel to 8x8 smaller panels, you must draw the board and the pieces on a canvas. Later the players will eventually be dragging to move pieces on board. Also you could look for Bitboard presentation in chess game, although this presentation is only required for chess engines which are able to "think" for fast calculations, it is still useful when you have to check if the move that player is trying to make is correct.
Posible Bitboard:
public class BitBoard
{
public static final int P = 0;
public static final int N = 2;
public static final int B = 4;
public static final int R = 6;
public static final int Q = 8;
public static final int K = 10;
public static final int p = 1;
public static final int n = 3;
public static final int b = 5;
public static final int r = 7;
public static final int q = 9;
public static final int k = 11;
// empty field
public static final int empty = 12;
// number of pieces , squares
public static final int nPieces = 12;
public static final int nSquares = 64;
public static final int whitePieces = 12;
public static final int blackPieces = 13;
public static final int nBoards = 14;
public static long squareBits[];
// static member initialization
static
{
squareBits = new long[64];
long square = 1;
square = square << 8 * 8 - 1;
for (int i = 0; i < 64; i++) {
squareBits[i] = square >>> i;
}
}
long bitBoards[];
public BitBoard() {
bitBoards = new long[nBoards];
}
public boolean initBoard()
{
// Put the pieces on the board
EmptyBoard();
addPiece(0, r);
addPiece(1, n);
addPiece(2, b);
addPiece(3, q);
addPiece(4, k);
addPiece(5, b);
addPiece(6, n);
addPiece(7, r);
for (int i = 8; i < 16; i++) {
addPiece(i, p);
}
for (int i = 48; i < 56; i++) {
addPiece(i, P);
}
addPiece(56, R);
addPiece(57, N);
addPiece(58, B);
addPiece(59, Q);
addPiece(60, K);
addPiece(61, B);
addPiece(62, N);
addPiece(63, R);
return true;
}
public boolean addPiece(int whichSquare, int whichPiece)
{
bitBoards[whichPiece] |= squareBits[whichSquare];
bitBoards[nPieces + (whichPiece % 2)] |= squareBits[whichSquare];
return true;
}
private boolean removePiece(int whichSquare, int whichPiece)
{
bitBoards[whichPiece] ^= squareBits[whichSquare];
bitBoards[nPieces + (whichPiece % 2)] ^= squareBits[whichSquare];
return true;
}
private boolean EmptyBoard()
{
for (int i = 0; i < nBoards; i++)
{
bitBoards[i] = 0;
}
return true;
}
}
I would keep a structure of the pieces separate from the rendered board.
For example, I would make the chess pieces pure models w/o knowledge of hit they're rendered.
Pieces (baseclass)
+- Pawn
+- Knight
+- King
+- Queen
+- ..etc
This will allow you to keep an array of Pieces only, where empty squares are null.
For simplicity sake, I'd just have a matrix of peices:
Peices[][] board = new Pieces[8][8];
(of course an initialization method to traverse your 'board' and populate the board w/ the initial positions)
I would then have a visible board constructed of JPanels; a class called "Chess" to manage game; and the actual rendering of the tile/panel in the move function. Imagine:
// what a move might look like when initializing your panels
piece = board [0][0];
Chess.move(piece, 0 ,0); //responsible for clearing the old panel and rendering the panel at target location.
When the user interacts w/ your game..they click your panels..which will give you the panel coordinates. You use the same coordinates w/ your 'board' to determine what the piece is..how it can move etc..
Something like that...
I would just represent the game board using objects...for simplicity. Easiest to understand..and besides..computers are plenty fast now.
I am programming a game, but I have ran into an error.
When the player collided with an object, player.hasCollided is set to true.
if(playerBounds.intersects(wolfBounds)){
player.hasCollided = true;
player.dead();
}
Now, when hasCollided is true, something from the LoseScreen class is printed out onto the screen:
if(player.hasCollided){
lose.start(g);
}
In player.dead(), the player's speed is set to 0.
public void dead(){
playerSpeed = 0;
coinBank += coinsCollected;
}
The problem is that in my InputHandler class I make it so that on the lose screen, when the choice is 1, and enter is pressed, restartGame() is called.
public void restartGame(){
obstacleWolf.getNewPosition();
obstacleHole.getNewPosition();
hasLost = false;
player.hasCollided = false;
player.playerSpeed = 5;
player.nextX = 1000;
player.coinsCollected = 0;
player.xElapsed = 0;
}
if(lose.choice == 1 && enter){
game.hasLost = false;
game.restartGame();
System.out.println(player.hasCollided + " " + player.playerSpeed);
}
Those variables ARE being set to what they are meant to be set to (for example playerSpeed becomes 5 from 0, and hasCollided is becoming false from true) but the effects are not taking place. So, like I showed before, lose.start(g); is only meant to be called when hasCollided is true, but even when it becomes false, it is still printed out on the screen.
Here is how the relevant variables/methods are being used:
public void move() {
x = x - player.playerSpeed;
}
(All moving objects share the same move method)
Parts of the game class:
public void tick(){
input.tick();
if(gameState){
player.tick();
player.move();
collision();
treeline.move();
obstacleHole.move();
obstacleWolf.move();
coin.move();
coin.tick();
}
I am not sure if I can make this question clearer. I can provide more code from different classes if needed.
The question can't be answered in its current form (see 2 comments above).
The reason for that is current code structure.
You need to refactor code, then you will find the problem.
Put all modification of player fields in methods of Player class.
Access fields only through methods. Making fields private is old good practice.
Then the only code you need to share would be this Player class.
In one thread environment, that's all.
I'm programming a simple game in java.
I've made a collision test with 30 FPS, where I had to get the size of the window.
Because I haven't had access to the GUI instance, I thought I'd make a shared instance, because this is pretty standard in Objective-C, where I come from.
class GUI extends JFrame {
private static GUI _sharedInstance;
public static GUI sharedInstance() {
if (_sharedInstance == null) {
_sharedInstance = new GUI();
}
return _sharedInstance;
}
}
But for some reason, it was really slow.
Then I replaced the shared instance with public static final instances for the size, and it works fast now, even with 60 FPS or higher.
Can anyone explain me why this happens?
EDIT
So instead of calling GUI.sharedInstance().getWidth(), I'm just calling GUI.windowSize.width.
I have used the public static final Dimension windowSize instead.
EDIT
Here's the collision detection.
So, instead of calling int width = GUI.kWindowWidth;,
I was calling int width = GUI.sharedInstance().getWidth(); before.
// Appears on other side
if (kAppearsOnOtherSide) {
int width = GUI.kWindowWidth;
int height = GUI.kWindowHeight;
// Slow
// int width = GUI.sharedInstance().getWidth();
// int width = GUI.sharedInstance().getHeight();
Point p = this.getSnakeHead().getLocation();
int headX = p.x;
int headY = p.y;
if (headX >= width) {
this.getSnakeHead().setLocation(new Point(headX - width, headY));
} else if (headX < 0) {
this.getSnakeHead().setLocation(new Point(headX + width, headY));
} else if (headY >= height) {
this.getSnakeHead().setLocation(new Point(headX, headY - height));
} else if (headY < 0) {
this.getSnakeHead().setLocation(new Point(headX, headY + height));
}
}
I know that this might not be the real answer to the question, but there could be a problem with a race condition.
I assume that you are trying to use the lazy/singleton pattern, because the construction of the GUI class is quite expensive and you need only one instance.
Now, what happens? If a thread runs into the if statement body, it creates a new GUI instance. Just before the next assignment, it gets paused by the scheduler.
Now another thread pops in, sees that _sharedInstance is still null and creates another GUI instance (and so on...).
Lets assume that there are only two threads.
The first thread runs to the end and the second one is continued, now you have two instances of the GUI class. Nobody says that the unassigned GUI instance gets destroyed or garbage collected.
That could explain tha 50 % performance loss compared to using finally and assigning the GUI instance directly to _sharedInstance.
See e.g. the Java examples at http://en.wikipedia.org/wiki/Singleton_pattern
Double checked locking, inner classes or an enum are the ways you can use.
I've been using Processing for around two years now, and I really like it. However, I feel like Flash is a bit more useful for coding games, as it's more universal and flexible. I'm starting to feel like I have no idea what I'm doing, and I really don't get any of the concepts like movie clips and the stage and so forth. In Processing, to make, say, a ball, I might make this:
Ball[] ballArray = new Ball[ 0 ]; //Array to store each ball in
void setup()
{
size( 400, 400 );
}
void draw()
{
background( 255 );
for( int i = 0; i < ballArray.length; i++ )
{
ballArray[ i ].display(); //Run each ball's display code every time step
}
}
class Ball
{
PVector location; //Vector to store this ball's location in
Ball( int x, int y )
{
location = new PVector( x, y );
ballArray = ( Ball[] ) append( ballArray, this ); //Add this ball to the array
}
void display()
{
fill( 0 );
ellipse( location.x, location.y ); //Display this ball at its location
}
}
void mousePressed()
{
new Ball( mouseX, mouseY ); //Create a new ball at the mouse location
}
And that would let me create as many instances as I like, anywhere I like.
I haven't the faintest clue how to make a comparable applet in Flash.
I've tried making a 'ball' class in a separate .as file, but it gives me an error about too many arguments. I also don't know how to draw a shape directly to the screen.
Can somebody whip up an equivalent of this in Flash so I have something to start from?
It'd also be fantastic if I could get some recommended reading for total flash noobs,
or developers moving from Java to Flash.
The following is a simple flash movie/app that creates a new instance of Ball and adds it to the stage when and where you click the mouse on the stage. Also upon each creation of a new instance of Ball, its appended to an array of Ball objects called _balls.
Main.as(document class):
package
{
import com.display.Ball;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite
{
private var _balls:Array;
public function Main()
{
init();
}// end function
private function init():void
{
_balls = new Array();
stage.addEventListener(MouseEvent.CLICK, onStageMouseClick);
}// end function
private function onStageMouseClick(e:MouseEvent):void
{
createBall(e.stageX, e.stageY);
}// end function
private function createBall(p_x:Number, p_y:Number):void
{
var ball:Ball = new Ball(p_x, p_y);
addChild(ball);
_balls.push(ball);
}// end function
}// end class
}// end package
Ball.as:
package com.display
{
import flash.display.Sprite;
public class Ball extends Sprite
{
private var _radius:Number = 50;
private var _x:Number;
private var _y:Number;
private var _color:uint = 0xFF0000; // red
public function Ball(p_x:Number, p_y:Number)
{
_x = p_x;
_y = p_y;
init();
}// end function
public function init():void
{
draw();
}// end function
public function draw():void
{
this.graphics.beginFill(_color);
this.graphics.drawCircle(_x, _y, _radius);
this.graphics.endFill();
}// end function
}// end class
}// end package
I recommend reading the "ActionScript 3.0 Bible by Roger Braunstein" book for flash(as well as flex) "noobs". Also, even if you are experienced with ActionScript 3, it serves as a good reference book.
Also once you start to get a good grip on ActionScript 3, you may want to consider entering the realm of design patterns. To simplfy design patterns into a simple sentence it would probably be that they're "tools for coping with constant change in software design and development". I recommend reading "O'Reilly, ActionScript 3.0 Design Patterns by William Sanders & Chandima Cumaranatunge".
Check Colin Mook's Lost Actionscript Week End video tutorial , this will give you a good overview of Actionscript and enough understanding to apply your Processing knowledge to Flash. Bear in mind that in Processing a lot of the methods are hidden from you and you may have to write a lot more code in order to adapt Processing concepts to AS3.
http://tv.adobe.com/show/colin-moocks-lost-actionscript-weekend/