Hi, I made this thread for our groups assignment. We are suppose to get 3 program codes, at least 250 lines each, from anyone that created one. As soon as we retrieve them, we are supposed to evaluate them and find out what type of things they used and how they program it for ex abstract methods, interfaces. It's like a research paper just that we research on something we don't know about. If you supply your code could you please erase the comments you involved and include your name in your post because we are suppose to make a Work Cited. It doesn't have to be your full name a nick name is fine. Thanks.

You want people to give you fully functioning programs with our comments and names removed and not expect you to just turn them in as completed work with YOUR name on them?

If you don't get 3 better contributions, feel free to use this. You should be able to run it. I wrote it as a quick check for how CPU usage scaled with number of sprites. I removed the comments as requested, but feel free to ask questions.
J

ps: It was >250 before I removed the comments!

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import java.lang.reflect.Field;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Animation extends JPanel implements ActionListener, KeyListener {

   private static final long serialVersionUID = 1L;
   final Timer timer;
   public final static int TIMER_MSEC = 50;

   Animation(int width, int height) {
      setPreferredSize(new Dimension(width, height));
      setFocusable(true);
      addKeyListener(this);
      timer = new Timer(TIMER_MSEC, this);
      timer.start();
   }

   @Override
   public void actionPerformed(ActionEvent arg0) {
      ArrayList<Sprite> temp = new ArrayList<Sprite>(Sprite.sprites);
      for (Sprite s : temp)
         s.update();
      repaint();
   }

   @Override
   public void paintComponent(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      paintBackground(g2d);
      for (Sprite s : Sprite.sprites)
         s.draw(g2d);
   }

   void paintBackground(Graphics2D g2d) {
      g2d.setColor(Color.white);
      g2d.fillRect(0, 0, getWidth(), getHeight());
      g2d.setColor(Color.gray);
      g2d.drawString("type r,g, or b for new ball, p to pause", 10, 20);
   }

   @Override
   public void keyPressed(KeyEvent arg0) {
   }

   @Override
   public void keyReleased(KeyEvent arg0) {
   }

   @Override
   public void keyTyped(KeyEvent arg0) {
      // System.out.println("KeyTyped: " + arg0.getKeyChar());
      switch (arg0.getKeyChar()) {
      case 'p': { // toggle pause
         if (timer.isRunning()) timer.stop();
         else timer.start();
         break;
      }
      case 'r': {
         BouncingBall ball = new BouncingBall(this, 0, 100, 10, 0);
         ball.setColor(Color.red);
         ball.setPhysics(2, .02f);
         break;
      }
      case 'g': {
         BouncingBall ball = new BouncingBall(this, 0, 100, 10, 0);
         ball.setColor(Color.green);
         ball.setPhysics(2, .02f);
         break;
      }
      case 'b': { 
         BouncingBall ball = new BouncingBall(this, 0, 100, 10, 0);
         ball.setColor(Color.blue);
         ball.setPhysics(2, .02f);
         break;
      }
      }
   }

   public static Color getColorByName(String colorName) {
      try {
         Field f = Color.class.getField(colorName.toUpperCase());
         return (Color) f.get(null);
      } catch (Exception e) {
         e.printStackTrace(); 
         return null; 
      }
   }

   public static void main(String[] args) {

      System.out.println(getColorByName("gray"));

      Animation animation = new Animation(600, 400);
      final JFrame frame = new JFrame("Animation");
      frame.add(animation);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

}

abstract class Sprite {

   abstract public void draw(Graphics2D g2d); 

   abstract public float getWidth(); 

   abstract public float getHeight(); 

   public static final ArrayList<Sprite> sprites = new ArrayList<Sprite>();

   float x, y, dx, dy; 
   float g = 0; )
   float drag = 0; 
   final JPanel canvas;

   public Sprite(JPanel canvas, float x, float y, float dx, float dy) {
      this.canvas = canvas;
      this.x = x;
      this.y = y;
      this.dx = dx;
      this.dy = dy;
      sprites.add(this);
   }

   public void setPhysics(int g, float drag) {
      this.g = g;
      this.drag = drag;
   }

   public void update() { 
      x += dx;
      y += dy; 
      dy += g; 
      dx = dx * (1 - drag); 
      dy = dy * (1 - drag);
   }

   public void dispose() {
      sprites.remove(this);
   }
}

class BouncingBall extends Sprite {

   Color ballColor = Color.black;
   int diameter = 32;

   public BouncingBall(JPanel canvas, float x, float y, float dx, float dy) {
      super(canvas, x, y, dx, dy);
   }

   public void setColor(Color c) {
      ballColor = c;
   }

   //@Override
   public void update() {
      super.update();
      if (y > canvas.getHeight() - getHeight()) { 
         y = canvas.getHeight() - getHeight(); 
         dy = -dy + 2 * g; 
      }
   }

   @Override
   public void draw(Graphics2D g2d) {
      g2d.setColor(ballColor);
      g2d.fillOval((int) x, (int) y, diameter, diameter);
   }

   @Override
   public float getWidth() {
      return diameter;
   }

   @Override
   public float getHeight() {
      return diameter;
   }

}

Edited 5 Years Ago by JamesCherrill: found more comments to remove

Hi, I made this thread for our groups assignment. We are suppose to get 3 program codes, at least 250 lines each, from anyone that created one. As soon as we retrieve them, we are supposed to evaluate them and find out what type of things they used and how they program it for ex abstract methods, interfaces. It's like a research paper just that we research on something we don't know about. If you supply your code could you please erase the comments you involved and include your name in your post because we are suppose to make a Work Cited. It doesn't have to be your full name a nick name is fine. Thanks.

Your request does force me to ask simple question. Why didn't you check any open source project on sourceforge.net, github or similar projects repository?

Comments
Insightful answer to a student's lazy question.

A number of posts to this forum contain code samples that are, unfortunately, over 250 lines. :(

For something small that is used in high performance production applications, I'd suggest "WAX", a Java "Writing API for XML."

https://code.google.com/p/waxy/source/browse/

Click on directories to navigate: trunk, trunk, java, src, com, ociweb, xml

Mark Volkmann wrote it. I wrote most of the JUnit tests, and refactored it heavily, giving it its current structure. It has several classes and makes good use of interfaces. Not much for inheritance.

Home page for WAX is
http://java.ociweb.com/mark/programming/WAX.html

Here's another reasonably short example:
http://anarchycreek.com/doubledawgdare-series/

Michael Hill started with some open source code that was really really nasty, and refactored it to make it more maintainable. I contributed JUnit tests. And you can see from my comments that I did several refactorings that took off in different directions.

To get his final source code, go to
http://anarchycreek.com/2010/03/30/doubledawgdare-7-one-spike-no-buffy/
and download the "Code After Step 7 (263)"

For some reason, I always have to change the last line in this method of the ReferenceMap class, to make it work:

Set<K> dereferenceKeySet(Set keyReferences) {
    return keyReferenceType == STRONG
        ? keyReferences
        : new TreeSet<K>(dereferenceCollection(keyReferenceType, keyReferences, new HashSet()));
  }

Well, it is just a few thousand lines. Focus on the 'com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder' class. Everything else is there only to support compiling and running tests on this class.

I have in a couple of comments in some areas, but they are generic. you can delete them if you wish. I have already released my code on thetechgame.com. Anyways here is the main part of the code the frame portion is separate.

package snakeColored;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class SnakeG extends JPanel implements KeyListener, Runnable{

	private Vector<Point> snake = new Vector<Point> (5,10);
	private Point target;
	private Rectangle targetRect;
	private Rectangle frameRect = new Rectangle (0,0,490,470);
	private Vector<Color> snakeColor = new Vector<Color> (5,10);
	private Color targetColor;
	private Vector<Rectangle> snakeRectangle = new Vector<Rectangle> (5,10);
	
	public void startGraphics (){
		
		this.addKeyListener(this);
		Thread thread = new Thread (this);
		
		repaint();
		grabFocus();
		snake.add (new Point (250,250));
		genTarget();
		snakeRectangle.add(new Rectangle (250,250,10,10));
		snakeColor.add(Color.black);
		runThread = true;
		thread.start();
	}
	
	private void addBall() {
		// TODO Auto-generated method stub
		if (previous.equals("right")){
		snake.add (new Point (snake.lastElement().x - 10, snake.lastElement().y));
		}
		if (previous.equals("left")){
			snake.add (new Point (snake.lastElement().x + 10, snake.lastElement().y));
		}
		if (previous.equals("up")){
			snake.add (new Point (snake.lastElement().x, snake.lastElement().y + 10));
		}
		if (previous.equals("down")){
			snake.add (new Point (snake.lastElement().x, snake.lastElement().y - 10));
		}
		snakeRectangle.add(new Rectangle ((int)snake.lastElement().x, (int) snake.lastElement().y, 10,10));
		snakeColor.add(targetColor);
		
		
		
	}

	
	
	public void paintComponent (Graphics g){
		//TODO GRAPHICS AREA
		super.paintComponent (g);
		
		
		for (Point x : snake){
			g.setColor(snakeColor.elementAt(snake.indexOf(x)));
			g.fillOval((int)x.getX(),(int)x.getY(),10, 10);
			
		}
		g.setColor (Color.black);
		if (runThread == false){
			System.out.println ("Lost message entered");
			g.setFont (new Font ("Arail", 30,30));
			g.drawString("You Lose!", 200, 220);
			g.setFont (new Font ("Arial", 10,10));
			g.drawString("Press N for a new Game", 210,230);
			g.setFont(new Font ("Arial", 17,17));
			g.drawString("Your Final Snake Size Was: " + snake.size(), 160, 250);
		}
		else {
			g.setFont(new Font ("Arial", 15,15));
			g.drawString("Snake size: " + snake.size(), 210, 220);
		}
		g.setColor(targetColor);
		g.fillOval((int)(target.getX()), (int)(target.getY()), 10,10);
	}

	
	
	private String previous;
	private boolean wasPressed = false;
	private boolean pressed = false;
	private boolean up,down,left,right;
	
	@Override
	public void keyPressed(KeyEvent e) {
		System.out.println ("KeyListener");
		int key = e.getKeyCode();
		
		up = false;
		down = false;
		left = false;
		right = false;
		System.out.println (pressed);
		if (key == KeyEvent.VK_UP && runThread == true){
			up = true;
			previous = "up";
		}
		else if (key == KeyEvent.VK_DOWN && runThread == true){
			down = true;
			previous = "down";
		}
		else if (key == KeyEvent.VK_LEFT && runThread == true){
			left = true;
			previous = "left";
		}
		else if (key == KeyEvent.VK_RIGHT  && runThread == true){
			right = true;
			previous = "right";
		}
		else if (key == KeyEvent.VK_N && runThread == false){
			resetGame();
		}
		else {}
		if (previous == null){
			runThread = true;
		}
		
	}

	private void resetGame() {
		// TODO Auto-generated method stub
		snake.removeAllElements();
		snakeRectangle.removeAllElements();
		target = null;
		targetRect = null;
		wasPressed = false;
		startGraphics();
	}

	@Override
	public void keyReleased(KeyEvent e) {
		wasPressed = true;
	}

	@Override
	public void keyTyped(KeyEvent e){}

	
	
	private boolean runThread = true;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println ("Started Thread");
		while (runThread){
			System.out.println ("Up: " + up + "\tDown: " + down + "\tLeft: " + left + "\tRight: " + right);
			
			//moving the snake
			if (up == true){
				System.out.println ("entered if");
				for (int i = snake.size() - 1; i > -1; i--){
					
					if (i == 0){
						snake.firstElement().y -= 10;
						
					}
					else {
						snake.elementAt(i).y = snake.elementAt(i - 1).y;
					}
				}

			}
			else if (down == true){
				for (int i = snake.size() - 1; i > -1; i--){
					
					if (i == 0){
						snake.firstElement().y += 10;
						
					}
					else {
						snake.elementAt(i).y = snake.elementAt(i - 1).y;
					}
				}

			}
			else if (left == true){
				for (int i = snake.size() - 1; i > -1; i--){
					
					if (i == 0){
						snake.firstElement().x -= 10;
						
					}
					else {
						snake.elementAt(i).x = snake.elementAt(i - 1).x;
					}
				}

			}
			else if (right == true){
				for (int i = snake.size() - 1; i > -1; i--){
					
					if (i == 0){
						snake.firstElement().x += 10;
						
					}
					else {
						snake.elementAt(i).x = snake.elementAt(i - 1).x;
					}
					
				}

			}
			System.out.println ("At start of turning");
			//Turning the snake
			if (wasPressed == true){
				if (previous.equals ("up")){
					for (int i = snake.size() - 1; i > 0; i--){
						
						snake.elementAt(i).x = snake.elementAt(i - 1).x;
					}
				}
				else if (previous.equals("down")){
					for (int i = snake.size() - 1; i > 0; i--){
						
						snake.elementAt(i).x = snake.elementAt(i - 1).x;
					}
				}
				else if (previous.equals("left")){
					for (int i = snake.size() - 1; i > 0; i--){
						
						snake.elementAt(i).y = snake.elementAt(i - 1).y;
					}
				}
				else if (previous.equals("right")){
					for (int i = snake.size() - 1; i > 0; i--){
						
						snake.elementAt(i).y = snake.elementAt(i - 1).y;
					}
				}
				else {}
			}
			updateRect();
			collisionDetect();
			
			
			
			
			repaint();
			//System.out.println ("before sleep. runThread: " + runThread);
			try {
				//System.out.println ("before sleep. runThread: " + runThread);
				Thread.sleep(100);
				//System.out.println ("After sleep. runThread: " + runThread);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//System.out.println ("After sleep. runThread: " + runThread);
			
		}
	}

	private void updateRect() {
		// TODO Auto-generated method stub
		for (int i = 0; i < snake.size(); i++){
			snakeRectangle.get(i).setLocation(snake.elementAt(i));
		}
	}

	private void collisionDetect() {
		// TODO Auto-generated method stub
		for (int i = 0; i < snake.size(); i++){

			//System.out.println("Z: " + z + " I " + i);
			if (i == 0){
				System.out.println("z = i accessed");
			}
			else {
				if (snakeRectangle.firstElement().contains((snakeRectangle.elementAt(i).getX()), (snakeRectangle.elementAt(i).getY()))){
					System.out.println("2 elements are the same");
					lost();
				}
			}

		}
		if (!frameRect.contains(snake.firstElement())){
			lost();
		}
		
		if (snakeRectangle.firstElement().contains(target)){
			addBall();
			genTarget();
		}
		
		
	}
	
	private void lost() {
		// TODO Auto-generated method stub
		runThread = false;
		repaint();
	}

	private void genTarget (){
		target = new Point ((int) (Math.random () * 48)* 10,(int) (Math.random () * 47) * 10);
		System.out.println (target);
		targetRect = new Rectangle (target, new Dimension (10,10));
		int colorGen = (int) (Math.random() * 10);
		
		if (colorGen == 0){
			targetColor = Color.red;
		}
		else if (colorGen == 1){
			targetColor = Color.blue;
		}
		else if (colorGen == 2){
			targetColor = Color.green;
		}
		else if (colorGen == 3){
			targetColor = Color.yellow;
		}
		else if (colorGen == 4){
			targetColor = Color.gray;
		}
		else if (colorGen == 5){
			targetColor = Color.cyan;
		}
		else if (colorGen == 6){
			targetColor = Color.orange;
		}
		else if (colorGen == 7){
			targetColor = Color.magenta;
		}
		else if (colorGen == 8){
			targetColor = Color.pink;
		}
		else if (colorGen == 9){
			targetColor = Color.white;
		}
		repaint();
	}
	
}

The frame

package snakeColored;

import javax.swing.JFrame;


public class snake {

	public snake (){
		JFrame frame = new JFrame ("Snake - v3.0");
		frame.setSize (500,500);
		frame.setResizable (false);
		SnakeG sg = new SnakeG();
		frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		frame.add (sg);
		
		frame.setVisible (true);
		sg.startGraphics();
	}
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		snake s = new snake ();
	}

}

If he was going to copy this code would be Academic dishonesty, and he could also get expelled. Since I released my code before it is technically open source.

I am kind of confused. The OP said they had to be over 250 lines, then JeffGrigg said they are over 350 lines, so they can't use them. Anyways. once you remove all of the blank lines in my first code, all of the comments and the @Overrides the code is exactly 250 lines.

Edited 5 Years Ago by sirlink99: n/a

This article has been dead for over six months. Start a new discussion instead.