Social Icons

Featured Posts

viernes, 28 de marzo de 2014

Como programar en red con visual basic 6 - programar juego del gato en red

¿Como programar un juego en red?

Para programar un juego en red, se necesitan simples pasos, los cuales son los siguientes:

  1. Crear una pantalla de Servidor y una pantalla de cliente. Esto para que el juego pueda sostenerse solo, y no necesite que otro programa actúe como servidor.
  2. Establecer la conexión entre el cliente y el servidor.
  3. Para enviar un comando, se debe enviar una clave, que el programa que lo recibe lo interpretará como que debe hacer una acción. Antes de realizar dicha acción debe informar al origen, que ya recibió la orden y que procederá a ejecutarla, esto para si el origen desea ejecutar alguna otra acción.
  4. Gestionar los posibles eventos en los dos programas: Cliente y servidor. Ya que si el cliente ganó, debe aparecer un mensaje de que ganó y en el programa servidor debe aparecer que perdió. 

Programando el juego del gato en red

Primeramente debemos crear los siguientes controles:
-          9 botones de comando que serán el tablero del juego, los cuales estarán dentro de un frame, llamado frame2.
-          Un frame y dentro de él dos botones de opción y textos para gestionar puertos y conexiones a IP. Además de botones de comando para aceptar y para cancelar.


Debe ser tal como se muestra en la figura. Puede basarse en el código fuente proporcionado para que sepa bien qué es lo que debe hacer.


En la parte “LOAD” del formulario, colocar el siguiente código:

  Option1.Value = True

Explicación: Establecemos que la opción 1 aparecerá elegida por default.







En el botón Option1, colocar el siguiente código:

  If Option1.Value = True Then
    Label2.Visible = False
    Text2.Visible = False
    Text3.Visible = False
    Label4.Visible = False
    Command11.Visible = False
    Label1.Visible = True
    Text1.Visible = True
    Command10.Visible = True
    Text4.Text = "X"    
  End If

Explicación: Indicamos que se activen los controles correspondientes al servidor.

En el botón Option2, colocar el siguiente código:

  If Option2.Value = True Then
    Label2.Visible = True
    Text2.Visible = True
    Text3.Visible = True
    Label4.Visible = True
    Command11.Visible = True
    Label1.Visible = False
    Text1.Visible = False
    Command10.Visible = False
    Text4.Text = "O"
  End If

Explicación: Indicamos que se activen los controles correspondientes al cliente.

En el botón “OK”, de servidor, colocar el siguiente código:

  Winsock1.LocalPort = Text1.Text
  Winsock1.Close
  Winsock1.Listen
  Frame1.Enabled = False
  Frame2.Enabled = True
 
  Command12.Visible = True

Explicación: Ponemos el juego a la espera de conexiones
                              



En el botón “OK”, de cliente, colocar el siguiente código:

  Winsock1.Connect Text2.Text, Text3.Text
  Frame1.Enabled = False
  Command12.Visible = True

Explicación: Con este código se establece la conexión Cliente a Servidor.

En el botón “X” colocar el siguiente código:

  Winsock1.Close
  Command12.Visible = False
  Frame1.Enabled = True
 
  Text1.Text = ""
  Text2.Text = ""
  Text3.Text = ""

Explicación: En este código la conexión entre cliente y servidor es cerrada.


En el control Winsock1, en el evento ConnectionRequest, colocar el siguiente código:

  Winsock1.Close
  Winsock1.Accept requestID

Explicación: El servidor acepta la conexión entrante.

En el control winsock, en el evento DataArrival, colocar el siguiente código:

  Dim datos As String
  Winsock1.GetData datos
  If datos = "1" Then
    Winsock1.SendData "recibido1"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command1.Caption = "X"
    Else
      Command1.Caption = "O"
    End If
  End If
 
  If datos = "recibido1" Then
    Command1.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "2" Then
    Winsock1.SendData "recibido2"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command2.Caption = "X"
    Else
      Command2.Caption = "O"
    End If
  End If
 
  If datos = "recibido2" Then
    Command2.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "3" Then
    Winsock1.SendData "recibido3"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command3.Caption = "X"
    Else
      Command3.Caption = "O"
    End If
  End If
 
  If datos = "recibido3" Then
    Command3.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "4" Then
    Winsock1.SendData "recibido4"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command4.Caption = "X"
    Else
      Command4.Caption = "O"
    End If
  End If
 
  If datos = "recibido4" Then
    Command4.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "5" Then
    Winsock1.SendData "recibido5"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command5.Caption = "X"
    Else
      Command5.Caption = "O"
    End If
  End If
 
  If datos = "recibido5" Then
    Command5.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "6" Then
    Winsock1.SendData "recibido6"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command6.Caption = "X"
    Else
      Command6.Caption = "O"
    End If
  End If
 
  If datos = "recibido6" Then
    Command6.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "7" Then
    Winsock1.SendData "recibido7"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command7.Caption = "X"
    Else
      Command7.Caption = "O"
    End If
  End If
 
  If datos = "recibido7" Then
    Command7.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "8" Then
    Winsock1.SendData "recibido8"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command8.Caption = "X"
    Else
      Command8.Caption = "O"
    End If
  End If
 
  If datos = "recibido8" Then
    Command8.Caption = Text4.Text
    Frame2.Enabled = False
  End If
 
 
  If datos = "9" Then
    Winsock1.SendData "recibido9"
    Frame2.Enabled = True
    If Text4.Text = "O" Then
      Command9.Caption = "X"
    Else
      Command9.Caption = "O"
    End If
  End If
 
  If datos = "recibido9" Then
    Command9.Caption = Text4.Text
    Frame2.Enabled = False
  End If

Explicación: En data arrival, llegan todos los datos que se reciben y es aquí donde los procesamos.











Y por último en el Timer1, colocar el siguiente código:

  If Option1.Value = True And Winsock1.State = 2 Then
    Label3.Caption = "Puerto " & Winsock1.LocalPort & " abierto"
  End If
 
  If Option1.Value = True And Winsock1.State = 7 Then
    Label3.Caption = "Conexión recibida y aceptada. Conexión establecida"
  End If
 
  If Option2.Value = True And Winsock1.State = 7 Then
    Label3.Caption = "Conexión establecida con la IP: " & Winsock1.RemoteHostIP
  End If
 
  If Not (Option1.Value = True And Winsock1.State = 2) And Not (Option2.Value = True And Winsock1.State = 7) And Not (Option1.Value = True And Winsock1.State = 7) Then
    Label3.Caption = ""
  End If
 
  If Len(Command1.Caption) > 0 And Len(Command2.Caption) > 0 And Len(Command3.Caption) > 0 And Len(Command4.Caption) > 0 And Len(Command5.Caption) > 0 And Len(Command6.Caption) > 0 And Len(Command7.Caption) > 0 And Len(Command8.Caption) > 0 And Len(Command9.Caption) > 0 Then
    limpiar
    MsgBox "Juego sin ganador", vbOKOnly, "Juego del gato en red"
  End If
 
  If Command1.Caption = "X" And Command2.Caption = "X" And Command3.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
  If Command1.Caption = "X" And Command4.Caption = "X" And Command7.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
  If Command1.Caption = "X" And Command5.Caption = "X" And Command9.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 

  If Command2.Caption = "X" And Command5.Caption = "X" And Command8.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command3.Caption = "X" And Command5.Caption = "X" And Command7.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command3.Caption = "X" And Command6.Caption = "X" And Command9.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command4.Caption = "X" And Command5.Caption = "X" And Command6.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command7.Caption = "X" And Command8.Caption = "X" And Command9.Caption = "X" Then
    If Text4.Text = "X" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command1.Caption = "O" And Command2.Caption = "O" And Command3.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
  If Command1.Caption = "O" And Command4.Caption = "O" And Command7.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
  If Command1.Caption = "O" And Command5.Caption = "O" And Command9.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 

  If Command2.Caption = "O" And Command5.Caption = "O" And Command8.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command3.Caption = "O" And Command5.Caption = "O" And Command7.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command3.Caption = "O" And Command6.Caption = "O" And Command9.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command4.Caption = "O" And Command5.Caption = "O" And Command6.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If
 
 
  If Command7.Caption = "O" And Command8.Caption = "O" And Command9.Caption = "O" Then
    If Text4.Text = "O" Then
      MsgBox "Has ganado el juego", vbOKOnly, "Juego del gato en red"
    Else
      MsgBox "Has perdido el juego", vbOKOnly, "Juego del gato en red"
    End If
    limpiar
  End If

Explicación: El timer es el que se encarga de verificar a cada instante si ya hay un ganador o si el juego terminó sin ganador, y de acuerdo a esto manda un mensaje de información.

Te recordamos que este y otros códigos fuente, los puedes obtener de: 

Como programar en red con visual basic 6 - Mini-chat que acepta varias conexiones

Ahora entraremos a la programación de un minichat que aceptará varias conexiones. El anterior solo aceptaba una conexión, que era 1 solo servidor con 1 solo cliente, ahora será 1 solo servidor con x número de clientes.

Viendo este código, se podrán hacer muchas otras aplicaciones similares, éste minichat se puede decir que es la base para poder crear sistemas de administración, ya sea de cybers, control de acceso, en el que se involucran varias computadoras clientes.

El minichat en lugar de usar el puerto 10112 como el anterior, usará el puerto 80 para asegurar de que también podrá usarse a través de internet.

El código tiene explicación linea por linea.


En un formulario, que actuará como menú, se crean los siguientes submenús


Debe verse algo así:


Y entonces programaremos los menús:

Private Sub mcliente1_Click()
  cliente.Show 'llama al formulario "cliente2"
End Sub

Private Sub mcliente2_Click()
  cliente2.Show 'llama al formulario "cliente2"
End Sub

Private Sub salir_Click()
  Unload Me
End Sub

Private Sub servidor1_Click()
  servidor.Show 'llama al formulario "servidor"
End Sub

Entonces creamos un nuevo formulario que se llame “servidor”, al cual le agregaremos:
-          1 listbox
-          2 textos (text2 y text1)
-          1 botón de comando (command2), en caption “Enviar”
-          3 etiquetas (label1, label2, label5), label1 en caption “Estado”, label5 en caption “Mi ip es:”
-          1 timer (timer1), timer1 en interval = 1
-          1 winsock(winsock1), winsock1 en index = 0



Ahora coloca el siguiente código fuente

Public contador_conexiones As Integer
Private Sub Delay(lngCentSeg As Long)
  Dim TimeEnd As Single
  TimeEnd = Timer + lngCentSeg / 100
  Do While TimeEnd > Timer
    DoEvents
  Loop
End Sub

Private Sub Command2_Click()
  Dim enviar As String
  enviar = Text2.Text
  Dim c As Integer
  c = 1
  'Ciclo para enviar datos a todos los clientes
  While c < contador_conexiones
    Call Delay(1)
    If Val(Winsock1(c).State) = 7 Then 'Si la conexión está establecida con el cliente
      Winsock1(c).SendData enviar 'Enviamos datos al cliente
    End If
    c = c + 1
  Wend
  List1.AddItem "yo: " & enviar ' Imprimimos en nuestra pantalla el mensaje mandado
  Text2.Text = ""
End Sub

Private Sub Form_Load()
  Winsock1(0).LocalPort = 80 'Establecemos el puerto que se usará
  Winsock1(0).Listen 'Pone a la escucha el winsock principal
  contador_conexiones = 1
  Text1.Text = Winsock1(0).LocalIP ' Obtenemos la ip de nuestra computadora
End Sub

Private Sub Timer1_Timer()
  If Winsock1(0).State = 2 Then 'Si el winsock está a la espera de conexiones
    Label2.Caption = "Esperando una solicitud de conexión"
  End If
  If List1.ListCount > 0 Then
    List1.ListIndex = List1.ListCount - 1 'Se selecciona el último mensaje recibido
  End If
End Sub




Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
  Load Winsock1(contador_conexiones)  'Se crea un nuevo winsock en el vector
  Winsock1(contador_conexiones).Close 'Se cierra el winsock creado
  Winsock1(contador_conexiones).Accept requestID 'El winsock creado acepta la conexión entrante
  contador_conexiones = contador_conexiones + 1 'Aumentamos nuestra variable de conexiones
End Sub


Private Sub Winsock1_DataArrival(Index As Integer, ByVal bytesTotal As Long)
  Dim datos As String
  Winsock1(Index).GetData datos 'Obtenemos los datos que haya enviado x cliente
  List1.AddItem Winsock1(Index).RemoteHost & datos 'Ponemos en pantalla el mensaje recibido
End Sub


Ahora crea un nuevo formulario el cual se llamará “cliente”, al cual le agregarás:
-          1 listbox
-          2 etiquetas (label1, label3), label1 en caption “IP”, label3 en caption “Mi IP es:”
-          3 textos (text2, text3, text1)
-          2 botones de comando (command2, command1), command2 en caption “Enviar”, command1 en caption ”Conectar ”.
-          1 winsock (winsock1)
-          1 timer (timer1), timer en interval = 30





Ahora agrega el siguiente código:

Private Sub Command1_Click()
  If Command1.Caption = "Conectar" Then
    Winsock1.Connect Text3.Text, 80 'Conectamos mediante el puerto 80
  Else
    Unload Me    'Cerramos el formulario
    cliente.Show 'Lo volvemos a abrir
  End If
End Sub

Private Sub Command2_Click()
  If Winsock1.State = 7 Then 'Si la conexión está establecida
    Dim enviar As String
    enviar = Text2.Text
    Winsock1.SendData Winsock1.LocalHostName & ": " & enviar 'Enviamos un mensaje como el siguiente: nombre_computadora:mensaje
    List1.AddItem "yo" & ": " & enviar 'Imprimimos en nuestra propia pantalla el mensaje enviado
    Text2.Text = ""
  Else
    MsgBox ("Error, al enviar mensaje") 'Se manda un mensaje de error si la conexión no está establecida
  End If
End Sub

Private Sub Form_Load()
  Text1.Text = Winsock1.LocalIP 'Obtenemos nuestra propia IP
End Sub

Private Sub Timer1_Timer()
  If Winsock1.State = 7 Then 'Si la conexión está establecida
    Command1.Caption = "Desconectar"
  End If
  If Winsock1.State = 0 Then 'Si la conexión está cerrada
    Command1.Caption = "Conectar"
  End If
  If List1.ListCount > 0 Then
    List1.ListIndex = List1.ListCount - 1 'Se selecciona el último mensaje recibido
  End If
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
  Dim datos As String
  Winsock1.GetData datos 'Obtenemos los datos que haya enviado el servidor
  List1.AddItem "Servidor: " & datos 'Ponemos en pantalla el mensaje recibido
End Sub
Crea un nuevo formulario, que se llamará “cliente2”, y haz lo mismo que en el cliente1.

Ahora procedemos a ejecutar nuestro programa, y se debe ver de la siguiente manera:



Te recordamos que este y otros códigos fuente, los puedes obtener de: 
 
Blogger Templates