How do I shuffle and deal cards one at a time to players?

后端 未结 2 1393
忘掉有多难
忘掉有多难 2020-11-27 08:27

This is what I got so far and find myself stuck.=/

Private Sub Dealbtn_Click(sender As Object, e As EventArgs) Handles Dealbtn.Click  
     Dim Suits() As S         


        
2条回答
  •  甜味超标
    2020-11-27 09:00

    You need to generate the whole deck upfront (52 cards), store it in a List/Stack/Queue, and when required, deal one to the player.

    A double loop should be good enough to generate cards sequentially, then sort by random number:

    Dim Suits() As String = {"S", "D", "C", "H"}
    Dim Faces() As String = {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}
    
    Dim cards As New List(Of String)
    For Each s As String In Suits
      For Each f As String In Faces
        cards.Add(s & f)
      Next
    Next
    
    Dim r As New Random
    Dim cardsShuffled = cards.OrderBy(Function() r.Next)
    

    EDIT: Here is how you can populate your labels (just one way of doing it):

    Dim deck As New Stack(Of String)(cardsShuffled)
    For Each lbl As Label in {Label1, Label2, Label3, ...} 'you need to write all
      Try
        lbl.Text = deck.Pop()
      Catch ex As InvalidOperationException
        MessageBox.Show("No more cards.")
      End Try      
    Next
    

    Reference:

    • Stack(Of T).Pop @ MSDN.

    A proper solution would be to create labels dynamically, but first make sure you can get this to work. Refactoring is usually done after you have a working product.

提交回复
热议问题