Hola, nececito ayoda para una tarea en la que tengo que construir un juego de carrera de caballos que permita interactuar entre computadoras empleando el uso de sockets y threads.
El juego conciste en que cada participante elige un caballo el cual debe correr hasta la meta, debo tener 3 caballos cada uno con una formula de desplasamiento diferente pero balanceadas entre si, es decir ningun caballo debe tener ventaja.
Dos jugadores no pueden elegir un mismo caballo por lo que el maximo de jugadores sera 3, en caso de tratar de elegir el mismo le debera salir un mensaje indicando que ese caballo ya esta seleccionado y que debe elegir otro.
El jugador debe poder apostar a su caballo un valor en dolares que en caso de ganar se duplicara.
El juego debe iniciar cuando todos los jugadores dan click en iniciar y al final se debe mostrar el valor ganado por cada jugador
tengo que tener una clase cliente con la interfaz para seleccionar al caballo y para poder ver la carrera y una clase servidor que sera a la que se conecten los 3 clientes para poder realizar la carrera
necesito ayuda o sugerencias porque no tengo ni idea de como voy a hacer esto antes del lunes
Suerte
De socket no tengo ni idea de pero de thread un poquito.
Tienes que crearte un objeto que implemente Runnable con el metodo run() que será el que se ejecute al comenzar el hilo.
Luego desde el main te creas tantos objetos hilo como quieras y tantos objetos tipo Thread como hilos te hayas creado
Thread nuevo = new Thread(objeto Runnable);
Luego haces un nuevo.run() y a volar xD
Yo tambien entiendo la parte de threads pero no puedo conectar el cliente con el servidor y mostrar lo mismo a todos los clientes
tengo esta clase para la carrera en si pero no entiendo como hacer un servidor y los clientes alguien me puede ayudar
package picture;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.beans.*;
//Pintar la línea de meta
public class Applet1 extends Applet {
boolean isStandalone = false;
private int NUM_CABALLOS=6;
private Caballo arrcaballo[] = new Caballo[NUM_CABALLOS]; //Arreglo de caballos
private boolean primeravez=true; // Indica si se carga por primera vez el applet
private AudioClip sndaplauso;
private Label [] arrtiempo = new Label[NUM_CABALLOS];
private Label [] arrganados = new Label[NUM_CABALLOS];
private Label [] arrtotcarr = new Label[NUM_CABALLOS];
Color [] colores = {Color.orange,Color.blue,Color.red,Color.pink,Color.green,
Color.black};
Button button1 = new Button();
Label label1 = new Label();
Choice choice1 = new Choice();
Choice choice2 = new Choice();
Label label2 = new Label();
Label labelt1 = new Label();
Label labelt2 = new Label();
Label labelt3 = new Label();
Label labelt4 = new Label();
Label labelt5 = new Label();
Label labelt6 = new Label();
Label labelg1 = new Label();
Label labelg2 = new Label();
Label labelg3 = new Label();
Label labelg4 = new Label();
Label labelg5 = new Label();
Label labelg6 = new Label();
Label labeltc1 = new Label();
Label labeltc2 = new Label();
Label labeltc3 = new Label();
Label labeltc4 = new Label();
Label labeltc5 = new Label();
Label labeltc6 = new Label();
Label label3 = new Label();
Label label4 = new Label();
Label label5 = new Label();
/**Get a parameter value*/
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
}
/**Construct the applet*/
public Applet1() {
}
/**Initialize the applet*/
public void init() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
// Llenar combobox de velocidad
choice1.addItem("Normal");
choice1.addItem("Rápido");
choice1.addItem("Más rápido");
// Llenar combobox del número de caballos: 2 a 6
for(int i=6; i>1; i--)
choice2.addItem(Integer.toString(i));
sndaplauso = getAudioClip(getCodeBase(), "Applause.au");
arrtiempo[0]= labelt1; arrtiempo[1]= labelt2; arrtiempo[2]= labelt3;
arrtiempo[3]= labelt4; arrtiempo[4]= labelt5; arrtiempo[5]= labelt6;
arrganados[0]= labelg1; arrganados[1]= labelg2; arrganados[2]= labelg3;
arrganados[3]= labelg4; arrganados[4]= labelg5; arrganados[5]= labelg6;
arrtotcarr[0]= labeltc1; arrtotcarr[1]= labeltc2; arrtotcarr[2]= labeltc3;
arrtotcarr[3]= labeltc4; arrtotcarr[4]= labeltc5; arrtotcarr[5]= labeltc6;
}
/**Component initialization*/
private void jbInit() throws Exception {
Image [] arrimgcaballo = new Image[NUM_CABALLOS];
// Arreglo de imagenes del lugar en que llegan los caballos a la meta
Caballo.imglugar = cargaarregloimg("lugar",".jpg",NUM_CABALLOS);
Caballo.terminan = 0; // Cuántos caballos han llegado a la meta
// Arreglo de imagenes de los caballos
arrimgcaballo = cargaarregloimg("image",".gif",NUM_CABALLOS);
// Arreglo de objetos Caballo: Caballo(Applet,x,y,Imagen)
for(int i=0; i arrcaballo = new Caballo(this,5,(i*45)+10,arrimgcaballo);
primeravez = true;
this.setLayout(null);
button1.setLabel("Empieza");
button1.setBounds(new Rectangle(328, 279, 83, 22));
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
button1_actionPerformed(e);
}
});
this.setBackground(Color.white);
label1.setText("Velocidad");
label1.setBounds(new Rectangle(3, 282, 59, 17));
choice1.setBounds(new Rectangle(65, 279, 91, 22));
choice1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
choice1_itemStateChanged(e);
}
});
choice2.setBounds(new Rectangle(266, 281, 41, 20));
choice2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
choice2_itemStateChanged(e);
}
});
label2.setText("Núm. de Caballos");
label2.setBounds(new Rectangle(163, 281, 101, 19));
labelt1.setText("0:000");
labelt1.setBounds(new Rectangle(62, 368, 43, 20));
labelt2.setBounds(new Rectangle(110, 368, 46, 20));
labelt2.setText("0:000");
labelt3.setBounds(new Rectangle(163, 368, 41, 20));
labelt3.setText("0:000");
labelt4.setBounds(new Rectangle(210, 368, 46, 20));
labelt4.setText("0:000");
labelt5.setBounds(new Rectangle(263, 368, 46, 20));
labelt5.setText("0:000");
labelt6.setBounds(new Rectangle(323, 368, 46, 20));
labelt6.setText("0:000");
labelg1.setText("0");
labelg1.setBounds(new Rectangle(64, 344, 31, 18));
labelg2.setBounds(new Rectangle(113, 346, 31, 18));
labelg2.setText("0");
labelg3.setBounds(new Rectangle(164, 344, 31, 18));
labelg3.setText("0");
labelg4.setBounds(new Rectangle(212, 346, 31, 18));
labelg4.setText("0");
labelg5.setBounds(new Rectangle(267, 345, 31, 18));
labelg5.setText("0");
labelg6.setBounds(new Rectangle(323, 345, 31, 18));
labelg6.setText("0");
labeltc1.setText("0");
labeltc1.setBounds(new Rectangle(64, 321, 25, 19));
labeltc2.setBounds(new Rectangle(113, 321, 25, 19));
labeltc2.setText("0");
labeltc3.setBounds(new Rectangle(163, 321, 25, 19));
labeltc3.setText("0");
labeltc4.setBounds(new Rectangle(212, 321, 25, 19));
labeltc4.setText("0");
labeltc5.setBounds(new Rectangle(268, 321, 25, 19));
labeltc5.setText("0");
labeltc6.setBounds(new Rectangle(324, 321, 25, 19));
labeltc6.setText("0");
label3.setFont(new java.awt.Font("Dialog", 1, 12));
label3.setForeground(Color.blue);
label3.setText("Carreras");
label3.setBounds(new Rectangle(2, 321, 57, 17));
label4.setBounds(new Rectangle(2, 343, 54, 17));
label4.setText("Ganados");
label4.setForeground(Color.blue);
label4.setFont(new java.awt.Font("Dialog", 1, 12));
label5.setBounds(new Rectangle(1, 366, 50, 17));
label5.setText("Tiempo");
label5.setForeground(Color.red);
label5.setFont(new java.awt.Font("Dialog", 1, 12));
this.add(button1, null);
this.add(label1, null);
this.add(choice1, null);
this.add(label2, null);
this.add(choice2, null);
this.add(labelt6, null);
this.add(labeltc6, null);
this.add(labeltc1, null);
this.add(labeltc4, null);
this.add(labeltc5, null);
this.add(labelg6, null);
this.add(labelg1, null);
this.add(labelg4, null);
this.add(labelg5, null);
this.add(labelt1, null);
this.add(labelt2, null);
this.add(labelt4, null);
this.add(labelt5, null);
this.add(labeltc2, null);
this.add(labelg2, null);
this.add(labeltc3, null);
this.add(labelg3, null);
this.add(labelt3, null);
this.add(label3, null);
this.add(label4, null);
this.add(label5, null);
}
/**Get Applet information*/
public String getAppletInfo() {
return "Applet Information";
}
/**Get parameter info*/
public String[][] getParameterInfo() {
return null;
}
///////////////////////////////////////////////////////////////
////////////////// Actualizar la pantalla /////////////////////
public void paint(Graphics g){
if (Caballo.terminan == NUM_CABALLOS){ // Se terminó la carrera
button1.setEnabled(true);
choice2.setEnabled(true);
}
else if (Caballo.terminan == 1) // Llegó el primero
sndaplauso.play();
if (primeravez==true){// Pintar los cabalos sólo cuando se carga por primera vez el applet
for(int i=0; i g.clipRect(10,(i*45)+10,arrcaballo.width/4,arrcaballo.height);
g.drawImage(arrcaballo.miimage,10,(i*45)+10,this);
g.setClip(null);
}//for
}//if primera vez
if (!button1.isEnabled()) // Estoy en una carrera
{
for(int i=0; i//Pintar los caballos
if (arrcaballo.termine==false){
g.clipRect(arrcaballo.getX(),(i*45)+10,arrcaballo.width/4,arrcaballo.height);
g.drawImage(arrcaballo.miimage,//Pinta el frame siguiente
arrcaballo.getX()-arrcaballo.getFrame()*arrcaballo.width/4,
(i*45)+10,this);
g.setClip(null);
// long tiempo = System.currentTimeMillis()-arrcaballo.tiempo;
long tiempo = arrcaballo.horafin - arrcaballo.horaini;
long seg = tiempo/1000;
long mili = tiempo % 1000;
arrtiempo.setText(seg+":"+mili);
}
}//if ya empecé la carrera
else{
for(int i=0; i//Pintar los caballos
arrganados.setText(arrcaballo.ganados+" ");
arrtotcarr.setText(arrcaballo.totCarreras +" ");
}
}
g.setColor(Color.blue);
g.drawLine(550,0,550,330);
for(int i=0; i//Pintar los colores
g.setColor(colores);
g.fillRect(0,(i*45)+12,9,20);
g.fillRect(70+(i*50),304,20,9);
}//for pinta colores
}
//////////////////////////////////////////////////////////////////
/// Reescribir update para pintar sólo el área afectada del applet
public void update(Graphics g){
paint(g);
}
//////////////////// PRINCIPAL btnClick /////////////////////
//////////////////// Iniciar la carrera /////////////////////
void button1_actionPerformed(ActionEvent e) {
Thread arr_thread[] = new Thread[NUM_CABALLOS];
button1.setEnabled(false);
choice2.setEnabled(false);
Caballo.terminan = 0; // Inicializar contador de caballos que han terminado
// Ajustar el tiempo de retardo de cambio del frame
Caballo.RETARDO = dameRetardo(choice1.getSelectedIndex());
for(int i=0; i arrcaballo.setX(0); // Regresar al punto de inicio de la carrera
arrcaballo.termine = false; //Bandera que indica si ya llegó a la meta
arrcaballo.horaini = System.currentTimeMillis();
}
//Limpiar área del applet
getGraphics().clearRect(10,0,this.getSize().width,getSize().height);
primeravez = false;
for(int i=0; i arr_thread = new Thread(arrcaballo);
for(int i=0; i arr_thread.start();
}
///////////////////////////////////////////////////////////////////////////
/////// Carga imagenes seriadas y las coloca en un arreglo //////////////
private Image [] cargaarregloimg(String nomserie,String extension,int total){
Image [] imglugar = new Image[total];
MediaTracker tracker=new MediaTracker(this);
for (int i=0; i imglugar = this.getImage(getCodeBase(),nomserie+Integer.toString(i+1)+extension);
tracker.addImage(imglugar,i);
}
// Esperar hasta que se cargen la imagenes
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
return imglugar;
}
//////////////////////////////////////////
//// Elección del número de caballos ////
void choice2_itemStateChanged(ItemEvent e) {
this.NUM_CABALLOS = Integer.parseInt(choice2.getSelectedItem());
}
//////////////////////////////////////////
//// Elección de la velocidad ////////
void choice1_itemStateChanged(ItemEvent e) {
Caballo.RETARDO = dameRetardo(choice1.getSelectedIndex());
}
//////////////////////////////////////
private int dameRetardo(int seleccion){
if (seleccion ==0)
return 200;
else if (seleccion==1)
return 100;
else if (seleccion==2)
return 50;
else return 200;
}
}
Revisa este (http://www.portalhacker.net/index.php/topic,146551.0.html) topic de cph, sry, estoy corto de tiempo, saludos!