23 jun 2010

Juego con el teclado

Ahora en este programa lo que intente hacer fue un juego, este consiste en un círculo que debe ser introducido en un cuadrado, cada vez que el círculo este dentro del cuadrado se obtendrá un punto. No logre que hiciera lo que yo quería, pero espero lograr terminarlo bien en estos días.

Las teclas de dirección mueven el círculo dentro del panel.
Logre que el círculo cuando se encuentra el final de la ventana no desaparezca, este aparece de nuevo en el otro lado, dando una sensación de que se transporta de una orilla a la otra.

Los botones que se muestran en la parte inferior de la ventana hacen diferentes funciones:
El botón Reset, mueve el circulo a su posición inicial.
El botón Salir, cierra la ventana.
Los botones Color Café y Color Azul, cambian el color del panel donde se encuentran los objetos.

Aquí algunas imágenes del programa:




Aquí les dejo el código:

// Librerias usadas en el programa
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.*;

// Aqui comienza nuestra clase
public class Juego extends JPanel implements KeyListener,
                                  ActionListener {

 public void actionPerformed(ActionEvent e) {
  String cmd = e.getActionCommand();
  if (cmd.equals("RESET")) {
   System.out.println("Reset");
   this.reset();
      this.repaint();
   return;
  }
  if (cmd.equals("SALIR")) {
   System.out.println("Hasta pronto!");
   System.exit(1);
  }
  if (cmd.equals("COLOR1")) {
   System.out.println("Cambio de color");
   miPanel.setBackground(this.colorArena);
   return;
  }
  if (cmd.equals("COLOR2")) {
   System.out.println("Cambio de color");
   miPanel.setBackground(this.colorMar);
   return;
  }
    }

    private double x;
    private double y;
    private double ancho;
    private double altura;
    private static final double MOVER = 0.02;

    private JPanel miPanel;
    private Color colorMar, colorArena;

    private void dibujaObjeto(Graphics2D g, int ancho,
    int altura) {
  g.setColor(Color.ORANGE);
  g.fill(new Ellipse2D.Double(this.x*ancho, this.y*altura,
                   this.ancho*ancho, this.altura*altura));
  return;
    }

    public void paint(Graphics g) {
  super.paint(g);
  this.dibujaCuadro((Graphics2D)g, super.getWidth(),
                                   super.getHeight());
  this.dibujaObjeto((Graphics2D)g, super.getWidth(),
                                   super.getHeight());
  return;
    }

    // Dibujar un cuadro
 private double a;
 private double b;
 private double w;
    private double h;

    private void dibujaCuadro(Graphics2D r, int w, int h) {
  r.setColor(Color.BLACK);
  r.fill(new Rectangle2D.Double(this.a*w, this.b*h,
                                this.w*w, this.h*h));
  return;
    }

    private void medidas() {
  this.a = Math.random()*0.9;
  this.b = Math.random()*0.9;
  this.w = 0.1;
  this.h = 0.14;
  return;
 }
    // Termina intento

 private void reset() {
  this.x = 0.0;
  this.y = 0.0;
  this.ancho = 0.07;
  this.altura = 0.1;
  return;
    }

    public Juego(JPanel p){
  this.miPanel = p;
  this.colorMar = new Color(12, 90, 100);
  this.colorArena = new Color(100, 70, 10);
 }

    public Juego() {
  super();
  this.reset();
  this.medidas();
  System.out.println("Ahora mueve el objeto");
    }

 public void keyPressed(KeyEvent e) {
  int c = e.getKeyCode();
  switch (c) {
   case KeyEvent.VK_DOWN:
    this.y += Juego.MOVER;
    break;
   case KeyEvent.VK_UP:
    this.y -= Juego.MOVER;
    break;
   case KeyEvent.VK_LEFT:
    this.x -= Juego.MOVER;
    break;
   case KeyEvent.VK_RIGHT:
    this.x += Juego.MOVER;
    break;
   default:
    break;
  }

  if (this.x < -0.05) {
   this.x = 0.98;
  } else if (this.x > 0.98) {
   this.x = -0.05;
  }

  if (this.y < -0.08) {
   this.y = 0.98;
  } else if (this.y > 0.98) {
   this.y = -0.08;
  }

  if (this.x == this.a && this.y == this.b){
   System.out.println("Ganaste un punto!");
  }

  super.repaint();
  return;
    }

    public void keyReleased(KeyEvent e) {
  return;
    }

    public void keyTyped(KeyEvent e) {
  return;
    }

 // Metodo principal
    public static void main(String[] args) {

  System.out.println("Bienvenido al Juego");
  JFrame f = new JFrame();
  f.setSize(600, 500);
  f.setLocation(200, 80);
  f.setTitle("Ventana de Juego");
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  Juego t = new Juego();
  t.setBackground(Color.WHITE);
  Juego yo = new Juego(t);

  // Creamos paneles para agrupar elementos
  JPanel pArriba = new JPanel();
  JPanel pAbajo = new JPanel();
  JPanel pIzquierda = new JPanel();
  JPanel pDerecha = new JPanel();
  JPanel p = new JPanel();
  p.setFocusable(true);
  p.addKeyListener(t);

  // Administradores de acomodo a cada panel
  pAbajo.setLayout(new GridLayout(1, 2));
  pIzquierda.setLayout(new GridBagLayout());
  pDerecha.setLayout(new GridBagLayout());
  p.setLayout(new BorderLayout());

  // Asignar un color de fondo a cada panel
  pAbajo.setBackground(Color.GRAY);
  pIzquierda.setBackground(Color.CYAN);
  pDerecha.setBackground(Color.BLUE);
  p.setBackground(Color.GRAY);

  GridBagConstraints con = new GridBagConstraints();

  con.gridx = 1;
  con.gridy = 1;
  con.gridwidth = 2;
  con.gridheight = 3;
  JButton bReset = new JButton("Reset");
  bReset.addActionListener(t);
  bReset.addKeyListener(t);
  bReset.setActionCommand("RESET");
  pIzquierda.add(bReset, con);

  con.gridx = 1;
  con.gridy = 4;
  con.gridwidth = 2;
  con.gridheight = 3;
  JButton salir = new JButton("Salir");
  salir.addActionListener(t);
  salir.setActionCommand("SALIR");
  pIzquierda.add(salir, con);

  // Botones para cambio de color
  con.gridx = 1;
  con.gridy = 1;
  con.gridwidth = 2;
  con.gridheight = 3;
  JButton bColorOne = new JButton("Color Cafe");
  bColorOne.addActionListener(yo);
  bColorOne.addKeyListener(t);
  bColorOne.setActionCommand("COLOR1");
  pDerecha.add(bColorOne, con);

  con.gridx = 1;
  con.gridy = 4;
  con.gridwidth = 2;
  con.gridheight = 3;
  JButton bColorTwo = new JButton("Color Azul");
  bColorTwo.addActionListener(yo);
  bColorTwo.addKeyListener(t);
  bColorTwo.setActionCommand("COLOR2");
  pDerecha.add(bColorTwo, con);

  // Acomodar los paneles
  p.add(t);
  p.add(pAbajo, BorderLayout.SOUTH);
  pAbajo.add(pIzquierda);
  pAbajo.add(pDerecha);

  // Colocar el panel en la ventana
  f.setContentPane(p);
  f.setVisible(true);
  return;
 }
}

1 comentario: