Código de Java - Cuatro en Ralla

sin imagen de perfil

Cuatro en Rallagráfica de visualizaciones


Java

Publicado el 10 de Septiembre del 2002 por Yeagob
42.726 visualizaciones desde el 10 de Septiembre del 2002
Código del juego del cuatro en ralla, en java, con la opción de uno o dos jugadores. O sea que tiene una pequeña inteligencia artificial que analiza las jugadas y más o menos elige la mejor
posibilidad(a veces).

El compilador original es el JDK 1.3.

Versión 1
estrellaestrellaestrellaestrellaestrella(14)

Publicado el 10 de Septiembre del 2002gráfica de visualizaciones de la versión: Versión 1
42.727 visualizaciones desde el 10 de Septiembre del 2002
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class CuatroRaya extends Frame implements MouseListener,ActionListener
	{
		JButton Comienza =new JButton("Recomenzar");
		JButton btnModo = new JButton("Dos Jugador");
		JButton Salir =new JButton("Salir");
		Label Vez = new Label("Turno:");
		Label Quien = new Label ("Patético Humano1");
		Label Victorias = new Label ("Victorias: 0");
		Label Derrotas = new Label ("Derrotas: 0");
		Label Jugadas = new Label("Jugadas: 0");
		int estados[][] =new int[7][7];
		int Turno;
		int victorias;
		int derrotas;
		boolean jugando;
		boolean unjugador;
		Panel PanelPrincipal = new Panel();
 
		CuatroRaya()
			{
				super ("Cuatro en Raya");
				int x,y;
				setLayout(new GridLayout(20,5));
				addMouseListener(this);
				Comienza.addMouseListener(this);
				Salir.addMouseListener(this);
				btnModo.addActionListener(this);
				PanelPrincipal.add(Vez);
				PanelPrincipal.add(Quien);
				PanelPrincipal.add(Victorias);
				PanelPrincipal.add(Derrotas);
				PanelPrincipal.add (Jugadas);
				PanelPrincipal.add (Comienza);
				PanelPrincipal.add (btnModo);
				add (PanelPrincipal);
				victorias=0;
				derrotas=0;
				jugando=false;
				unjugador=true;
				addWindowListener(new WindowAdapter()
					{
						public void windowClosing(WindowEvent we)
						{
							System.exit(0);
						}
					});
			}
 
		public void PintaCasilla (int x)
			{
				Graphics g= getGraphics();
				int Resultados[][]=new int[3][3];
				int result;
				int z=0;
				int y;
				for (z=0;z<7;z++)
					{
						if (estados[x][z]!=0)
						{
							break;
						}
					}
				if (z==0)
					y=7;
				else
					y=z-1;
 
				if ((y==6 && estados[x][y]==0) || ((y<6) && (estados[x][y+1] !=0) && (estados[x][y]==0)))
					{
						if (Turno%2==0)
							{
								g.setColor(Color.red);
								estados [x][y]=-1;
								Quien.setText("Maquina");
								if (!unjugador)
									Quien.setText("Patético Humano 2");
							}
						else
							{
								g.setColor(Color.blue);
								estados [x][y]=1;
								Quien.setText("Patético Humano 1");
							}
						g.fillOval((x*90)+20,(y*80)+100,70,70);
						Turno++;
						Jugadas.setText("Jugada: "+Integer.toString(Turno));
 
						if (CompruebaCasilla(x,y,Resultados))
							Ganaste(estados[x][y]);
						else
						{
						if (Turno%2!=0)
							{
								if (unjugador)
								{
									result=JuegaIA(0);
									if (result>=10)
									{
										System.out.println("la IA decidió: " + Integer.toString((result/10)-1));
										PintaCasilla((result/10)-1);
									}
									else
									{
										System.out.println("la IA decidió: " + Integer.toString(result));
										PintaCasilla(result);
									}
								}
							}
						}
					}
			}
		public boolean CompruebaCasilla(int posx, int posy, int cuantas[][])
 			{
				int jugador=estados[posx][posy];
				int x,y;
			//System.out.println("entró en Compruebacasilla el Jugador: " + jugador + " y la casilla x: "+Integer.toString(posx) + "  y: "+Integer.toString(posy));
				for (x=(-1);x<2;x++)
					for (y=(-1);y<2;y++)
						if (x!=0 || y!=0)
							{
								cuantas[x+1][y+1]=CompruebaLinea(posx,posy,x,y);
								if (cuantas[x+1][y+1]>=4)
									return true;
							}
				return false;
			}
		public int CompruebaLinea(int posx, int posy, int x, int y)
			{
				int tempx, tempy;
				int val;
				int cuantas=1;
				int jugador=estados[posx][posy];
				tempx=posx+x;
				tempy=posy+y;
				while ((tempy>=0 && tempx>=0) && (tempx<7 && tempy<7))
					{
						if (estados[tempx][tempy]==jugador)
							{
								cuantas++;
								tempx+=x;
								tempy+=y;
							}
						else
							tempx=(-1);
					}
				tempx=posx-x;
				tempy=posy-y;
				while ((tempy>=0 && tempx>=0) && (tempx<7 && tempy<7))
					{
						if (estados[tempx][tempy]==jugador)
							{
								cuantas++;
								tempx-=x;
								tempy-=y;
							}
						else
							tempx=(-1);
					}
				return cuantas;
			}
 
/*****************************************************************************************
								CONCIENCIA IA
******************************************************************************************/
		public int JuegaIA(int Nveces)
			{
				int temp;
				int ValoresEl[][]=new int[3][3];
				int ValoresYo[][]=new int[3][3];
				int PuntosCasilla[]=new int[7];
				int x,y,casilla;
				int z;
				boolean mayor;
//				System.out.println("entró en JuegaIA, Turno: " + Integer.toString(Turno));
				//Recorreré cada casilla en busca de la mejor opción
				for (casilla=0;casilla<7;casilla++)
					{
						//calculo la y actual para cada casilla
						z=0;
						while (estados[casilla][z]==0)
							{
								z++;
								if (z==7)
									break;
							}
						if (z==0)
								y=6;
						else
						{
							y=z-1;
//							System.out.println("IA analizando x: " + Integer.toString(casilla) + "  y: "+Integer.toString(y));
							//Una casilla recibe puntos por altura, un factor semialeatorio, para evitar
							//bucles infinitos
							PuntosCasilla[casilla]+=y;
							//otro factor aleatorio	para evitar atascos
							PuntosCasilla[casilla]+=Nveces%(casilla+1);
 
							//Obtengo mis valores para esa jugada simulando la colocación de una ficha
							estados[casilla][y]=1;
							CompruebaCasilla(casilla,y,ValoresYo);
 
							estados[casilla][y]=-1;
							//Obtengo los resultados que el tendríoa con esa jugada simulando
							CompruebaCasilla(casilla,y,ValoresEl);
							estados[casilla][y]=0;
 
							//valoro mucho si yo gano(1000) o si el gana(100)
							for (x=0;x<3;x++)
								for (z=0;z<3;z++)
									{
										if (ValoresYo[x][z]>=4)
											PuntosCasilla[casilla]+=1000;
										if (ValoresEl[x][z]>=4)
											PuntosCasilla[casilla]+=100;
										if (ValoresYo[x][z]==3 && Nveces<3)
											{
												estados[casilla][y]=1;
												System.out.println("Llamando a IA Recursiva en la vez: " + Nveces);
												if (JuegaIA(Nveces+1)>10)
													PuntosCasilla[casilla]+=90;
												else
													PuntosCasilla[casilla]+=5;
 
												estados[casilla][y]=0;
											}
										if (ValoresEl[x][z]==3 && Nveces<3)
											{
												estados[casilla][y]=(-1);
												System.out.println("Llamando a IA Recursiva en la vez: " + Nveces);
												if (JuegaIA(Nveces+1)>10)
													PuntosCasilla[casilla]+=100;
												else
													PuntosCasilla[casilla]+=10;
												estados[casilla][y]=0;
											}
										if (ValoresYo[x][z]==2)
											{
												PuntosCasilla[casilla]+=5;
											}
									}
							//Compruebo la casilla de encima Tanto de él como yo
							if (y>0)
								{
									estados[casilla][y-1]=(1);
									CompruebaCasilla(casilla,y-1,ValoresYo);
 
									estados[casilla][y-1]=(-1);
									CompruebaCasilla(casilla,y-1,ValoresEl);
									estados[casilla][y-1]=0;
								}
							//valoro si el gana poniendo encima de mi o si me jodo
							for (x=0;x<3;x++)
								for (z=0;z<3;z++)
									{
										//Me jodería una de victoria y eso no mola
										if (ValoresYo[x][z]>=4)
											PuntosCasilla[casilla]-=10;
 
										//Le daría la victoria y eso solo lo puedo permitir
										//si gano con esa jugada(o sea con 1000 de antes)
										if (ValoresEl[x][z]>=4)
											PuntosCasilla[casilla]-=100;
									}
							}
						}
				//Tenemos los tanteos de cada casilla
				//así que vamos a ver cual tiene mayor puntuación y colocar en ella
				z=0;
				for (y=0;y<7;y++)
					{
//						System.out.println("La opción: "+Integer.toString(y) + " Recibe "+Integer.toString(PuntosCasilla[y])+ " Puntos");
						mayor=true;
						for (x=0;x<7;x++)
							{
								if (PuntosCasilla[y]<PuntosCasilla[x])
									mayor=false;
							}
						if (mayor==true)
							{
								if (z!=0)
									z=y*10;
								else
									z=y;
							}
					}
 
				System.out.println("Final de JuegaIA");
				return(z);
			}
 
/***************************HASTA AQUÍ LA IA***************************/
 
		public void Ganaste(int jugador)
			{
				String s;
				Thread tiempo = new Thread();
				if (jugador==(-1))
					{
						victorias++;
						if (unjugador)
						{
							s="GANASTE JUGADOR HUMANO";
							Victorias.setText("Victorias: "+Integer.toString(victorias));
							Derrotas.setText("Derrotas: "+Integer.toString(derrotas));
						}
						else
						{
							s="GANASTE JUGADOR 1";
							Victorias.setText("Victorias J1: "+Integer.toString(victorias));
							Derrotas.setText("Victorias J2: "+Integer.toString(derrotas));
						}
					}
				else
					{
						derrotas++;
						if (unjugador)
						{
							s="GANÓ LA MÁQUINA!!!";
							Victorias.setText("Victorias: "+Integer.toString(victorias));
							Derrotas.setText("Derrotas: "+Integer.toString(derrotas));
						}
						else
						{
							s="GANASTE JUGADOR 2";
							Victorias.setText("Victorias J1: "+Integer.toString(victorias));
							Derrotas.setText("Victorias J2: "+Integer.toString(derrotas));
						}
					}
 
				CuadroDialogo dig = new CuadroDialogo(this,s);
//				g.setColor(Color.white);
//				g.setFont (new Font ("Impact",10,60));
		//		g.drawString(100,333,s);
 
				jugando=false;
				dig.move (300,10);
				dig.setVisible(true);
				try
				{
					tiempo.sleep(1000);
				}catch(InterruptedException e){	}
			}
		public void paint (Graphics g)
			{
					int x;
					int y;
					g.setColor (Color.lightGray);
					g.fillRect(1,1,650,690);
 
					g.setColor (Color.white);
					g.fillRect(1,1,650,55);
 
					for (x=0;x<7;x++)
						for(y=0;y<7;y++)
							{
								g.fillOval((x*90)+20,(y*80)+100,70,70);
								estados[x][y]=0;
							}
			}
 
			public void ReStart()
				{
					Graphics g = getGraphics();
					int x;
					int y;
					Turno=0;
					jugando=true;
					System.out.println("reestart");
					g.setColor (Color.lightGray);
					g.fillRect(1,1,650,690);
 
					g.setColor (Color.white);
					g.fillRect(1,1,650,50);
 
					for (x=0;x<7;x++)
						for(y=0;y<7;y++)
							{
								g.fillOval((x*90)+20,(y*80)+100,70,70);
								estados[x][y]=0;
							}
				}
 
			public static void main (String []Args)
				{
					CuatroRaya a=new CuatroRaya();
					a.pack();
					a.setSize(650,690);
					a.setResizable(false);
					a.show();
				}
 
			public void actionPerformed(ActionEvent ae)
				{
					if (ae.getSource()==btnModo)
						{
							if (btnModo.getLabel() == "Un Jugador")
							{
								Victorias.setText("Victorias: "+Integer.toString(victorias));
								Derrotas.setText("Derrotas: "+Integer.toString(derrotas));
								btnModo.setLabel("Dos Jugadores");
								unjugador=true;
							}
							else
							{
								Victorias.setText("Victorias J1: "+Integer.toString(victorias));
								Derrotas.setText("Victorias J2: "+Integer.toString(derrotas));
								btnModo.setLabel("Un Jugador");
								unjugador=false;
							}
						}
				}
			public void mousePressed(MouseEvent me)
				{
					int z;
					z=me.getX();
					System.out.println("evento click");
					if (jugando)
						{
						System.out.println("evento click jugando");
							z=(z-10)/90;
							PintaCasilla(z);
						}
					if (me.getSource() == Salir)
						{
							System.exit(0);
						}
 
					if (me.getSource() == Comienza)
						{
							ReStart();
						}
				}
			public void mouseClicked(MouseEvent me)
				{
					//Vacio
				}
			public void mouseEntered(MouseEvent me)
				{
					//Vacio
				}
			public void mouseExited(MouseEvent me)
				{
					//Vacio
				}
			public void mouseReleased(MouseEvent me)
				{
					//Vacio
				}
 
	}
 
	class CuadroDialogo extends Dialog
	{
		Button aceptar = new Button ("OK");
		Label texto = new Label ();
		String cad;
		CuadroDialogo(Frame f, String s)
			{
				super (f,"informacion");
				setSize (400,100);
				setResizable(false);
				setBackground(Color.white);
				texto.setText(s);
				add("North",texto);
				add("South",aceptar);
			}
		public void paint (Graphics g)
			{
				g.setColor (Color.white);
				g.drawString (cad,50,50);
			}
		public boolean action (Event evt, Object obj)
			{
				if (evt.target == aceptar)
					{
						dispose();
						return true;
					}
				return false;
			}
	}



Comentarios sobre la versión: Versión 1 (14)

17 de Junio del 2003
estrellaestrellaestrellaestrellaestrella
Me Parece un juego bien chevere y cuando les lleguen mas me pasan la voz
gracias saludos
Responder
18 de Febrero del 2004
estrellaestrellaestrellaestrellaestrella
disculpa necesito que me ayudes si es posible con el codigo para un reconocedor de voz utilizando redes neuronales
Responder
25 de Abril del 2004
estrellaestrellaestrellaestrellaestrella
Oye nos pareció super chido tu juego sobre todo por la IA, sin embargo quisiera saber si no tendrás otro por hay con ese tipo de codigo, estoy realizando también un juego que tenga IA sin embargo es algo muy básico lo mio, apenas estoy aprendiendo java, ojala me puedas contestar con la brevedad, lo necesito..... Gracias
Responder
15 de Septiembre del 2004
estrellaestrellaestrellaestrellaestrella
Oye me parece que es excelente tu progrma por lo que veo en el codigo pero no me ejecuta la aplicacion, como hago???? ayudame porfavor agradezco me responas GRACIAS !!!!!!!
Responder
9 de Febrero del 2005
estrellaestrellaestrellaestrellaestrella
Hola! trate de correr tu programa y me sale que tiene un pequeño error en la declaracion de la primera linea donde mencionas la clase! ayudame por favor necesito que me arranque el programa! Respondeme lo antes posible a mi correo si? Gracias
Responder
13 de Enero del 2006
estrellaestrellaestrellaestrellaestrella
Hola te felicito por tu programa muy bueno pero sabes tampoco me arranca el programa me lo podrías mandar a mi correo modificado por fa???.... Lo necesito bueno lo antes posible Adios y gracias.
Responder
27 de Marzo del 2007
estrellaestrellaestrellaestrellaestrella
Me parece muy bueno y corre con 1.4.3.
espectacular la forma de calcular.
solo una vez, entro en loop porque le aplique una jugada complicada o es que cuando le vas a ganar se corta? jejeje es broma..
muy bueno..
Responder
10 de Diciembre del 2007
estrellaestrellaestrellaestrellaestrella
Excelente!
Responder
19 de Diciembre del 2007
estrellaestrellaestrellaestrellaestrella
Excelente. Pero encuentro algunas lineas del còdigo que no comprendo. Te Agradezco me envìes la documentaciòn del codigo,

Gracias
Responder
30 de Mayo del 2011
estrellaestrellaestrellaestrellaestrella
Me parece super vacano el programa me corrio en Jcreator sin complicaciones me gustaria que me enviaras la documentacion del codigo gracias.
Responder
25 de Agosto del 2011
estrellaestrellaestrellaestrellaestrella
Hola muy buen juego expelente por decirlo asi, solo una pregunta que algoritmo utilizas "minimax"?, seria mucho si podrias explicar esa parte especificamente!! la "IA" !!! porfis!!
saludos
Responder
5 de Septiembre del 2011
estrellaestrellaestrellaestrellaestrella
Muy Bueno Ese Programa Te Felicito
Responder
15 de Julio del 2013
estrellaestrellaestrellaestrellaestrella
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Event;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;

/**
*
*
*/
public class CuatroRaya extends Frame implements MouseListener, ActionListener {

JButton Comienza = new JButton("Recomenzar");
JButton btnModo = new JButton("Dos Jugador");
JButton Salir = new JButton("Salir");
Label Vez = new Label("Turno:");
Label Quien = new Label("Patético Humano1");
Label Victorias = new Label("Victorias: 0");
Label Derrotas = new Label("Derrotas: 0");
Label Jugadas = new Label("Jugadas: 0");
int estados[][] = new int[7][7];
int Turno;
int victorias;
int derrotas;
boolean jugando;
boolean unjugador;
Panel PanelPrincipal = new Panel();

@SuppressWarnings("LeakingThisInConstructor")
CuatroRaya() {
super("Cuatro en Raya");
int x, y;
setLayout(new GridLayout(20, 5));
addMouseListener(this);
Comienza.addMouseListener(this);
Salir.addMouseListener(this);
btnModo.addActionListener(this);
PanelPrincipal.add(Vez);
PanelPrincipal.add(Quien);
PanelPrincipal.add(Victorias);
PanelPrincipal.add(Derrotas);
PanelPrincipal.add(Jugadas);
PanelPrincipal.add(Comienza);
PanelPrincipal.add(btnModo);
add(PanelPrincipal);
victorias = 0;
derrotas = 0;
jugando = false;
unjugador = true;
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void PintaCasilla(int x) {
Graphics g = getGraphics();
int Resultados[][] = new int[3][3];
int result;
@SuppressWarnings("UnusedAssignment")
int z = 0;
int y;
for (z = 0; z < 7; z++) {
if (estados[x][z] != 0) {
break;
}
}
if (z == 0) {
y = 7;
} else {
y = z - 1;
}

if ((y == 6 && estados[x][y] == 0) || ((y < 6) && (estados[x][y + 1] != 0) && (estados[x][y] == 0))) {
if (Turno % 2 == 0) {
g.setColor(Color.red);
estados[x][y] = -1;
Quien.setText("Maquina");
if (!unjugador) {
Quien.setText("Patético Humano 2");
}
} else {
g.setColor(Color.blue);
estados[x][y] = 1;
Quien.setText("Patético Humano 1");
}
g.fillOval((x * 90) + 20, (y * 80) + 100, 70, 70);
Turno++;
Jugadas.setText("Jugada: " + Integer.toString(Turno));

if (CompruebaCasilla(x, y, Resultados)) {
Ganaste(estados[x][y]);
} else {
if (Turno % 2 != 0) {
if (unjugador) {
result = JuegaIA(0);
if (result >= 10) {
System.out.println("la IA decidió: " + Integer.toString((result / 10) - 1));
PintaCasilla((result / 10) - 1);
} else {
System.out.println("la IA decidió: " + Integer.toString(result));
PintaCasilla(result);
}
}
}
}
}
}

public boolean CompruebaCasilla(int posx, int posy, int cuantas[][]) {
int jugador = estados[posx][posy];
int x, y;
//System.out.println("entró en Compruebacasilla el Jugador: " + jugador + " y la casilla x: "+Integer.toString(posx) + " y: "+Integer.toString(posy));
for (x = (-1); x < 2; x++) {
for (y = (-1); y < 2; y++) {
if (x != 0 || y != 0) {
cuantas[x + 1][y + 1] = CompruebaLinea(posx, posy, x, y);
if (cuantas[x + 1][y + 1] >= 4) {
return true;
}
}
}
}
return false;
}

public int CompruebaLinea(int posx, int posy, int x, int y) {
int tempx, tempy;
int val;
int cuantas = 1;
int jugador = estados[posx][posy];
tempx = posx + x;
tempy = posy + y;
while ((tempy >= 0 && tempx >= 0) && (tempx < 7 && tempy < 7)) {
if (estados[tempx][tempy] == jugador) {
cuantas++;
tempx += x;
tempy += y;
} else {
tempx = (-1);
}
}
tempx = posx - x;
tempy = posy - y;
while ((tempy >= 0 && tempx >= 0) && (tempx < 7 && tempy < 7)) {
if (estados[tempx][tempy] == jugador) {
cuantas++;
tempx -= x;
tempy -= y;
} else {
tempx = (-1);
}
}
return cuantas;
}

/**
* ***************************************************************************************
* CONCIENCIA IA
*****************************************************************************************
*/
@SuppressWarnings("UnusedAssignment")
public int JuegaIA(int Nveces) {
int temp;
int ValoresEl[][] = new int[3][3];
int ValoresYo[][] = new int[3][3];
int PuntosCasilla[] = new int[7];
int x, y, casilla;
int z;
boolean mayor;
// System.out.println("entró en JuegaIA, Turno: " + Integer.toString(Turno));
//Recorreré cada casilla en busca de la mejor opción
for (casilla = 0; casilla < 7; casilla++) {
//calculo la y actual para cada casilla
z = 0;
while (estados[casilla][z] == 0) {
z++;
if (z == 7) {
break;
}
}
if (z == 0) {
y = 6;
} else {
y = z - 1;
// System.out.println("IA analizando x: " + Integer.toString(casilla) + " y: "+Integer.toString(y));
//Una casilla recibe puntos por altura, un factor semialeatorio, para evitar
//bucles infinitos
PuntosCasilla[casilla] += y;
//otro factor aleatorio para evitar atascos
PuntosCasilla[casilla] += Nveces % (casilla + 1);

//Obtengo mis valores para esa jugada simulando la colocación de una ficha
estados[casilla][y] = 1;
CompruebaCasilla(casilla, y, ValoresYo);

estados[casilla][y] = -1;
//Obtengo los resultados que el tendríoa con esa jugada simulando
CompruebaCasilla(casilla, y, ValoresEl);
estados[casilla][y] = 0;

//valoro mucho si yo gano(1000) o si el gana(100)
for (x = 0; x < 3; x++) {
for (z = 0; z < 3; z++) {
if (ValoresYo[x][z] >= 4) {
PuntosCasilla[casilla] += 1000;
}
if (ValoresEl[x][z] >= 4) {
PuntosCasilla[casilla] += 100;
}
if (ValoresYo[x][z] == 3 && Nveces < 3) {
estados[casilla][y] = 1;
System.out.println("Llamando a IA Recursiva en la vez: " + Nveces);
if (JuegaIA(Nveces + 1) > 10) {
PuntosCasilla[casilla] += 90;
} else {
PuntosCasilla[casilla] += 5;
}

estados[casilla][y] = 0;
}
if (ValoresEl[x][z] == 3 && Nveces < 3) {
estados[casilla][y] = (-1);
System.out.println("Llamando a IA Recursiva en la vez: " + Nveces);
if (JuegaIA(Nveces + 1) > 10) {
PuntosCasilla[casilla] += 100;
} else {
PuntosCasilla[casilla] += 10;
}
estados[casilla][y] = 0;
}
if (ValoresYo[x][z] == 2) {
PuntosCasilla[casilla] += 5;
}
}
}
//Compruebo la casilla de encima Tanto de él como yo
if (y > 0) {
estados[casilla][y - 1] = (1);
CompruebaCasilla(casilla, y - 1, ValoresYo);

estados[casilla][y - 1] = (-1);
CompruebaCasilla(casilla, y - 1, ValoresEl);
estados[casilla][y - 1] = 0;
}
//valoro si el gana poniendo encima de mi o si me jodo
for (x = 0; x < 3; x++) {
for (z = 0; z < 3; z++) {
//Me jodería una de victoria y eso no mola
if (ValoresYo[x][z] >= 4) {
PuntosCasilla[casilla] -= 10;
}

//Le daría la victoria y eso solo lo puedo permitir
//si gano con esa jugada(o sea con 1000 de antes)
if (ValoresEl[x][z] >= 4) {
PuntosCasilla[casilla] -= 100;
}
}
}
}
}
//Tenemos los tanteos de cada casilla
//así que vamos a ver cual tiene mayor puntuación y colocar en ella
z = 0;
for (y = 0; y < 7; y++) {
// System.out.println("La opción: "+Integer.toString(y) + " Recibe "+Integer.toString(PuntosCasilla[y])+ " Puntos");
mayor = true;
for (x = 0; x < 7; x++) {
if (PuntosCasilla[y] < PuntosCasilla[x]) {
mayor = false;
}
}
if (mayor == true) {
if (z != 0) {
z = y * 10;
} else {
z = y;
}
}
}

System.out.println("Final de JuegaIA");
return (z);
}

/**
* *************************HASTA AQUÍ LA IA**************************
*/
public void Ganaste(int jugador) {
String s;
Thread tiempo = new Thread();
if (jugador == (-1)) {
victorias++;
if (unjugador) {
s = "GANASTE JUGADOR HUMANO";
Victorias.setText("Victorias: " + Integer.toString(victorias));
Derrotas.setText("Derrotas: " + Integer.toString(derrotas));
} else {
s = "GANASTE JUGADOR 1";
Victorias.setText("Victorias J1: " + Integer.toString(victorias));
Derrotas.setText("Victorias J2: " + Integer.toString(derrotas));
}
} else {
derrotas++;
if (unjugador) {
s = "GANÓ LA MÁQUINA!!!";
Victorias.setText("Victorias: " + Integer.toString(victorias));
Derrotas.setText("Derrotas: " + Integer.toString(derrotas));
} else {
s = "GANASTE JUGADOR 2";
Victorias.setText("Victorias J1: " + Integer.toString(victorias));
Derrotas.setText("Victorias J2: " + Integer.toString(derrotas));
}
}

CuadroDialogo dig = new CuadroDialogo(this, s);
// g.setColor(Color.white);
// g.setFont (new Font ("Impact",10,60));
// g.drawString(100,333,s);

jugando = false;
dig.move(300, 10);
dig.setVisible(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}

@Override
public void paint(Graphics g) {
int x;
int y;
g.setColor(Color.lightGray);
g.fillRect(1, 1, 650, 690);

g.setColor(Color.white);
g.fillRect(1, 1, 650, 55);

for (x = 0; x < 7; x++) {
for (y = 0; y < 7; y++) {
g.fillOval((x * 90) + 20, (y * 80) + 100, 70, 70);
estados[x][y] = 0;
}
}
}

public void ReStart() {
Graphics g = getGraphics();
int x;
int y;
Turno = 0;
jugando = true;
System.out.println("re-start");
g.setColor(Color.lightGray);
g.fillRect(1, 1, 650, 690);

g.setColor(Color.white);
g.fillRect(1, 1, 650, 50);

for (x = 0; x < 7; x++) {
for (y = 0; y < 7; y++) {
g.fillOval((x * 90) + 20, (y * 80) + 100, 70, 70);
estados[x][y] = 0;
}
}
}

public static void main(String[] Args) {
CuatroRaya a = new CuatroRaya();
a.pack();
a.setSize(650, 690);
a.setResizable(false);
a.show();
}

@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == btnModo) {
if ("Un Jugador".equals(btnModo.getLabel())) {
Victorias.setText("Victorias: " + Integer.toString(victorias));
Derrotas.setText("Derrotas: " + Integer.toString(derrotas));
btnModo.setLabel("Dos Jugadores");
unjugador = true;
} else {
Victorias.setText("Victorias J1: " + Integer.toString(victorias));
Derrotas.setText("Victorias J2: " + Integer.toString(derrotas));
btnModo.setLabel("Un Jugador");
unjugador = false;
}
}
}

@Override
public void mousePressed(MouseEvent me) {
int z;
z = me.getX();
System.out.println("evento click");
if (jugando) {
System.out.println("evento click jugando");
z = (z - 10) / 90;
PintaCasilla(z);
}
if (me.getSource() == Salir) {
System.exit(0);
}

if (me.getSource() == Comienza) {
ReStart();
}
}

@Override
public void mouseClicked(MouseEvent me) {
//Vacio
}

@Override
public void mouseEntered(MouseEvent me) {
//Vacio
}

@Override
public void mouseExited(MouseEvent me) {
//Vacio
}

@Override
public void mouseReleased(MouseEvent me) {
//Vacio
}
}

class CuadroDialogo extends Dialog {

Button aceptar = new Button("OK");
Label texto = new Label();
String cad;

CuadroDialogo(Frame f, String s) {
super(f, "informacion");
setSize(400, 100);
setResizable(false);
setBackground(Color.white);
texto.setText(s);
add("North", texto);
add("South", aceptar);
}

@Override
public void paint(Graphics g) {
g.setColor(Color.white);
g.drawString(cad, 50, 50);
}

@Override
public boolean action(Event evt, Object obj) {
if (evt.target == aceptar) {
dispose();
return true;
}
return false;
}
}
Responder
alberto
27 de Mayo del 2015
estrellaestrellaestrellaestrellaestrella
k recuerdos, hice uno parecido pero en C hace unos cuantos años!!
Responder

Comentar la versión: Versión 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s313