Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    ' Game constants
    Private Const GRID_SIZE As Integer = 20
    Private Const CELL_SIZE As Integer = 40
    Private ReadOnly ALPHABET As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    ' Game variables
    Private snake As New List(Of Point)
    Private direction As Point = New Point(1, 0)
    Private nextDirection As Point = New Point(1, 0)
    Private targetLetterIndex As Integer = 0
    Private targetLetter As Char = "A"
    Private gameSpeed As Integer = 152
    Private score As Integer = 0
    Private isGameOver As Boolean = False
    Private isPaused As Boolean = False

    ' Runtime controls
    Private WithEvents gameTimer As New Timer()
    Private scoreLabel As Label
    Private targetLabel As Label
    Private gameOverPanel As Panel
    Private restartButton As Button
    Private pauseButton As Button

    Public Sub New()
        InitializeForm()
        InitializeRuntimeControls()
        InitializeGame()
    End Sub

    Private Sub InitializeForm()
        Me.Text = "ABC Snake Game"
        Me.Size = New Size(800, 600)
        Me.BackColor = Color.Black
        Me.DoubleBuffered = True
        Me.KeyPreview = True
        Me.FormBorderStyle = FormBorderStyle.FixedSingle
        Me.MaximizeBox = False
    End Sub

    Private Sub InitializeRuntimeControls()
        ' Score label
        scoreLabel = New Label()
        With scoreLabel
            .Text = "Score: 0"
            .Font = New Font("Arial", 14, FontStyle.Bold)
            .ForeColor = Color.Lime
            .BackColor = Color.Transparent
            .AutoSize = True
            .Location = New Point(10, 10)
        End With
        Me.Controls.Add(scoreLabel)

        ' Target letter label
        targetLabel = New Label()
        With targetLabel
            .Text = "Target: A"
            .Font = New Font("Arial", 14, FontStyle.Bold)
            .ForeColor = Color.Cyan
            .BackColor = Color.Transparent
            .AutoSize = True
            .Location = New Point(10, 40)
        End With
        Me.Controls.Add(targetLabel)

        ' Pause button
        pauseButton = New Button()
        With pauseButton
            .Text = "Pause"
            .Font = New Font("Arial", 10)
            .Size = New Size(80, 30)
            .Location = New Point(Me.ClientSize.Width - 90, 10)
            .BackColor = Color.DarkBlue
            .ForeColor = Color.White
        End With
        AddHandler pauseButton.Click, AddressOf PauseButton_Click
        Me.Controls.Add(pauseButton)

        ' Game over panel (initially hidden)
        gameOverPanel = New Panel()
        With gameOverPanel
            .Size = New Size(300, 150)
            .BackColor = Color.FromArgb(200, 0, 0, 0)
            .Visible = False
            .Location = New Point((Me.ClientSize.Width - 300) \ 2, (Me.ClientSize.Height - 150) \ 2)
        End With

        ' Game over label
        Dim gameOverLabel As New Label()
        With gameOverLabel
            .Text = "GAME OVER"
            .Font = New Font("Arial", 24, FontStyle.Bold)
            .ForeColor = Color.Red
            .AutoSize = True
            .Location = New Point(50, 20)
        End With
        gameOverPanel.Controls.Add(gameOverLabel)

        ' Final score label
        Dim finalScoreLabel As New Label()
        With finalScoreLabel
            .Name = "finalScoreLabel"
            .Text = "Final Score: 0"
            .Font = New Font("Arial", 14)
            .ForeColor = Color.Yellow
            .AutoSize = True
            .Location = New Point(50, 70)
        End With
        gameOverPanel.Controls.Add(finalScoreLabel)

        ' Restart button
        restartButton = New Button()
        With restartButton
            .Text = "Restart Game"
            .Font = New Font("Arial", 10)
            .Size = New Size(120, 35)
            .Location = New Point(90, 110)
            .BackColor = Color.Green
            .ForeColor = Color.White
        End With
        AddHandler restartButton.Click, AddressOf RestartButton_Click
        gameOverPanel.Controls.Add(restartButton)

        Me.Controls.Add(gameOverPanel)

        ' Game timer
        With gameTimer
            .Interval = gameSpeed
        End With
        AddHandler gameTimer.Tick, AddressOf GameTimer_Tick
    End Sub

    Private Sub InitializeGame()
        ' Initialize snake with 3 segments
        snake.Clear()
        snake.Add(New Point(5, 10)) ' Head
        snake.Add(New Point(4, 10))
        snake.Add(New Point(3, 10))

        ' Reset game state
        direction = New Point(1, 0)
        nextDirection = New Point(1, 0)
        targetLetterIndex = 0
        targetLetter = ALPHABET(targetLetterIndex)
        score = 0
        isGameOver = False
        isPaused = False

        ' Update labels
        scoreLabel.Text = "Score: 0"
        targetLabel.Text = "Target: " & targetLetter

        ' Start timer
        gameTimer.Start()

        ' Generate first target letter
        GenerateTargetLetter()
    End Sub

    Private Sub GenerateTargetLetter()
        ' Generate random position for target letter
        Dim rand As New Random()
        Dim targetPos As Point

        Do
            targetPos = New Point(rand.Next(0, GRID_SIZE), rand.Next(0, GRID_SIZE))
        Loop While snake.Contains(targetPos)

        ' Store target position in Tag property
        Me.Tag = targetPos

        Me.Invalidate()
    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        If isGameOver Then Return

        Dim g As Graphics = e.Graphics

        ' Calculate drawing area
        Dim gridWidth As Integer = Me.ClientSize.Width - 20
        Dim gridHeight As Integer = Me.ClientSize.Height - 80
        Dim cellSize As Integer = Math.Min(gridWidth \ GRID_SIZE, gridHeight \ GRID_SIZE)
        Dim offsetX As Integer = (Me.ClientSize.Width - (GRID_SIZE * cellSize)) \ 2
        Dim offsetY As Integer = 70

        ' Draw grid
        For x As Integer = 0 To GRID_SIZE
            g.DrawLine(Pens.DarkGray, offsetX + x * cellSize, offsetY, offsetX + x * cellSize, offsetY + GRID_SIZE * cellSize)
        Next

        For y As Integer = 0 To GRID_SIZE
            g.DrawLine(Pens.DarkGray, offsetX, offsetY + y * cellSize, offsetX + GRID_SIZE * cellSize, offsetY + y * cellSize)
        Next

        ' Draw snake
        For i As Integer = 0 To snake.Count - 1
            Dim segment As Point = snake(i)
            Dim color As Color

            If i = 0 Then
                ' Head - green
                color = Color.Lime
            Else
                ' Body - dark green
                color = Color.Green
            End If

            Using brush As New SolidBrush(color)
                g.FillRectangle(brush, offsetX + segment.X * cellSize + 1, offsetY + segment.Y * cellSize + 1, cellSize - 2, cellSize - 2)
            End Using

            ' Draw eyes on head
            If i = 0 Then
                Using brush As New SolidBrush(Color.Black)
                    g.FillEllipse(brush, offsetX + segment.X * cellSize + cellSize \ 3, offsetY + segment.Y * cellSize + cellSize \ 4, cellSize \ 6, cellSize \ 6)
                    g.FillEllipse(brush, offsetX + segment.X * cellSize + cellSize \ 2, offsetY + segment.Y * cellSize + cellSize \ 4, cellSize \ 6, cellSize \ 6)
                End Using
            End If
        Next

        ' Draw target letter
        If Me.Tag IsNot Nothing Then
            Dim targetPos As Point = CType(Me.Tag, Point)

            ' Draw letter background
            Using brush As New SolidBrush(Color.Red)
                g.FillRectangle(brush, offsetX + targetPos.X * cellSize + 1, offsetY + targetPos.Y * cellSize + 1, cellSize - 2, cellSize - 2)
            End Using

            ' Draw the letter
            Using font As New Font("Arial", cellSize \ 2, FontStyle.Bold)
                Using brush As New SolidBrush(Color.White)
                    Dim format As New StringFormat()
                    format.Alignment = StringAlignment.Center
                    format.LineAlignment = StringAlignment.Center

                    g.DrawString(targetLetter.ToString(), font, brush,
                                New RectangleF(offsetX + targetPos.X * cellSize, offsetY + targetPos.Y * cellSize, cellSize, cellSize), format)
                End Using
            End Using
        End If

        ' Draw game border
        Using pen As New Pen(Color.White, 2)
            g.DrawRectangle(pen, offsetX, offsetY, GRID_SIZE * cellSize, GRID_SIZE * cellSize)
        End Using
    End Sub

    Private Sub GameTimer_Tick(sender As Object, e As EventArgs)
        If isPaused OrElse isGameOver Then Return

        ' Update direction
        direction = nextDirection

        ' Calculate new head position
        Dim newHead As New Point(snake(0).X + direction.X, snake(0).Y + direction.Y)

        ' Check wall collision
        If newHead.X < 0 OrElse newHead.X >= GRID_SIZE OrElse newHead.Y < 0 OrElse newHead.Y >= GRID_SIZE Then
            GameOver()
            Return
        End If

        ' Check self collision
        If snake.Contains(newHead) Then
            GameOver()
            Return
        End If

        ' Add new head
        snake.Insert(0, newHead)

        ' Check if target letter collected
        If Me.Tag IsNot Nothing Then
            Dim targetPos As Point = CType(Me.Tag, Point)

            If newHead.Equals(targetPos) Then
                ' Check if correct letter
                If targetLetter = ALPHABET(targetLetterIndex) Then
                    ' Correct letter - increase score
                    score += 10
                    scoreLabel.Text = "Score: " & score

                    ' Move to next letter
                    targetLetterIndex += 1

                    If targetLetterIndex >= ALPHABET.Length Then
                        ' Completed alphabet - extra points and reset
                        score += 50
                        scoreLabel.Text = "Score: " & score
                        targetLetterIndex = 0
                    End If

                    targetLetter = ALPHABET(targetLetterIndex)
                    targetLabel.Text = "Target: " & targetLetter

                    ' Generate new target
                    GenerateTargetLetter()

                    ' Speed up game slightly
                    If gameTimer.Interval > 50 Then
                        gameTimer.Interval -= 5
                    End If
                Else
                    ' Wrong letter - game over
                    GameOver()
                    Return
                End If
            Else
                ' Remove tail if no target collected
                snake.RemoveAt(snake.Count - 1)
            End If
        End If

        Me.Invalidate()
    End Sub

    Private Sub GameOver()
        isGameOver = True
        gameTimer.Stop()

        ' Update final score
        Dim finalScoreLabel As Label = CType(gameOverPanel.Controls("finalScoreLabel"), Label)
        finalScoreLabel.Text = "Final Score: " & score

        ' Show game over panel
        gameOverPanel.Visible = True
        gameOverPanel.BringToFront()
    End Sub

    Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
        MyBase.OnKeyDown(e)

        If isGameOver Then Return

        Select Case e.KeyCode
            Case Keys.Up
                If direction.Y <> 1 Then nextDirection = New Point(0, -1)
            Case Keys.Down
                If direction.Y <> -1 Then nextDirection = New Point(0, 1)
            Case Keys.Left
                If direction.X <> 1 Then nextDirection = New Point(-1, 0)
            Case Keys.Right
                If direction.X <> -1 Then nextDirection = New Point(1, 0)
            Case Keys.Space
                TogglePause()
            Case Keys.R
                If e.Control Then RestartGame()
        End Select
    End Sub

    Private Sub TogglePause()
        isPaused = Not isPaused

        If isPaused Then
            gameTimer.Stop()
            pauseButton.Text = "Resume"
            Me.Text = "ABC Snake Game - PAUSED"
        Else
            gameTimer.Start()
            pauseButton.Text = "Pause"
            Me.Text = "ABC Snake Game"
        End If

        Me.Invalidate()
    End Sub

    Private Sub PauseButton_Click(sender As Object, e As EventArgs)
        TogglePause()
    End Sub

    Private Sub RestartButton_Click(sender As Object, e As EventArgs)
        RestartGame()
    End Sub

    Private Sub RestartGame()
        gameOverPanel.Visible = False
        InitializeGame()
        Me.Invalidate()
    End Sub

    Protected Overrides Sub OnResize(e As EventArgs)
        MyBase.OnResize(e)

        ' Center game over panel
        If gameOverPanel IsNot Nothing Then
            gameOverPanel.Location = New Point((Me.ClientSize.Width - gameOverPanel.Width) \ 2,
                                             (Me.ClientSize.Height - gameOverPanel.Height) \ 2)
        End If

        ' Reposition pause button
        If pauseButton IsNot Nothing Then
            pauseButton.Location = New Point(Me.ClientSize.Width - pauseButton.Width - 10, 10)
        End If

        Me.Invalidate()
    End Sub

    Protected Overrides Sub OnFormClosing(e As FormClosingEventArgs)
        gameTimer.Stop()
        MyBase.OnFormClosing(e)
    End Sub

    <STAThread>
    Sub Main()
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New Form1())
    End Sub
End Class
