Results 1 to 16 of 16

Thread: [RESOLVED] Help for a noob

Threaded View

  1. #14
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Help for a noob

    We'll need a form, a picturebox, called picDisp and a button called btnStart (see pic):


    First of all we'll need a game field and its contents:

    Code:
    Public Enum SquareContents
            Empty = 0
            Food = 1
            Obstacle = 2
            Body = 3
    End Enum
    
    Public Const FIELD_WIDTH As Integer = 30
    Public Const FIELD_HEIGHT As Integer = 30
    Public Shared GameField(0 To FIELD_WIDTH - 1, 0 To FIELD_HEIGHT - 1) As SquareContents
    
    Public Enum Directions
            Left
            Right
            Up
            Down
    End Enum
    Now, let's create our snake:

    vb.net Code:
    1. Public Class Snake
    2.         ' His body is simply a queue of points
    3.         ' A queue works by the FIFO principle - First In - First Out
    4.         Public BodyCells As New Queue(Of Point)
    5.        
    6.         ' The direction of his movement
    7.         Public Direction As Directions
    8.  
    9.         ' The location of his head
    10.         Public HeadLocation As Point
    11.  
    12.         ' We'll need two events
    13.         Public Event PainfulDeath() ' Game over
    14.         Public Event YumYum() ' Snake eats
    15.  
    16. Public Sub New()
    17.             HeadLocation = New Point(FIELD_WIDTH \ 2, FIELD_HEIGHT \ 2) ' We place him in the center
    18.             BodyCells.Enqueue(HeadLocation) ' We add his only cell to his body
    19.             Direction = Directions.Right  ' ... and make him look to the right
    20. End Sub
    21.  
    22. ' Now, what will our snake do with each heatbeat?
    23.    Public Sub Tick()
    24.             Dim NextCell As Point = HeadLocation  ' Where is the next cell
    25.             Select Case Direction
    26.                 Case Directions.Up
    27.                     NextCell.Y -= 1  
    28.                     If NextCell.Y < 0 Then
    29.                         RaiseEvent PainfulDeath()  ' ... kill the poor beast.
    30.                         Exit Sub
    31.                     End If
    32.                 Case Directions.Down
    33.                     NextCell.Y += 1
    34.                     If NextCell.Y = FIELD_HEIGHT Then
    35.                         RaiseEvent PainfulDeath()
    36.                         Exit Sub
    37.                     End If
    38.                 Case Directions.Left
    39.                     NextCell.X -= 1
    40.                     If NextCell.X < 0 Then
    41.                         RaiseEvent PainfulDeath()
    42.                         Exit Sub
    43.                     End If
    44.                 Case Directions.Right
    45.                     NextCell.X += 1
    46.                     If NextCell.X = FIELD_WIDTH Then
    47.                         RaiseEvent PainfulDeath()
    48.                         Exit Sub
    49.                     End If
    50.             End Select
    51.  
    52.             ' What do we have in this cell
    53.             Select Case GameField(NextCell.X, NextCell.Y)            
    54.                 Case SquareContents.Body, SquareContents.Obstacle  ' bumped into an obstacle
    55.                     RaiseEvent PainfulDeath()                                  
    56.                     Exit Sub
    57.                 Case SquareContents.Food  '  some food here
    58.                     BodyCells.Enqueue(NextCell) '  add another cell to body
    59.                     HeadLocation = NextCell  
    60.                     GameField(NextCell.X, NextCell.Y) = SquareContents.Body  ' Delete eaten food
    61.                     RaiseEvent YumYum()     ' Gimme more food
    62.  
    63.                 Case SquareContents.Empty  
    64.                     BodyCells.Enqueue(NextCell) ' The tricky part - we add a body cell here..
    65.                     HeadLocation = NextCell        
    66.                     Dim Tail As Point = BodyCells.Dequeue()  '  ... and cut off his tail
    67.                     GameField(Tail.X, Tail.Y) = SquareContents.Empty  
    68.                     GameField(NextCell.X, NextCell.Y) = SquareContents.Body
    69.             End Select
    70.         End Sub
    71. End Class


    Something that would drive our game - a timer and some other helpers at the class level:

    vb.net Code:
    1. Public TICKS_FOR_FOOD As Integer  
    2.                                                            
    3. Public Bob As Snake ' Here's our Bob
    4. Public CellSize As Size ' This is a size in pixels of one field cell (we'll determine it later)
    5. Public tmr As Timer ' Main timer
    6. Public FoodAt As Point ' Where the food is
    7. Public KeepFood As Integer = 0 ' Ticks remaining before the food is spoiled
    8.  
    9. ' Colors:
    10. Public pGrass As Color
    11. Public pFood As Color
    12. Public pBody As Color
    13. Public pObstacle As Color
    14.  
    15. Public GameOver As Boolean = False

    A few preparations:

    vb.net Code:
    1. Private Sub frmSnake_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    2.         Me.KeyPreview = True
    3.         tmr = New Timer
    4.         tmr.Interval = 100 ' Setting timer interval (this value actually controls the speed of the game)
    5. ' the less it is the faster the game
    6.         tmr.Enabled = False
    7.  
    8. ' Colors:
    9.         pGrass = Color.DarkGreen
    10.         pFood = Color.Red
    11.         pBody = Color.Yellow
    12.         pObstacle = Color.White
    13.  
    14.         AddHandler tmr.Tick, AddressOf tmr_Tick   ' Making timer work
    15. End Sub
    16.  
    17. ' Update the size of the game field cell in pixels:
    18. Private Sub frmSnake_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
    19.         CellSize.Width = CInt(picDisp.Width / FIELD_WIDTH)        
    20.         CellSize.Height = CInt(picDisp.Height / FIELD_HEIGHT)
    21. End Sub

    Clicking the start button:

    vb.net Code:
    1. Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
    2.         Bob = New Snake
    3.         ReDim GameField(0 To FIELD_WIDTH - 1, 0 To FIELD_HEIGHT - 1) ' Clear the game field
    4.         AddHandler Bob.PainfulDeath, AddressOf EndGame ' Show 'Game Over' if snake dies
    5.         AddHandler Bob.YumYum, AddressOf PlaceNewFood ' For placing food
    6.  
    7.         tmr.Enabled = True
    8.         btnStart.Enabled = False
    9.         GameOver = False
    10. End Sub
    11.  
    12. ' Tell Bob where to go:
    13. Private Sub frmSnake_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    14.         Select Case e.KeyCode
    15.             Case Keys.Left
    16.                 If Bob.Direction = Directions.Right Then Exit Sub
    17.                 Bob.Direction = Directions.Left
    18.             Case Keys.Right
    19.                 If Bob.Direction = Directions.Left Then Exit Sub
    20.                 Bob.Direction = Directions.Right
    21.             Case Keys.Up
    22.                 If Bob.Direction = Directions.Down Then Exit Sub
    23.                 Bob.Direction = Directions.Up
    24.             Case Keys.Down
    25.                 If Bob.Direction = Directions.Up Then Exit Sub
    26.                 Bob.Direction = Directions.Down
    27.         End Select
    28. End Sub
    29.  
    30. ' Bob dies:
    31. Public Sub EndGame()
    32.         GameOver = True
    33.         tmr.Stop()
    34.         btnStart.Enabled = True
    35.         picDisp.Invalidate()
    36. End Sub
    37.  
    38. ' Game tick:
    39. Public Sub tmr_Tick(ByVal sender As Object, ByVal e As EventArgs)
    40.  
    41.         If KeepFood = 0 Then
    42.               PlaceNewFood(EmptyCell:=True) ' We need to remove the old food and place a new one
    43.               Dim rng As New Random
    44.               TICKS_FOR_FOOD = rng.Next(10, 40)
    45.         End If
    46.  
    47.         KeepFood += 1  
    48.         If KeepFood > TICKS_FOR_FOOD Then KeepFood = 0   ' Food is spolied if KeepFood = 0
    49.         Bob.Tick()  ' Kick Bob to move
    50.         picDisp.Invalidate()  ' Redraw screen
    51. End Sub

    Providing food is an important business:

    vb.net Code:
    1. Public Sub PlaceNewFood(Optional ByVal EmptyCell As Boolean = False)
    2.         Dim rng As New Random
    3.         Dim fx, fy As Integer
    4.  
    5.         Do    
    6.             fx = rng.Next(0, FIELD_WIDTH)
    7.             fy = rng.Next(0, FIELD_HEIGHT)
    8.         Loop While GameField(fx, fy) <> SquareContents.Empty
    9.  
    10.         If EmptyCell Then   ' If we need to remove the old food we do that:
    11.             GameField(FoodAt.X, FoodAt.Y) = SquareContents.Empty
    12.         End If
    13.  
    14.         GameField(fx, fy) = SquareContents.Food       '  New food is placed
    15.         FoodAt.X = fx   ' We should remember where it is to remove it later
    16.         FoodAt.Y = fy
    17.     End Sub
    18.  
    19. ' Drawing the game screen:
    20. Private Sub DrawGameField(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles picDisp.Paint
    21.        
    22.         If GameOver Then
    23.             Dim fnt As New Font(Me.Font.FontFamily, 42, FontStyle.Bold, GraphicsUnit.Pixel)
    24.             Dim txt As String = "GAME OVER"
    25.             Dim TextSize As SizeF = e.Graphics.MeasureString(txt, fnt, New SizeF(picDisp.Width, fnt.Height))
    26.             e.Graphics.DrawString(txt, fnt, Brushes.Red, _
    27.                                   CSng(picDisp.Width / 2 - TextSize.Width / 2), _
    28.                                   CSng(picDisp.Height / 2 - TextSize.Height / 2))
    29.             Exit Sub
    30.         End If
    31.  
    32.         Dim x, y As Integer
    33.  
    34.         ' Draw each game square them:
    35.         For y = 0 To FIELD_HEIGHT - 1
    36.             For x = 0 To FIELD_WIDTH - 1
    37.                 Dim cellRect As New Rectangle(x * CellSize.Width, y * CellSize.Height, CellSize.Width, CellSize.Height)
    38.  
    39.                 Select Case GameField(x, y)
    40.                     Case SquareContents.Empty
    41.                         e.Graphics.FillRectangle(New SolidBrush(pGrass), cellRect)
    42.                     Case SquareContents.Body
    43.                         e.Graphics.FillRectangle(New SolidBrush(pGrass), cellRect)
    44.                         e.Graphics.FillEllipse(New SolidBrush(pBody), cellRect)
    45.                     Case SquareContents.Food
    46.                         e.Graphics.FillRectangle(New SolidBrush(pGrass), cellRect)
    47.                         e.Graphics.FillEllipse(New SolidBrush(pFood), cellRect)
    48.                     Case SquareContents.Obstacle
    49.                         e.Graphics.FillRectangle(New SolidBrush(pObstacle), cellRect)
    50.                 End Select
    51.             Next
    52.         Next
    53.     End Sub

    That's all. Complete source code is attached.
    Attached Files Attached Files

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width