好let's劃分問題成幾塊。
- 所有函數/子/變量位於類Form1
- 對於佔位符我選擇_
與FontStyle.Underline
選項。這將始終強調在正確的位置。在這種情況下,空白
也應該用作佔位符。
確定hang子手字的字符。
將結果存儲在類變量中,以便稍後在設置下劃線佔位符或顯示正確的字符時使用。
private _solution as Char()
Private Sub setSolution(word As String)
'Get chars from word and put into class variable
_solution = word.ToArray()
End Sub
創建一個類似於表格的面板佈局。每列包含一個字符:
Private Sub createLayout(word As String)
setSolution(word)
'Create a panel layout with columns to get a proper distribution of chars
Dim table As New TableLayoutPanel()
table.Name = "tblHangmanWord"
table.ColumnCount = _solution.Length
table.RowCount = 1
table.AutoSize = True
table.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
'Adjust the bounds to your needs
table.SetBounds(40, 150, 400, 25)
table.CellBorderStyle = TableLayoutPanelCellBorderStyle.None
'Create labels which display placeholder first, add them to the panel. The array index of _solution correspond to the table columns index.
For i As Integer = 0 To _solution.Length - 1
Dim label As New Label()
label.Name = "lblWord" & i.ToString
label.Text = "___" 'Placeholder
label.AutoSize = True
label.Font = New Font(DefaultFont, FontStyle.Underline)
'Add label to pabel
table.Controls.Add(label)
Next
'Add panel to form
Me.Controls.Add(table)
End Sub
手柄上的一個char按鈕user's點擊。
檢查解決方案中的哪些字符與按鈕匹配,然後顯示正確的字符。
Private Sub btnM_Click(sender As Object, e As EventArgs) Handles btnM.Click
'Get the indexes of the matches of the current button char
Dim idxOfMatches = getIndexOfMatches(DirectCast(sender, Button).Text.First())
'Show the correct chars in the grid
revealMatchingChars(idxOfMatches)
End Sub
Private Function getIndexOfMatches(selected As Char) As Integer()
Dim idxOfMatches As New List(Of Integer)
For i As Integer = 0 To _solution.Length - 1
If selected = _solution(i) Then
idxOfMatches.Add(i)
End If
Next
Return idxOfMatches.ToArray()
End Function
Private Sub revealMatchingChars(idxOfMatches As Integer())
'Get the table panel layout
Dim tbl = Me.Controls.OfType(Of TableLayoutPanel).Where(Function(t) t.Name = "tblHangmanWord").First()
'reveal correct chars
For Each idx As Integer In idxOfMatches
tbl.Controls(idx).Text = _solution(idx)
Next
End Sub
把所有在一起,創建一個測試佈局:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
createLayout("Millencolin")
End Sub
![User clicked M](https://i.stack.imgur.com/NpLQ5.png)
你只有兩個標籤,一個是字符,一個用於行?我建議爲每個字符創建一個標籤(或文本框)以供猜測,併爲每個下劃線創建一個。這使得處理一個字符/下劃線位置變得更容易。你甚至可以動態地創建標籤的數量。 –
@AlexB。它跨過了我的想法嘗試它,但我很不確定如何實際做到這一點。當談到VB時,並不是最有經驗的人。 – ForfA
當我找到答案的時候,我會寫一個答案 –