Posted on 29-06-2008
Filed Under (Desarrollo, VB.NET) by Programlocura

Hace un tiempo en el curso empezamos con este proyecto y lo estamos agrandando cada dia.
Voy a tratar de ir mostrando de a partes y dando consejos para construir un juego de este tipo en CONSOLA y dejando bien abierto para proximas cosas que tengan ganas de ponerle.

1. Uso de Constantes

Visual Basic:
  1. Const FILAS As Integer = 10
  2. Const COLUMNAS As Integer = 10
  3. Const CANT_BARCOS As Integer = 4

Siempre! Siempre! Se usan constantes para este tipo de cosas, es complicado acostumbrarse a programar "generico" pero tiene que hacerse, que pasa si cambia el tamaño del tablero? Que pasa si queremos aumentar el numero de barcos en el juego? Tendriamos que cambiar todos los numeros en el codigo, seria un desastre.
El uso de constantes evita todo tipo de problemas y el uso de las palabras hace más clara la lectura del codigo.

2. El Procedimiento "Main()" limpio.

Visual Basic:
  1. Sub Main()
  2.         Dim opcion As Integer
  3.         Dim Pantalla As New ClearConsole
  4.  
  5.         Titulo()
  6.         Console.WriteLine("1. Player 1 Vs Player 2")
  7.         Console.WriteLine("2. Player 1 Vs CPU")
  8.         Do
  9.             opcion = Console.ReadLine()
  10.  
  11.             If (opcion> 2) Then
  12.                 Console.WriteLine("La opcion no esta disponible")
  13.             End If
  14.         Loop While (opcion> 2)
  15.  
  16.         Select Case opcion
  17.             Case 1
  18.                 Pantalla.Clear()
  19.                 Player1vs2()
  20.             Case 2
  21.                 Pantalla.Clear()
  22.                 Player1vsCPU()
  23.         End Select
  24.     End Sub

El Main debe contener el menor numero de instrucciones posibles, cuanto más limpio mejor, no tiene porque pero si es muy recomendable.

3. Procedimientos genericos util para cualquier cantidad de jugadores

Visual Basic:
  1. Sub Player1vs2()
  2.         ' Player 1 VS Player 2
  3.         Dim Jugador As Short = 1
  4.         Dim Tablero_uno(FILAS, COLUMNAS), Tablero_dos(FILAS, COLUMNAS) As Short
  5.         Dim Tablero_uno_aux(FILAS, COLUMNAS), Tablero_dos_aux(FILAS, COLUMNAS) As Short
  6.         Dim num_barcos_uno, num_barcos_dos, intento As Integer
  7.         Dim x, y, xx, yy, i, j As Integer
  8.         Dim Pantalla As New ClearConsole
  9.  
  10.         cargaBarcos(Jugador, Tablero_uno)
  11.         Jugador = 2
  12.         cargaBarcos(Jugador, Tablero_dos)
  13.  
  14.         ' Comenzamos a Jugar
  15.         intento = 1
  16.         Jugador = 1
  17.  
  18.         num_barcos_uno = CANT_BARCOS
  19.         num_barcos_dos = CANT_BARCOS
  20.  
  21.             Do
  22.                 Pantalla.Clear()
  23.                 Titulo()
  24.                 Console.WriteLine("Empieza el juego")
  25.                 Console.WriteLine("Jugador {0} - Intente hundir un barco:", Jugador)
  26.                 Console.WriteLine("Barco {0} - FILA:", intento)
  27.                 Do
  28.                     Do
  29.                         xx = Console.ReadLine()
  30.                         If (xx> FILAS) Then
  31.                             Console.WriteLine("El numero es Mayor al numero de FILAS")
  32.                         End If
  33.                     Loop While (xx> FILAS)
  34.                     Console.WriteLine("Barco {0} - COLUMNA:", intento)
  35.                     Do
  36.                         yy = Console.ReadLine()
  37.                         If (yy> COLUMNAS) Then
  38.                             Console.WriteLine("El numero es Mayor al numero de COLUMNAS")
  39.                         End If
  40.                     Loop While (yy> COLUMNAS)
  41.  
  42.                     If ((Jugador = 1 And Tablero_uno_aux(xx, yy) = 1) Or (Jugador = 2 And Tablero_dos_aux(xx, y) = 1)) Then
  43.                         Console.WriteLine("La Posicion {0},{1} Esta ocupada", xx, yy)
  44.                     End If
  45.                 Loop While ((Jugador = 1 And Tablero_uno_aux(xx, yy) = 1) Or (Jugador = 2 And Tablero_dos_aux(xx, y) = 1))
  46.  
  47.                 If (Jugador = 1) Then
  48.                     If Tablero_dos(xx, yy) = 1 Then
  49.                         Console.WriteLine("Has Hundido el Barco ({0},{1}) !", xx, yy)
  50.                         Tablero_dos_aux(xx, yy) = 2
  51.                         num_barcos_dos -= 1
  52.                         Jugador = 2
  53.                     Else
  54.                         Console.WriteLine("Agua en la posicion ({0},{1})", xx, yy)
  55.                         Tablero_dos_aux(xx, yy) = 1
  56.                         Jugador = 2
  57.                     End If
  58.                 Else
  59.                     If Tablero_uno(xx, yy) = 1 Then
  60.                         Console.WriteLine("Has Hundido el Barco ({0},{1}) !", xx, yy)
  61.                         Tablero_uno_aux(xx, yy) = 2
  62.                         num_barcos_uno -= 1
  63.                         Jugador = 1
  64.                     Else
  65.                         Console.WriteLine("Agua en la posicion ({0},{1})", xx, yy)
  66.                         Tablero_uno_aux(xx, yy) = 1
  67.                         Jugador = 1
  68.                     End If
  69.                 End If
  70.                 Console.ReadLine()
  71.         Loop While (num_barcos_uno <> 0 Or num_barcos_dos <> 0)
  72.     End Sub

Los procedimientos deben ser genericos SIEMPRE! no podemos estar copiando y pegando codigo cada vez que necesitemos insertar un jugador nuevo por ejemplo.

Dejemoslo por acá... Esperen la 2° Parte :D.

(0) Comments    Read More   
Posted on 11-05-2008
Filed Under (Desarrollo, VB.NET) by Programlocura

Tengo que admitir que a pesar de no ser un "gran fanatico" de las tecnologias de Microsoft, es muy utilizada y en muchos casos es bastante util. Hace poco comenzé con mi carrera (Analista de Sistemas) y hemos comenzado el primer modulo: VB.NET. Luego de haber hecho un par de aplicaciones de bajo "calibre" un problema con el profesor hizo que apareciera una profesora, la cual comenzó con una clase un poco mas amena y con mucha mas "logica de programacion" y no tanta "aplicacion", ya que al fin y al cabo el curso es para saber programar no para saber VB.NET nada mas.
Para no extenderme más comenzamos programando aplicaciones de consola (Si si, se han dejado de usar, pero para el aprendizaje es excelente) y tuvimos que hacer la tipica Calculadora. Ante la imposibilidad de hacer un "CLEAR" de pantalla "nativo" desde el Visual busqué y encontré la clase que pasaré a continuación para hacer un borrado de pantalla de la consola.

Clase: Clear.vb

Visual Basic:
  1. Imports System.Runtime.InteropServices
  2.  
  3. Public Class ClearConsole
  4.  
  5. Private Const STD_OUTPUT_HANDLE As Integer = &amp;HFFFFFFF5
  6. Private Const EMPTY As Byte = 32
  7.  
  8. ' Structure defines the coordinates of a character cell in a console screen buffer.
  9. ' The origin of the coordinate system (0,0) is at the top-left cell of the buffer.
  10. _
  11. Structure COORD
  12. Dim X As Short
  13. Dim Y As Short
  14. End Structure
  15.  
  16. ' Structure defines the coordinates of the upper-left and lower-right corners of a rectangle
  17. _
  18. Structure SMALL_RECT
  19. Dim Left As Short
  20. Dim Top As Short
  21. Dim Right As Short
  22. Dim Bottom As Short
  23. End Structure
  24.  
  25. ' Structure containing information about the Console's screen buffer.
  26. _
  27. Structure CONSOLE_SCREEN_BUFFER_INFO
  28. Dim dwSize As COORD
  29. Dim dwCursorPosition As COORD
  30. Dim wAttributes As Integer
  31. Dim srWindow As SMALL_RECT
  32. Dim dwMaximumWindowSize As COORD
  33. End Structure
  34.  
  35. ' Win32 API Function declarations.
  36. Declare Auto Function GetStdHandle Lib "kernel32.dll" (ByVal nStdHandle As Integer) As IntPtr
  37. Declare Auto Function FillConsoleOutputCharacter Lib "kernel32.dll" (ByVal hConsoleOutput As IntPtr, ByVal cCharacter As Byte, _
  38. ByVal nLength As Integer, _
  39. ByVal dwWriteCoord As COORD, _
  40. ByRef lpNumberOfCharsWritten As IntPtr) As Integer
  41. Declare Auto Function GetConsoleScreenBufferInfo Lib "kernel32.dll" (ByVal hConsoleOutput As IntPtr, _
  42. ByRef lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Integer
  43. Declare Auto Function SetConsoleCursorPosition Lib "kernel32.dll" (ByVal hConsoleOutput As IntPtr, ByVal dwCursorPosition As COORD) As Integer
  44.  
  45. ' Subroutine used to clear the Console screen.
  46. Public Sub Clear()
  47. Dim hConsoleHandle As IntPtr
  48. Dim hWrittenChars As IntPtr
  49. Dim strConsoleInfo As CONSOLE_SCREEN_BUFFER_INFO
  50. Dim strOriginalLocation As COORD
  51. hConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE) ' Get Handle for standard output
  52. GetConsoleScreenBufferInfo(hConsoleHandle, strConsoleInfo) ' Get information about the standard output buffer of the Console
  53. FillConsoleOutputCharacter(hConsoleHandle, EMPTY, strConsoleInfo.dwSize.X * strConsoleInfo.dwSize.Y, strOriginalLocation, hWrittenChars) ' Fill output buffer with Empty characters (ASCII 32)
  54. SetConsoleCursorPosition(hConsoleHandle, strOriginalLocation) ' Set the Console cursor back to the origin
  55. End Sub
  56.  
  57. End Class

Y Aqui les dejo una calculadora muy poco util pero que sirve de ejemplo :P.
Nombre: El_que_quieran.vb

Visual Basic:
  1. ' Inicio una Instancia de la Clase para limpiar la Consola
  2. Dim MyConsole As New ClearConsole()
  3. ' Declaramos dos variables que son los numeros para operar y la
  4. ' opcion que guardará la (Valga la redundancia) opcion del menu seleccionada
  5. Dim num_1, num_2 As Integer
  6. Dim opcion As Short
  7. Dim comando As String
  8.  
  9. Do
  10. MyConsole.Clear()
  11. Console.WriteLine("------------------------------")
  12. Console.WriteLine("Calculadora de Consola")
  13. Console.WriteLine("------------------------------")
  14. Console.WriteLine("1er Numero: ")
  15. num_1 = Console.Read()
  16. Console.WriteLine("2do Numero: ")
  17. num_2 = Console.Read()
  18. Console.WriteLine()
  19.  
  20. Do
  21. Console.WriteLine("1. Sumar")
  22. Console.WriteLine("2. Restar")
  23. Console.WriteLine("3. Multiplicar")
  24. Console.WriteLine("4. Dividir")
  25. Console.WriteLine("5. Resto de la Division")
  26.  
  27. opcion = Console.ReadLine()
  28. Loop While (opcion&gt; 5)
  29.  
  30. Select Case opcion
  31. Case 1
  32. Console.WriteLine("La Suma de " &amp; num_1 &amp; " + " &amp; num_2 &amp; " = " &amp; num_1 + num_2)
  33. Case 2
  34. Console.WriteLine("La Resta de " &amp; num_1 &amp; " - " &amp; num_2 &amp; " = " &amp; num_1 - num_2)
  35. Case 3
  36. Console.WriteLine("La Multiplicacion de " &amp; num_1 &amp; " x " &amp; num_2 &amp; " = " &amp; num_1 * num_2)
  37. Case 4
  38. Console.WriteLine("La Division de " &amp; num_1 &amp; " / " &amp; num_2 &amp; " = " &amp; num_1 / num_2)
  39. Case 5
  40. Console.WriteLine("El Modulo de " &amp; num_1 &amp; " / " &amp; num_2 &amp; " = " &amp; num_1 Mod num_2)
  41. End Select
  42.  
  43. Console.WriteLine()
  44. comando = Console.ReadLine()
  45. Loop While (comando &lt;&gt; "exit")

P.D: No está depurado, es un ejemplo MUY basico de el uso de la clase.

Via: Microsoft (La definición de la Clase)

(2) Comments    Read More