Below is a program that still lack of code. I was trying to put like x+=10 but I
ID: 3627977 • Letter: B
Question
Below is a program that still lack of code. I was trying to put like x+=10 but I don't know what code or algorithm to add every movement of the snake, Left, Right, Down and Up.We have to use the redo and undo as stack...
One of the problem of my program is i don't know how to set border so that the snake will not go out from the frame...X,Y coordinate....I need to submit this program and I hope somebody could make this program works very well...
/***
* PROVIDE THE MISSING CODE in the keyPressed() method
* in order to move the 'snake' around the interface
* by pressing:
*
* --> cursor keys
* --> CTRL-Z to 'undo' last move
* --> CTRL-Y to 'redo' past/last move
*/
package prelims;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import javax.swing.border.*;
public class Snakes extends JPanel implements KeyListener {
final static long serialVersionUID = 1;
final private int WIDTH = 600;
final private int HEIGHT = 400;
LinkedList<Point> snake = new LinkedList<Point>();
Stack<Point> undo = new Stack<Point>();
Stack<Point> redo = new Stack<Point>();
int x = WIDTH/2;
int y = HEIGHT/2;
/***
* KeyListener method - keyPressed()
*
* Complete the missing code in this method
*/
public void keyPressed(KeyEvent ke) {
int code = ke.getKeyCode();
switch( code ) {
default: // exit the method, i.e. do NOT repaint
return;
case KeyEvent.VK_Z:
if (ke.isControlDown()){
undo.add(snake.pop());
}
repaint();
return; // exit the method, i.e. do NOT add new point(X,Y)
case KeyEvent.VK_Y:
if (ke.isControlDown()){
redo.add(snake.peek());
}// redo past/last move ...
break;
case KeyEvent.VK_UP:
y-=10;
// update x and/or y ...
break;
case KeyEvent.VK_DOWN:
y+=10;
// update x and/or y ...
break;
case KeyEvent.VK_LEFT:
x-=10;
// update x and/or y ...
break;
case KeyEvent.VK_RIGHT:
x+=10;
// update x and/or y ...
break;
}
// .. then add the new x,y coordinate to the list
snake.add( new Point(x,y) );
if(snake.size()==51){
snake.remove(0);
}
repaint();
}
/***
* just a constructor
*/
public Snakes() {
snake.add( new Point(x,y) );
this.setPreferredSize( new Dimension(600, 400) );
this.setBackground( Color.WHITE );
}
/***
* 'other' KeyListener methods
*/
public void keyTyped(KeyEvent ke) { /* NOT USED - DON'T REMOVE */ }
public void keyReleased(KeyEvent ke) { /* NOT USED - DON'T REMOVE */ }
/***
* paintComponent - overloaded JPanel method
*/
Path2D.Double path = new Path2D.Double();
public void paintComponent(Graphics g) {
super.paintComponent( g );
Graphics2D canvas = (Graphics2D)g;
Point p;
canvas.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
canvas.setStroke( new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND) );
path.reset();
// (re)copy the points in 'snake' to create a 'path'
p = snake.get(0);
path.moveTo( p.x, p.y );
for(int i=1; i<snake.size(); i++) {
p = snake.get(i);
path.lineTo( p.x, p.y );
}
// draw the path
canvas.setColor( Color.BLUE );
canvas.draw( path );
}
/***
* main() - program execution starts here!
*/
public static void main(String[] args) {
Snakes myProgram = new Snakes();
JFrame frame = new JFrame("Snakes!");
frame.addKeyListener( myProgram );
frame.setContentPane( myProgram );
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setResizable( false );
frame.setVisible( true );
}
}
Explanation / Answer
/*
Hi, I have modified your code and placed comments explaining the modifications. Since no behavior for hitting a border was given, I have left it as do nothing behavior. This has been tested and is in perfect working order. Feel free to send me a PM if you have more questions.
-B
UPDATE: see embelished solution at the VERY BOTTOM in commentted code
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import javax.swing.border.*;
public class Snakes extends JPanel implements KeyListener {
final static long serialVersionUID = 1;
final private int WIDTH = 600;
final private int HEIGHT = 400;
LinkedList snake = new LinkedList();
Stack undo = new Stack();
Stack redo = new Stack();
int x = WIDTH / 2;
int y = HEIGHT / 2;
public void keyPressed(KeyEvent ke) {
int code = ke.getKeyCode();
boolean isLegalMove = false; /*Sentienal variable to keep track if the move is legal*/
switch (code) {
default:
return;
case KeyEvent.VK_Z:
if (ke.isControlDown()) {
undo.add(snake.pop());
}
repaint();
return;
case KeyEvent.VK_Y:
if (ke.isControlDown()) {
redo.add(snake.peek());
}
break;
case KeyEvent.VK_UP:
y -= 10;
if (isValidPoint(x, y)) { /*Check if its a valid position on the frame*/
isLegalMove = true;
} else {
y += 10;
}/*if it is not a valid move the position of the head is readjusted*/
break;
case KeyEvent.VK_DOWN:
y += 10;
if (isValidPoint(x, y)) {
isLegalMove = true;
} else {
y -= 10;
}
break;
case KeyEvent.VK_LEFT:
x -= 10;
if (isValidPoint(x, y)) {
isLegalMove = true;
} else {
x += 10;
}
break;
case KeyEvent.VK_RIGHT:
x += 10;
if (isValidPoint(x, y)) {
isLegalMove = true;
} else {
x -= 10;
}
break;
}
/*Add the valid move to the snake's movement in the linked list*/
if (isLegalMove) {
snake.add(new Point(x, y));
}
if (snake.size() == 51) {
snake.remove(0);
}
repaint();
}
/*Function to check if a point is Valid*/
public boolean isValidPoint(int x, int y) {
System.out.println(x + ", " + y);
if ((x >= 0 && x < this.getSize().width)
&& ((y >= 0 && y < this.getSize().height))) {
return true;
}
return false;
}
public Snakes() {
snake.add(new Point(x, y));
this.setPreferredSize(new Dimension(600, 400));
this.setBackground(Color.WHITE);
}
public void keyTyped(KeyEvent ke) { /* NOT USED - DON'T REMOVE */ }
public void keyReleased(KeyEvent ke) { /* NOT USED - DON'T REMOVE */ }
Path2D.Double path = new Path2D.Double();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D canvas = (Graphics2D) g;
Point p;
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvas.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
path.reset();
p = snake.get(0);
path.moveTo(p.x, p.y);
for (int i = 1; i < snake.size(); i++) {
p = snake.get(i);
path.lineTo(p.x, p.y);
}
canvas.setColor(Color.BLUE);
canvas.draw(path);
}
public static void main(String[] args) {
Snakes myProgram = new Snakes();
JFrame frame = new JFrame("Snakes!");
frame.addKeyListener(myProgram);
frame.setContentPane(myProgram);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}
/*Begin of second sample solution
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.Timer; /**/
import java.util.*;
public class Snakes extends JPanel implements KeyListener {
private static JFrame frame; /**/
private static Snakes myProgram; /**/
Timer sysTimer = new javax.swing.Timer(500, new SysActionListener());/**/
String direction; /**/
int maxSnakeSize;
final static long serialVersionUID = 1;
final private int WIDTH = 600;
final private int HEIGHT = 400;
LinkedList<Point> snake = new LinkedList<Point>();
Stack<Point> undo = new Stack<Point>();
Stack<Point> redo = new Stack<Point>();
int x = WIDTH / 2;
int y = HEIGHT / 2;
public int getYpos(){return y;}
public int getXpos(){return x;}
public void setYpos(int n){y = n;}
public void setXpos(int n){x = n;}
public String getDIR(){return direction;}
public void keyPressed(KeyEvent ke) {
int code = ke.getKeyCode();
switch (code) {
default:
return;
case KeyEvent.VK_UP:
direction = "up";
break;
case KeyEvent.VK_DOWN:
direction = "down";
break;
case KeyEvent.VK_LEFT:
direction = "left";
break;
case KeyEvent.VK_RIGHT:
direction = "right";
break;
}
}
public boolean isValidPoint(int x, int y){
if( (x >= 0 && x < this.getSize().width) &&
((y >= 0 && y < this.getSize().height)) )
return true;
return false;
}
class SysActionListener implements ActionListener
{
private int X;
private int Y;
public SysActionListener() {
}
public void actionPerformed(ActionEvent e) {
frame.repaint();
if (myProgram.getDIR().equals("right")){myProgram.setXpos(myProgram.getXpos() + 10 ); }
if (myProgram.getDIR().equals("left")){myProgram.setXpos(myProgram.getXpos() - 10 ); }
if (myProgram.getDIR().equals("up")){myProgram.setYpos(myProgram.getYpos() - 10 ); }
if (myProgram.getDIR().equals("down")){myProgram.setYpos(myProgram.getYpos() + 10 ); }
if(isValidPoint(myProgram.getXpos(), myProgram.getYpos()))
snake.add(new Point(myProgram.getXpos(), myProgram.getYpos()));
else
{
JOptionPane.showMessageDialog(null, "Wall Hit! GAME OVER.", "ARRGGH!", JOptionPane.WARNING_MESSAGE);
sysTimer.stop();
}
if (snake.size() == maxSnakeSize) {
snake.remove(0);
}
}
}
public Snakes() {
snake.add(new Point(x, y));
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
this.setBackground(Color.WHITE);
sysTimer.start(); /**/
direction = "right";
maxSnakeSize = 51;
}
public void keyTyped(KeyEvent ke) {}
public void keyReleased(KeyEvent ke) {}
Path2D.Double path = new Path2D.Double();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D canvas = (Graphics2D) g;
Point p;
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvas.setStroke(new BasicStroke(5.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
path.reset();
//draw the snake
p = snake.get(0);
path.moveTo(p.x, p.y);
for (int i = 1; i < snake.size(); i++) {
p = snake.get(i);
path.lineTo(p.x, p.y);
}
//color the snake
canvas.setColor(Color.BLUE);
canvas.draw(path);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
myProgram = new Snakes();
frame = new JFrame("Snakes!");
frame.addKeyListener(myProgram);
frame.setContentPane(myProgram);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
});
}
}
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.