2013-12-08 7 views
0

이것은 매우 간단한 코드입니다. 나는 VB를 사용하기 시작했다. 당신이 올바른 순서로 셔플 번호를 재주문하는 게임을하고있는 Im. 최소한의 시간과 최소한의 클릭으로 퍼즐을 풀려고합니다. 다음에 게임을 할 때 점수를 낮추려고 시도하거나 그 기록을이기십시오. 16 개의 버튼 (4x4)과 15 개의 숫자가 있습니다. 체크 버튼 기능이있어 퍼즐 해결 여부를 확인할 수 있습니다. 프로그램을 디버깅 할 때마다 클릭 수 및 최종 시간이 강조 표시되고 Null 참조 예외가 처리되지 않았다고 말합니다. 코드의 일부를 heres. null 참조 예외가 처리되지 않았습니다.

Public Class Form1 
Dim Clicks As Integer = 0 'The variable that counts the number of times you clicked 
Dim Time As Integer 'The vairable that holds the time 
Dim TimeMin As Integer 'The variable that holds the minutes 
Dim TimeSec As Integer 'The variable that holds the seconds 
Dim FinalTime As String 'The variable that holds the final time (minutes and seconds) 
Dim lngArray() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""} {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""}  
Dim NumArray() As Integer 
Dim NumArray1() As String 

Private Sub CheckButton(ByRef Butt1 As Button, ByRef Butt2 As Button) 
    If Butt2.Text = "" Then 'Checks if the button around the clicked number is empty "" It's the location of the empty square that you want the number in Butt1 to move to. 
     Butt2.Text = Butt1.Text 'If it is, the value from Butt2 will "copy and paste" into Butt1 
     Butt1.Text = "" 'Butt1 will keep the value and the value in Butt2 will clear "" 
     Clicks += 1 'Incrementing Each click by only 1. It's a counter. In addition, the code above only allows the click to increment by 1 if the number has moved. If you just click on a number that can't move, the click would not count. 
    End If 
    If Clicks > 1 Then 
     lblTotal.Text = Clicks & " Clicks" 'Shows the total amount of clicks when it is greater than one 
    Else 
     lblTotal.Text = Clicks & " Click" 'Shows the total amount of clicks when it is one 
    End If 

End Sub 

Private Sub CheckSolved() 'A private sub that checks if the puzzle is solved ,restarts the count, and stops the time 
    Dim strName As String = "" 'The variable that has the string of the winners name 
    If Me.Button1.Text = "1" And Me.Button2.Text = "2" And Me.Button3.Text = "3" And Me.Button4.Text = "4" And Me.Button5.Text = "5" And Me.Button6.Text = "6" And Me.Button7.Text = "7" And Me.Button8.Text = "8" And Me.Button9.Text = "9" And Me.Button10.Text = "10" And Me.Button11.Text = "11" And Me.Button12.Text = "12" And Me.Button13.Text = "13" And Me.Button14.Text = "14" And Me.Button15.Text = "15" Then 'Checks if the numbers are in the correct buttons 
     Timer1.Enabled = False 'Stops the time 
     strName = InputBox("What is your name", "Name of winner") 'Get's the winners name 
     MessageBox.Show("In " & FinalTime & " , you solved the puzzle in " & Me.Clicks & " clicks! Congratulations " & strName) 'Messagebox showing how many times you clicked to solve the puzzle. It gets the name you typed into the inputbox (strname) and displays it 
     Call Restart() 'Shuffles the buttons and restarts the game when you win 
     Call Record(NumArray, NumArray1) 
    End If 
End Sub 
Private Sub Record(ByVal NumArray() As Integer, ByVal NumArray1() As String) 
    'Make timemin array and then make time array. Then make click array 
    For i As Integer = 0 To 1000 
     NumArray(i) = Clicks 'This is where the Null Reference error occured 
     i = +1 
     Array.Sort(NumArray) 'sorting the array values from least to greatest 
    Next i 

    lblRecordClicks.Text = NumArray(0) & " Clicks" 'displaying the lowest number of clicks in the label 
    For k As Integer = 0 To 1000 'Making an integer that captures 1000 values 
     NumArray1(k) = FinalTime 'This is where the Null Reference error occured 
     k = +1 
     Array.Sort(NumArray1) 'sorting the array values from least to greatest 
    Next k 

    lblRecordTime.Text = NumArray1(0) 'displaying the lowest time in the label 
End Sub 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 
    Call Times() 
End Sub 

Private Sub Shuffle(ByVal lngArray As Object) 'Shuffles the values of the Array 
    Dim i As Long 
    Dim iMin As Long 
    Dim iMax As Long 
    Dim lngReplace As Long 
    Dim varSwap As Object 
    iMin = LBound(lngArray) 
    iMax = UBound(lngArray) 
    For i = iMax To iMin + 1 Step -1 
     lngReplace = Int((i - iMin + 1) * Rnd() + iMin) 
     varSwap = lngArray(i) 
     lngArray(i) = lngArray(lngReplace) 
     lngArray(lngReplace) = varSwap 
    Next 
    Button1.Text = lngArray(0) 
    Button2.Text = lngArray(1) 
    Button3.Text = lngArray(2) 
    Button4.Text = lngArray(3) 
    Button5.Text = lngArray(4) 
    Button6.Text = lngArray(5) 
    Button7.Text = lngArray(6) 
    Button8.Text = lngArray(7) 
    Button9.Text = lngArray(8) 
    Button10.Text = lngArray(9) 
    Button11.Text = lngArray(10) 
    Button12.Text = lngArray(11) 
    Button13.Text = lngArray(12) 
    Button14.Text = lngArray(13) 
    Button15.Text = lngArray(14) 
    Button16.Text = lngArray(15) 
End Sub 

Private Sub RestartToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestartToolStripMenuItem.Click 
    Call Restart() 
    Call Me.btnStart_Click(sender, e) 'Call the button click to enable all buttons 
End Sub 
Private Sub Times() 
    Time = Time + 1 'Increase the time by 1 second every interval 
    TimeSec = TimeSec + 1 'Increase the time by 1 second every interval 
    TimeMin = Convert.ToInt32(TimeSec \ 60) 'Takes the whole number of the amount of seconds divided by 60 and leaves out the remainder 
    If Time >= 60 Then 
     Time = 0 
    End If 
    'If the seconds pass 59 (and they do), it restarts to 0 
    FinalTime = TimeMin & " min " & Time & " seconds" 'Final time is the string displayed showing the final time 
    lblTime.Text = FinalTime 'The label displays the final time 
End Sub 
Private Sub Restart() 
    Time = 0 'Resets the time 
    Clicks = 0 'Resets the amount of clicks 
    lblTotal.Text = "" 'Clears the label 
    lblCheat.Visible = False 
    lblTotal.Visible = True 
    lblClicks.Visible = True 
    lblQuote.Visible = True 
    lblRecordClicks.Visible = True 
    lblRecordTime.Visible = True 
    'If the user cheated and hit the solve button and wants to restart and solve the puzzle on their own, then he can. Turning these label settings to true allows you to see them again 
    Call Shuffle(lngArray) 'Shuffles the numbers 
    Timer1.Enabled = True 'Continues the time when it resets to 0 

End Sub 

Public Sub RefreshEverythingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshEverythingToolStripMenuItem.Click 
    Timer1.Enabled = False 'Pauses the timer 
    If MessageBox.Show("Do you want to restart everything?", "Restart Game", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then 
     Time = 0 
     TimeSec = 0 
     'Resets the time 
     Clicks = 0 'Resets the amount of clicks 
     lblTotal.Text = "" 'Clears the label 
     lblRecordClicks.Text = "" 'Resets the record click 
     lblRecordTime.Text = "" 'Resets the record time 
    End If 
    Call Shuffle(lngArray) 'Shuffles the numbers 
    Timer1.Enabled = True 'Continues the timer if no is selected 
    ReDim NumArray(1000) 'Clears the array data that was captured 
    ReDim NumArray1(1000) 'Clears the array data that was captured 
End Sub 

End Class 

당신은 (그리고 난 당신이 이해 해 주길 바래)는 "컴퓨터"얘기를 사용하지 않도록하고 "나에게 바보 그것을 아래로"하려고 시도 할 수 있도록 결정했다면

. 전에 말했듯이, 나는 이것에 대해 새로운 것입니다. 시간 내 줘서 고마워.

+0

예외가 발생하는 행은 무엇입니까? – Szymon

+1

Theres this happenens ... '여기 Null Reference 오류가 발생하는 곳의 주석이 있습니다. – user3078445

답변

0

값을 배열에 저장하려고합니다. Dim NumArray() As Integer과 같은 배열을 정의 할 때 배열에 대한 경계 (배열은 기본적으로 Nothing)가 설정되어 있지 않으므로 배열 항목에 액세스하려고하면 Null 참조 예외가 발생합니다. Public Sub RefreshEverythingToolStripMenuItem_Click에 배열 경계 만 설정합니다. 이제 모든 코드를 알 수는 없지만 사용자가 특별히이 단추를 클릭하지 않고 게임을 시작하면 배열이 Nothing이됩니다. 게임을 시작하기 전에 배열 경계가 항상 설정되어 있는지 확인해야합니다.

.NET에서 더 많은 추상 배열과 유사한 유형을 조사 할 수도 있습니다. 예를 들어 목록을 시도해 볼 수 있습니다. List는 사실상 임의의 경계를 가진 배열입니다. 당신은 키워드를 사용하여 특정 유형의 목록을 정의하고 다음 정렬 항목을 제거, 목록으로에 목록을 추가하는 방법을 항목을 추가 할 수 있습니다 등

가 전역 변수로 정의 :

Dim FinalTimes as New List(Of Integer) 
Dim FinalClicks as New List(Of Integer) 

여기서 새 키워드를 사용하십시오. 즉, List 클래스의 새 객체가 만들어집니다. 그렇지 않으면 아래 행에 Null 참조 예외가 발생합니다. 사용자가 퍼즐을 풀었을 때 당신이 다음을 수행하십시오

FinalTimes.Add(FinalTime) 
FinalClicks.Add(Clicks) 
FinalTimes.Sort 
FinalClicks.Sort 

이것은 기본적으로 하나 목록의 길이를 증가 마지막 항목에 FinalTime/클릭 수의 값을 기록하고 두 목록을 의지합니다. 아이디어 : 최고 점수를 얻으려면 FinalTime, 클릭 수 및 플레이어 이름을 구조에 연결하고 IComparer 인터페이스를 사용하여 사용자가 이름/시간/클릭 수로 높은 점수 목록을 정렬하도록 할 수 있습니다.

  • 옌스

PS : 나는 잊어 버리기 전에 : 예외 코드에서 발생하는 루프에 대한 더 진정한 의미하지 않습니다. 첫 번째 문제는 루프가 i = 1000 일 때 끝나는 동안 루프에서 i를 1로 설정했기 때문에 현재 양식에서 무한 루프가된다는 것입니다. 나는 당신이 i=i+1 또는 더 짧은 i += 1을 의미했다고 생각합니다. 그러나 그들은 여전히 ​​거의 의미가 없습니다. 정확히 무슨 일이 일어나는지 보려고 시도했는데 (분명하지는 않습니다 :-)), 높은 점수의 절반이 새로운 가치 등으로 덮어 쓰여집니다. 위의 방법이 더 쉬울 것이라고 생각합니다. :-)

+0

분류 된 FinalTimes 및 FinalClicks를 어떻게 레이블에 표시 하시겠습니까? FinalClicks 및 Final Time 변수를 정렬 한 코드 아래의 단락에 대한 설명을 정확히 이해하지 못했습니다. – user3078445

+0

'FinalTimes.정렬 '을 선택하면 목록의 값이 정렬되고 표시되지 않습니다. 값을 표시하기 위해서 자신 만의'Function ListToString (By Integer List)를'String'으로 만들 수 있습니다. 거기에 :'Dim res as string = ""','각각의 i가 정수 인 경우','res & = i.tostring','Next','Return res','End Function'. 귀하의 코드에서 :'lblTimes.Text = ListToString (FinalTimes)' – Jens

관련 문제