Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    ' Game state variables
    Private deck As New List(Of String)
    Private playerHand As New List(Of String)
    Private opponentHand As New List(Of String)
    Private discardPile As New List(Of String)
    Private currentSuit As String = ""
    Private currentPlayer As Integer = 0 ' 0 = player, 1 = opponent
    Private playerScore As Integer = 0
    Private opponentScore As Integer = 0
    Private gameStarted As Boolean = False

    ' Runtime controls
    Private WithEvents btnStartGame As Button
    Private WithEvents btnDrawCard As Button
    Private WithEvents btnPlayCard As Button
    Private WithEvents btnPass As Button
    Private lblPlayerScore As Label
    Private lblOpponentScore As Label
    Private lblCurrentTurn As Label
    Private lblDiscardPile As Label
    Private flowPlayerCards As FlowLayoutPanel
    Private flowOpponentCards As FlowLayoutPanel
    Private pnlGameBoard As Panel
    Private selectedCardIndex As Integer = -1

    Public Sub New()
        Me.Text = "Toepen - Dutch Card Game"
        Me.Size = New Size(1000, 700)
        Me.StartPosition = FormStartPosition.CenterScreen
        Me.BackColor = Color.DarkGreen

        InitializeControls()
        InitializeDeck()
    End Sub

    Private Sub InitializeControls()
        ' Title label
        Dim lblTitle As New Label With {
            .Text = "TOEPEN - Dutch Card Game",
            .Font = New Font("Arial", 16, FontStyle.Bold),
            .ForeColor = Color.White,
            .Size = New Size(400, 30),
            .Location = New Point(300, 10),
            .TextAlign = ContentAlignment.MiddleCenter
        }
        Me.Controls.Add(lblTitle)

        ' Game board panel
        pnlGameBoard = New Panel With {
            .BackColor = Color.ForestGreen,
            .Size = New Size(950, 600),
            .Location = New Point(25, 50),
            .BorderStyle = BorderStyle.FixedSingle
        }
        Me.Controls.Add(pnlGameBoard)

        ' Player score label
        lblPlayerScore = New Label With {
            .Text = "Player Score: 0",
            .Font = New Font("Arial", 12, FontStyle.Bold),
            .ForeColor = Color.White,
            .Size = New Size(150, 25),
            .Location = New Point(50, 20)
        }
        pnlGameBoard.Controls.Add(lblPlayerScore)

        ' Opponent score label
        lblOpponentScore = New Label With {
            .Text = "Opponent Score: 0",
            .Font = New Font("Arial", 12, FontStyle.Bold),
            .ForeColor = Color.White,
            .Size = New Size(150, 25),
            .Location = New Point(750, 20)
        }
        pnlGameBoard.Controls.Add(lblOpponentScore)

        ' Current turn label
        lblCurrentTurn = New Label With {
            .Text = "Current Turn: -",
            .Font = New Font("Arial", 12, FontStyle.Bold),
            .ForeColor = Color.Yellow,
            .Size = New Size(200, 25),
            .Location = New Point(375, 20)
        }
        pnlGameBoard.Controls.Add(lblCurrentTurn)

        ' Discard pile label
        lblDiscardPile = New Label With {
            .Text = "Discard Pile: Empty",
            .Font = New Font("Arial", 10),
            .ForeColor = Color.White,
            .Size = New Size(200, 25),
            .Location = New Point(400, 250)
        }
        pnlGameBoard.Controls.Add(lblDiscardPile)

        ' Opponent cards area
        Dim lblOpponentCards As New Label With {
            .Text = "Opponent's Cards",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .ForeColor = Color.White,
            .Size = New Size(150, 25),
            .Location = New Point(400, 50)
        }
        pnlGameBoard.Controls.Add(lblOpponentCards)

        flowOpponentCards = New FlowLayoutPanel With {
            .Size = New Size(400, 80),
            .Location = New Point(275, 80),
            .BackColor = Color.Transparent
        }
        pnlGameBoard.Controls.Add(flowOpponentCards)

        ' Player cards area
        Dim lblPlayerCards As New Label With {
            .Text = "Your Cards",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .ForeColor = Color.White,
            .Size = New Size(150, 25),
            .Location = New Point(400, 400)
        }
        pnlGameBoard.Controls.Add(lblPlayerCards)

        flowPlayerCards = New FlowLayoutPanel With {
            .Size = New Size(400, 120),
            .Location = New Point(275, 430),
            .BackColor = Color.Transparent
        }
        pnlGameBoard.Controls.Add(flowPlayerCards)

        ' Start Game button
        btnStartGame = New Button With {
            .Text = "Start New Game",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .Size = New Size(150, 40),
            .Location = New Point(425, 300),
            .BackColor = Color.DarkOrange,
            .ForeColor = Color.White
        }
        pnlGameBoard.Controls.Add(btnStartGame)

        ' Draw Card button
        btnDrawCard = New Button With {
            .Text = "Draw Card",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .Size = New Size(120, 40),
            .Location = New Point(200, 350),
            .BackColor = Color.DodgerBlue,
            .ForeColor = Color.White,
            .Enabled = False
        }
        pnlGameBoard.Controls.Add(btnDrawCard)

        ' Play Card button
        btnPlayCard = New Button With {
            .Text = "Play Card",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .Size = New Size(120, 40),
            .Location = New Point(350, 350),
            .BackColor = Color.LimeGreen,
            .ForeColor = Color.White,
            .Enabled = False
        }
        pnlGameBoard.Controls.Add(btnPlayCard)

        ' Pass button
        btnPass = New Button With {
            .Text = "Pass",
            .Font = New Font("Arial", 10, FontStyle.Bold),
            .Size = New Size(120, 40),
            .Location = New Point(500, 350),
            .BackColor = Color.Crimson,
            .ForeColor = Color.White,
            .Enabled = False
        }
        pnlGameBoard.Controls.Add(btnPass)
    End Sub

    Private Sub InitializeDeck()
        ' Standard Toepen deck: 7 through Ace (32 cards)
        Dim suits() As String = {"♠", "♥", "♦", "♣"}
        Dim values() As String = {"7", "8", "9", "10", "J", "Q", "K", "A"}

        deck.Clear()
        For Each suit In suits
            For Each value In values
                deck.Add(value & suit)
            Next
        Next

        ' Shuffle the deck
        ShuffleDeck()
    End Sub

    Private Sub ShuffleDeck()
        Dim rnd As New Random()
        deck = deck.OrderBy(Function(x) rnd.Next()).ToList()
    End Sub

    Private Sub DealCards()
        playerHand.Clear()
        opponentHand.Clear()
        discardPile.Clear()
        currentSuit = ""
        selectedCardIndex = -1

        ' Deal 4 cards to each player
        For i As Integer = 1 To 4
            playerHand.Add(deck(0))
            deck.RemoveAt(0)
            opponentHand.Add(deck(0))
            deck.RemoveAt(0)
        Next

        UpdateCardDisplays()
    End Sub

    Private Sub UpdateCardDisplays()
        ' Clear card displays
        flowPlayerCards.Controls.Clear()
        flowOpponentCards.Controls.Clear()

        ' Display opponent's cards (face down)
        For i As Integer = 0 To opponentHand.Count - 1
            Dim cardPanel As New Panel With {
                .Size = New Size(60, 90),
                .BackColor = Color.DarkBlue,
                .BorderStyle = BorderStyle.FixedSingle,
                .Tag = i
            }

            ' Add card back design
            Dim cardBack As New Label With {
                .Text = "?",
                .Font = New Font("Arial", 24, FontStyle.Bold),
                .ForeColor = Color.White,
                .Size = New Size(60, 90),
                .TextAlign = ContentAlignment.MiddleCenter
            }
            cardPanel.Controls.Add(cardBack)

            flowOpponentCards.Controls.Add(cardPanel)
        Next

        ' Display player's cards
        For i As Integer = 0 To playerHand.Count - 1
            Dim card As String = playerHand(i)
            Dim cardPanel As New Panel With {
                .Size = New Size(60, 90),
                .BackColor = Color.White,
                .BorderStyle = BorderStyle.FixedSingle,
                .Tag = i
            }

            ' Determine card color
            Dim cardColor As Color
            If card.EndsWith("♥") OrElse card.EndsWith("♦") Then
                cardColor = Color.Red
            Else
                cardColor = Color.Black
            End If

            ' Add card value and suit
            Dim cardLabel As New Label With {
                .Text = card,
                .Font = New Font("Arial", 14, FontStyle.Bold),
                .ForeColor = cardColor,
                .Size = New Size(60, 90),
                .TextAlign = ContentAlignment.MiddleCenter,
                .Tag = i
            }
            AddHandler cardLabel.Click, AddressOf CardLabel_Click

            cardPanel.Controls.Add(cardLabel)
            flowPlayerCards.Controls.Add(cardPanel)
        Next

        ' Update discard pile display
        If discardPile.Count > 0 Then
            lblDiscardPile.Text = "Discard Pile: " & discardPile.Last()
        Else
            lblDiscardPile.Text = "Discard Pile: Empty"
        End If

        ' Update scores
        lblPlayerScore.Text = "Player Score: " & playerScore
        lblOpponentScore.Text = "Opponent Score: " & opponentScore

        ' Update turn indicator
        If gameStarted Then
            lblCurrentTurn.Text = "Current Turn: " & If(currentPlayer = 0, "Player", "Opponent")
        End If
    End Sub

    Private Sub CardLabel_Click(sender As Object, e As EventArgs)
        Dim label As Label = DirectCast(sender, Label)
        selectedCardIndex = CInt(label.Tag)

        ' Highlight selected card
        For Each panel As Panel In flowPlayerCards.Controls
            panel.BackColor = Color.White
        Next

        If selectedCardIndex >= 0 AndAlso selectedCardIndex < flowPlayerCards.Controls.Count Then
            flowPlayerCards.Controls(selectedCardIndex).BackColor = Color.LightBlue
        End If

        btnPlayCard.Enabled = True
    End Sub

    Private Sub PlayCard(cardIndex As Integer)
        If cardIndex < 0 OrElse cardIndex >= playerHand.Count Then Return

        Dim card As String = playerHand(cardIndex)

        ' Check if card can be played
        If discardPile.Count > 0 Then
            Dim topCard As String = discardPile.Last()
            Dim topValue As String = topCard.Substring(0, topCard.Length - 1)
            Dim topSuit As String = topCard.Last()
            Dim cardValue As String = card.Substring(0, card.Length - 1)
            Dim cardSuit As String = card.Last()

            ' In Toepen, you must follow suit if you can
            If currentSuit <> "" AndAlso cardSuit <> currentSuit Then
                ' Check if player has any cards of the current suit
                Dim hasSuit As Boolean = False
                For Each c In playerHand
                    If c.Last() = currentSuit Then
                        hasSuit = True
                        Exit For
                    End If
                Next

                If hasSuit Then
                    MessageBox.Show("You must follow suit!", "Invalid Move", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    Return
                End If
            End If
        End If

        ' Play the card
        playerHand.RemoveAt(cardIndex)
        discardPile.Add(card)
        currentSuit = card.Last()

        ' Check if player won the round
        If playerHand.Count = 0 Then
            MessageBox.Show("You won the round!", "Round Over", MessageBoxButtons.OK, MessageBoxIcon.Information)
            opponentScore += 1
            StartNewRound()
            Return
        End If

        ' Switch to opponent's turn
        currentPlayer = 1
        UpdateCardDisplays()
        btnPlayCard.Enabled = False
        selectedCardIndex = -1

        ' Opponent's turn (simple AI)
        OpponentTurn()
    End Sub

    Private Sub OpponentTurn()
        ' Simple AI for opponent
        Dim playableCards As New List(Of Integer)

        ' Find playable cards
        For i As Integer = 0 To opponentHand.Count - 1
            Dim card As String = opponentHand(i)
            Dim cardSuit As String = card.Last()

            If currentSuit = "" OrElse cardSuit = currentSuit Then
                playableCards.Add(i)
            End If
        Next

        ' If no cards match suit, any card can be played
        If playableCards.Count = 0 Then
            For i As Integer = 0 To opponentHand.Count - 1
                playableCards.Add(i)
            Next
        End If

        ' Randomly select a card to play
        If playableCards.Count > 0 Then
            Dim rnd As New Random()
            Dim cardIndex As Integer = playableCards(rnd.Next(playableCards.Count))
            Dim card As String = opponentHand(cardIndex)

            opponentHand.RemoveAt(cardIndex)
            discardPile.Add(card)
            currentSuit = card.Last()

            ' Check if opponent won the round
            If opponentHand.Count = 0 Then
                MessageBox.Show("Opponent won the round!", "Round Over", MessageBoxButtons.OK, MessageBoxIcon.Information)
                playerScore += 1
                StartNewRound()
                Return
            End If
        End If

        ' Switch back to player's turn
        currentPlayer = 0
        UpdateCardDisplays()
        btnDrawCard.Enabled = True
        btnPass.Enabled = True
    End Sub

    Private Sub StartNewRound()
        If playerScore >= 5 Or opponentScore >= 5 Then
            Dim winner As String = If(playerScore >= 5, "Player", "Opponent")
            MessageBox.Show(winner & " wins the game!", "Game Over", MessageBoxButtons.OK, MessageBoxIcon.Information)
            gameStarted = False
            btnStartGame.Enabled = True
            btnDrawCard.Enabled = False
            btnPlayCard.Enabled = False
            btnPass.Enabled = False
        Else
            InitializeDeck()
            DealCards()
            currentPlayer = 0
            UpdateCardDisplays()
            btnDrawCard.Enabled = True
            btnPass.Enabled = True
        End If
    End Sub

    ' Event Handlers
    Private Sub btnStartGame_Click(sender As Object, e As EventArgs) Handles btnStartGame.Click
        gameStarted = True
        playerScore = 0
        opponentScore = 0
        InitializeDeck()
        DealCards()
        currentPlayer = 0

        btnStartGame.Enabled = False
        btnDrawCard.Enabled = True
        btnPass.Enabled = True
        lblCurrentTurn.Text = "Current Turn: Player"
    End Sub

    Private Sub btnDrawCard_Click(sender As Object, e As EventArgs) Handles btnDrawCard.Click
        If deck.Count > 0 AndAlso playerHand.Count < 8 Then
            playerHand.Add(deck(0))
            deck.RemoveAt(0)
            UpdateCardDisplays()
            btnDrawCard.Enabled = False
            btnPass.Enabled = False
            OpponentTurn()
        Else
            MessageBox.Show("Cannot draw more cards!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End If
    End Sub

    Private Sub btnPlayCard_Click(sender As Object, e As EventArgs) Handles btnPlayCard.Click
        If selectedCardIndex >= 0 Then
            PlayCard(selectedCardIndex)
        End If
    End Sub

    Private Sub btnPass_Click(sender As Object, e As EventArgs) Handles btnPass.Click
        If MessageBox.Show("Are you sure you want to pass?", "Pass Turn",
                          MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            btnDrawCard.Enabled = False
            btnPass.Enabled = False
            btnPlayCard.Enabled = False
            OpponentTurn()
        End If
    End Sub
End Class

' Main Program Module
Module Program
    Sub Main()
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New Form1())
    End Sub
End Module

