試題說明:
專案名稱:班號-幻方19x19
表單大小:520x500、 表單標題「班級座號姓名-幻方19x19」
下拉式清單一個ComboBox1,位置(25 ,15 )顯非「請選擇」項目預設值 3,4,5,7,8,9
按鈕2個Button1,Button2,「產生格式」、「產生數字」位置(100,10)、(200,10)
程式規定:
1、載入時,將清單項目增加11,13,15,17,19及12,16
並新建標籤控制項陣列 19x19先隱藏, 兩個按鈕皆不啟動
2、選了下拉式清單的某一個 n 值時,改變表單大小
n>9則 寬、高皆 50*n ,否則 大小(520,500)
按鈕1啟動、按鈕2不啟動
3、按鈕1「產生格子」:左上角(40,40)起產生nxn個標籤,每個大小(35,35)
間距2,有外框,字型為("Arial", 9)、顯示值0
然後將按鈕1設為不啟動,將按鈕2設為啟動
4、按鈕2「產生數字」:產生幻方nxn的數字 ,規則如下
(1)以最上列中間格為1,左上為下1個數字
(2)上空則移至最下列
(3)左空則移至最右行
(4)已填則彈回往下1格 (5)兩空則同彈回
完成之幻方其橫、直、斜之和皆相同
參考程式碼
**** 共用區間之變數、常數 ****
Dim n As Integer 'nxn
Dim Maxr = 19, Maxc = 19 '列及行
Const stX = 40
Const stY = 40
Const GW = 35 '每小格寬
Const GH = 35 '每小格高
Const GP = 2 '每小格間距
Dim Lb(Maxr, Maxc) As Label '宣告為 公用陣列 Lb
Dim mtx(Maxr + 2, Maxc + 2) As Integer
*****************************
*** 程式一載入時 ***
For r = 0 To Maxr - 1
For c = 0 To Maxc - 1
Lb(r, c) = New Label '新增 控制項陣列
Lb(r, c).Visible = False ' 隱藏不顯現
Next
Next
For i = 11 To Maxr
If i Mod 4 <> 2 Then ComboBox1.Items.Add(i)
Next
Button1.Enabled = False '產生格子不啟動
Button2.Enabled = False '產生數字不啟動
********************
*** 選了清單某一項目時 ***
n = ComboBox1.Text
If n > 9 Then
Me.Height = n * 50
Me.Width = n * 50
Else
Me.Width = 520
Me.Height = 500
End If
Button2.Enabled = False '產生數字不啟動
Button1.Enabled = True '產生格子 啟動
********************
*** 按鈕1「產生格子」 ***
If n = 0 Then
MsgBox("請下拉選一個數字")
Exit Sub
End If
Dim r, c As Short
'隱
For r = 0 To Maxr - 1
For c = 0 To Maxc - 1
Lb(r, c).Visible = False
Next
Next
For r = 0 To n - 1 '列號
For c = 0 To n - 1 '行號
'仍須以 new 新增物件
Lb(r, c).AutoSize = False '自動大小取消
Lb(r, c).Top = stY + r * (GH + GP) '設定上邊距
Lb(r, c).Left = stX + c * (GW + GP) '設定左邊距
Lb(r, c).Width = GW '寬
Lb(r, c).Height = GH '高
Lb(r, c).Font = New Font("Arial", 9)
mtx(r, c) = 0
Lb(r, c).Text = mtx(r, c) '在 form_load 產生 mtx(r,c)
Lb(r, c).Visible = True
Lb(r, c).BorderStyle = BorderStyle.FixedSingle '加外框
Lb(r, c).Name = "LB" & (r & "_" & c)
Me.Controls.Add(Lb(r, c)) '加入控制項
' AddHandler Lb(r, c).Click, AddressOf LB_x '動態 新增事件
Next c
Next r
Button1.Enabled = False
Button2.Enabled = True
********************
*** 按鈕2「產生數字」 ***
If n Mod 2 = 1 Then
magic1() '奇階
ElseIf n Mod 4 = 0 Then
magic4() ' 4k 階
Else
' MsgBox(" 4K+2 階, 施工中! ")
'magic6()
End If
********************
*** 副程式magic1 為奇數階 ***
Dim p = 1
Dim n2 = n * n
Dim r As Integer = 0, c As Integer = n \ 2
Dim nr, nc As Integer
Do Until p > n2
mtx(r, c) = p
Lb(r, c).Text = mtx(r, c)
nr = r - 1 : nc = c - 1
If nr < 0 And nc < 0 Then
nr = r + 1 : nc = c
ElseIf nr < 0 Then
nr = n - 1
ElseIf nc < 0 Then
nc = n - 1
ElseIf mtx(nr, nc) > 0 Then
nr = r + 1 : nc = c
End If
r = nr : c = nc '下一座標
p += 1 '下一標號
Loop
********************
*** 副程式magic4 為 4k 階 ***
Dim p = 1
Dim n2 = n * n
Dim r, c, r1, c1 As Integer
For r = 0 To n - 1
r1 = r Mod 4
For c = 0 To n - 1
c1 = c Mod 4
If r1 = c1 Or r1 + c1 = 3 Then
mtx(r, c) = n2 + 1 - p
Else
mtx(r, c) = p
End If
p += 1
Lb(r, c).Text = mtx(r, c)
Next
Next
********************
0 意見:
張貼留言