miércoles, 9 de diciembre de 2009

Proyectos Elegidos

1. Proyecto 12: Juego de batallas 

2. Proyecto 8: Agenda Presidencial

3. Proyecto 5: Juego de ahorcados

lunes, 7 de diciembre de 2009

Proyecto final de programación para móviles

Hola aquí está mi proyecto final de programación para móviles.

La aplicación consiste en que el servidor le manda al cliente una cadena que contiene notas musicales, solamente las mayores y las sostenidas (do do# re re# mi fa fa# sol sol# la la# si). El cliente utilizando las teclas del celular (la tecla 1 siendo do y asi en adelante hasta la tecla#) debe de marcar las notas enviadas por el servidor, la pantalla del cliente cuenta con un pequeño diagrama de un teclado, en donde se marca la "nota" que se esta tocando, a su vez la nota tocada se muestra en una cadena, por último cabe mencionar que cuando el cliente toca las notas, estas suenan en el celular. Si las notas tocadas por el cliente son las mismas que pide el servidor se "gana" el "juego".

El código fuente se encuentra abajo.

Hugo Romero Bello 125896

Código Fuente Parte 1

package hello;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public abstract class SocketConnectionMidlet extends MIDlet implements CommandListener, Runnable, ItemStateListener {

  public Display display ;
  private Command exitCommand;
  public canvas canvas;

  public String participante;
  public String notasc;
  public String recordStoreId="Notas";

  public Form form;

  public TextField messageToSend;
  public StringItem messageReceived;

  public SendMessageTask sendMessageTask;


  public Command sendCommand;

  public InputStream inputStream;
  public OutputStream outputStream;


  public SocketConnection socketConnection;
  public MyRecordStore BD;

  Thread listeningTask;




  public SocketConnectionMidlet(String title) {
  canvas = new canvas();


  BD = new MyRecordStore(recordStoreId);
  BD.open();
  participante=title;
  form = new Form(title);
  messageReceived = new StringItem( null," " );
  form.append( messageReceived );
  messageToSend = new TextField( "Text to send:","",1024,TextField.ANY );
  form.append( messageToSend );
  exitCommand = new Command( "Exit",Command.EXIT,1 );
  sendCommand = new Command( "Send",Command.ITEM,1 );
  form.addCommand( sendCommand );
  form.addCommand( exitCommand );

  form.setCommandListener( this );
  }


  public void startApp() {


  display = Display.getDisplay( this );
  display.setCurrent( form );
  listeningTask = new Thread(this) ;
  listeningTask.start();

  }
  protected void pauseApp() {}

  protected void destroyApp(boolean unconditional) {}


  public void readMessages()
  {
  StringBuffer stringBuffer;
  StringBuffer otherStringBuffer;
  int characterRead;

  while( true )
  {
  stringBuffer = new StringBuffer();
  characterRead = -1;
  try
  {
  while( ((characterRead = inputStream.read()) != -1) &&
  (characterRead != '\n') )
  {
  stringBuffer.append( (char)characterRead );
  }//end while
  }//end try
  catch(Exception e)
  {
  System.out.println(e);
  }//end catch

  if( characterRead == -1 )
  {
   
  break;
  }//end if
  else
  {

  otherStringBuffer = new StringBuffer( messageReceived.getText()+
  "\n"+stringBuffer.toString() );
  messageReceived.setText( otherStringBuffer.toString() );

  String notass = stringBuffer.toString();


  if(participante.equals("Client"))
  {

  if(notass.equals("Felicidades, Acertaste"))
  {
  messageReceived.setText("Haz Ganado");

  }
  else if (notass.equals("Intenta de nuevo"))
  {
  messageReceived.setText("Intenta de nuevo");

  }
  else{

  messageReceived.setText("Toca las notas en 10 segundos" + notass);
  try {
  Thread.sleep(5000);
  } catch (Exception ex) {}

  int o=0;
  while ( o <>
  {
  try {
  Thread.sleep(1000);
  } catch (Exception ex) {}
  o++;
  }
  if (o<>
  display.setCurrent( canvas );
  else
  display.setCurrent( form );

  messageToSend.setString(BD.getRecord(BD.getNumberOfRecords()));


   
  }

  }


  else if(participante.equals("Server"))
  {  
  if(notass.equals(notasc))
  {  
  sendMessageTask.send( outputStream,"Felicidades, acertaste");
  }
  else{  
  sendMessageTask.send( outputStream,"Intenta de nuevo" );
  }
  }
  }
  }
  }

public abstract void run();


 public void setSocketConnectionOptions()
 {
  try
  {
  // defines socket connection options
  socketConnection.setSocketOption( socketConnection.DELAY,0 );
  socketConnection.setSocketOption( socketConnection.KEEPALIVE,0 );
  }
  catch(Exception any)
  {

  }
 }//end setSocketConnectionOptions




 public void getAndOpenIOStreams()
 {
  try
  {
  // get and open output and input streams
  inputStream = socketConnection.openInputStream();
  outputStream = socketConnection.openOutputStream();
  }
  catch(Exception any)
  {
  }

 }//end


 public void createsAndStartsSendMessageTask()
 {

  // creates and starts the send message thread
  sendMessageTask = new SendMessageTask();
  sendMessageTask.start();
 }//end createsAndStartsSendMessageTask


 public void commandAction( Command theCommand,Displayable any )
  {
  if( theCommand == Alert.DISMISS_COMMAND ||
  theCommand == exitCommand )
  {
  try
  {
  if( inputStream != null )
  {
  inputStream.close();
  }//end if

  if( outputStream != null )
  {
  outputStream.close();
  }//end if

  if( socketConnection != null )
  {
  socketConnection.close();
  }//end if

  }//end try
  catch( IOException e ) {}
  destroyApp( true );
  notifyDestroyed();
  }//end if


  if (theCommand == sendCommand )
  {
  if(participante.equals("Server"))
  notasc=messageToSend.getString();

  sendMessageTask.send( outputStream, messageToSend.getString() );

  }//end if

}//end commandAction

}


___________

package hello;

import javax.microedition.lcdui.*;
import javax.microedition.media.*;


public class canvas extends Canvas {

  String keyStatus;
  String theKeyPressed;
  String key;
  String nota;
  String notas;
  int vol, vel;
  private int pressedKey;
  private String[] displayStrings;
  private static final int[] kNoteX = {
  0, 11, 16, 29, 32, 48, 59, 64, 76, 80, 93, 96
  };
  private static final int[] kNoteWidth = {
  16, 8, 16, 8, 16, 16, 8, 16, 8, 16, 8, 16
  };
  private static final int[] kNoteHeight = {
  96, 64, 96, 64, 96, 96, 64, 96, 64, 96, 64, 96
  };
  private static final boolean[] kBlack = {
  false, true, false, true, false,
  false, true, false, true, false, true, false
  };
  private int mMiddleCX, mMiddleCY;
  private int mCurrentNote;

  private MyRecordStore DB;
  private RMSFilterStartsWith filter;
  private RMSOrder comparator;
  private String recordStoreId;

  public canvas() {
  int w = getWidth();
  int h = getHeight();
  int fullWidth = kNoteWidth[0] * 8;
  mMiddleCX = (w - fullWidth) / 2;
  mMiddleCY = (h - kNoteHeight[0]) / 2;
  mCurrentNote = 60;
  pressedKey = 0;
  displayStrings = new String[2];
  displayStrings[0] = "Presiona Select tras ingresar las notas... ";
  displayStrings[1] = "Nota: ";


  recordStoreId = "Notas";
  DB = new MyRecordStore(recordStoreId);
  DB.create();
  System.out.println( ">>> Record store: " + recordStoreId +
  " has been created." ); 
  vel=100;
  vol=100;
  }



  public void paint(Graphics g) {
  int w = getWidth();
  int h = getHeight();
  g.setColor(0xffffff);
  g.fillRect(0, 0, w, h);
  g.setColor(0x000000);
  for (int i = 60; i <= 71; i++) {
  drawNote(g, i);
  }
  drawSelection(g, mCurrentNote);

  if (pressedKey != 0) {  
  key = getKeyName(pressedKey);

  if (key.equals("1"))
  nota="do";
  else if (key.equals("2"))
  nota="do #";
  else if (key.equals("3"))
  nota="re";
  else if (key.equals("4"))
  nota="re #";
  else if (key.equals("5"))
  nota="mi";
  else if (key.equals("6"))
  nota="fa";
  else if (key.equals("7"))
  nota="fa #";
  else if (key.equals("8"))
  nota="sol";
  else if (key.equals("9"))
  nota="sol #";
  else if (key.equals("*"))
  nota="la";
  else if (key.equals("0"))
  nota="la #";
  else if (key.equals("#"))
  nota="si";
  else if (key.equals("Select"))
  DB.addRecord(notas);


  g.drawString(displayStrings[0] ,
  0, 0, Graphics.TOP | Graphics.LEFT);  
  g.drawString(displayStrings[1] +
  "'" + nota + "'",
  0, 20, Graphics.TOP | Graphics.LEFT);

  if (key.equals("1") ){
  mCurrentNote=60;
  notas = notas+nota;
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
   
  }
  if (key.equals("2")){
  mCurrentNote=61;
  notas = notas+nota;
  //repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("3")){
  mCurrentNote=62;
  notas = notas+nota;
  //repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("4")){
  mCurrentNote=63;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("5")){
  mCurrentNote=64;
  notas = notas+nota;
  //repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("6")){
  mCurrentNote=65;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("7")){
  mCurrentNote=66;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("8")){
  mCurrentNote=67;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("9")){
  mCurrentNote=68;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("*")){
  mCurrentNote=69;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("0")){
  mCurrentNote=70;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
  if (key.equals("#")){
  mCurrentNote=71;
  notas = notas+nota;
  // repaint();
  try { Manager.playTone(mCurrentNote, vel, vol); }
  catch (MediaException me) {}
  }
   


  } else {
  g.drawString("Presiona las teclas ... ", 0, 20, Graphics.TOP | Graphics.LEFT);
  }

  }

  private void drawNote(Graphics g, int note) {
  int n = note % 12;
  int octaveOffset = ((note - n) / 12 - 5) * 7 * kNoteWidth[0];
  int x = mMiddleCX + octaveOffset + kNoteX[n];
  int y = mMiddleCY;
  int w = kNoteWidth[n];
  int h = kNoteHeight[n];
  if (isBlack(n)) {
  g.fillRect(x, y, w, h);
  } else {
  g.drawRect(x, y, w, h);
  }
  }

  private void drawSelection(Graphics g, int note) {
  int n = note % 12;
  int octaveOffset = ((note - n) / 12 - 5) * 7 * kNoteWidth[0];
  int x = mMiddleCX + octaveOffset + kNoteX[n];
  int y = mMiddleCY;
  int w = kNoteWidth[n];
  int h = kNoteHeight[n];
  int sw = 6;
  int sx = x + (w - sw) / 2;
  int sy = y + h - 8;
  g.setColor(0xffffff);
  g.fillRect(sx, sy, sw, sw);
  g.setColor(0x000000);
  g.drawRect(sx, sy, sw, sw);
  g.drawLine(sx, sy, sx + sw, sy + sw);
  g.drawLine(sx, sy + sw, sx + sw, sy);
  }

  private boolean isBlack(int note) {
  return kBlack[note];
  }

  protected void keyPressed(int keyCode) {
  pressedKey = keyCode;
  keyStatus = "pressed";
  repaint();
  }

  protected void keyReleased(int keyCode)
  {
  keyStatus = "realease";
  }

}

_________

package hello;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

public class SocketConnectionServerMidlet extends SocketConnectionMidlet


{
  private ServerSocketConnection serverSocketConnection;
  private String url;


  // Constructor
  public SocketConnectionServerMidlet()
  {
  super("Server");
  url = "socket://:2500";
 }//end constructor


  protected void pauseApp() {}

  protected void destroyApp( boolean flag ) {}


  public void run()
  {


  try
  {
  messageReceived.setText( "Waiting for clients..." );
  serverSocketConnection =(ServerSocketConnection)Connector.open( url );

  while( true )
  {
  form.setTitle( "Server -> no, pos güeiting.." );
  messageReceived.setText( "waiting for connections..." );

  // Gets a SocketConnection object that represents a server side
  // socket connection.
  socketConnection = (SocketConnection)
  serverSocketConnection.acceptAndOpen();

  setSocketConnectionOptions();

  form.setTitle( "Server -> Connected !!!!" );
  messageReceived.setText( "Connection accepted " );

  getAndOpenIOStreams();

  // creates and starts the send message thread
  createsAndStartsSendMessageTask();

  form.addCommand( sendCommand );

  // then, read the messages !!
  readMessages();

  }//end while
  }//end try
  catch( IOException ie )
  {
  if( ie.getMessage().equals("ServerSocket Open") )
  {
  Alert a = new Alert( "server","port 2500 already occupied.",
  null,AlertType.ERROR );
  a.setTimeout( Alert.FOREVER );
  a.setCommandListener( this );
  display.setCurrent( a );
  }//end if
  }//end catch
  catch( Exception e ) {}
 }//end connectionToClient

}//end class controlConexion

__________

package hello;


import javax.microedition.io.*;
//import javax.microedition.lcdui.*;

public class SocketConnectionClientMidlet extends SocketConnectionMidlet

{
  public String url;


  // Constructor
  public SocketConnectionClientMidlet()
  {
  super("Client");
  url = "socket://localhost:2500";
  }//end constructor





  public void run()
  {

  try
  {
  socketConnection = (SocketConnection)Connector.open( url );

  setSocketConnectionOptions();

  form.setTitle( "Client" );
  messageReceived.setText( "Connection established." );

  // get and open inpust and output streams
  getAndOpenIOStreams();

  // creates and starts send message task thread
  createsAndStartsSendMessageTask();

  // then , to read!!!
  readMessages();

  }//end try
  catch( Exception e )
  {
  }//end catch
 }//end connectToServer





  protected void pauseApp() {}


  protected void destroyApp( boolean flag ) {}


}//end class SocketConnectionClientMidlet

_________

package hello;


import java.io.*;

 class SendMessageTask extends Thread
  {
  private String message;
  OutputStream outputStream;




  public synchronized void send( OutputStream theOutputStream,String aMessage )
  {
  outputStream = theOutputStream;
  message = aMessage;
  notify();
  }//end




  // the run method is synchronized
  public synchronized void run()
  {
  //waits.....for a message to be send
  while( true )
  {
  if( message == null )
  {
  try
  {

  wait();
  }//end try
  catch( Exception e ) {}
  }//end if

  else
  {
  try
  {
  //sends the message
  outputStream.write( message.getBytes() );
  // and a new line
  outputStream.write( "\r\n".getBytes() );
  }//end try
  catch( IOException e )
  {
  e.printStackTrace();
  }//end catch

  message = null;
  }//end if
  }//end while
  }//end run



  public synchronized void stop()
  {
  message = null;
  notify();
  }//end stop


  }//end class SendMessageTask