You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET太空入侵者游戏高分系统异常:低分触发高分输入框问题

问题原因

你的代码存在核心逻辑错误:更新Highscore.Text时,直接将数值与描述字符串拼接,导致后续判断高分时,Val(Highscore.Text)无法正确解析数字。

比如第一次设置高分后,Highscore.Text变成high Score: 100这类字符串,Val()函数遇到非数字的"high"就会停止解析,返回0。此时哪怕新得分只有50,50 > 0的判断也会成立,触发输入框弹出。

修复方案

需要将高分的纯数值和显示文本分离处理,以下是两种可行修改方式:

方式一:用变量存储纯数字高分

' 类级别变量存储纯数字高分
Private highScoreValue As Integer = 0

' 窗体加载时从文件读取已保存的高分
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    If File.Exists("score.txt") Then
        Dim lines() As String = File.ReadAllLines("score.txt")
        If lines.Length >= 2 Then
            ' 提取并解析高分数值
            Dim highScoreStr As String = lines(1).Replace("high Score: ", "")
            Integer.TryParse(highScoreStr, highScoreValue)
            Highscore.Text = lines(1)
            Best.Text = lines(0)
        End If
    End If
End Sub

' 游戏结束时的判断逻辑
If Val(Lives.Text) = 0 Then
    MsgBox("You Lose!")
    
    Dim currentScore As Integer = Val(score.Text)
    If currentScore > highScoreValue Then
        highScoreValue = currentScore
        Highscore.Text = "high Score: " & currentScore.ToString()
        
        Dim playerName As String = InputBox("Enter your name")
        Best.Text = "best Player: " & playerName
        
        ' 保存到文件
        filenum = FreeFile()
        FileOpen(filenum, "score.txt", OpenMode.Output)
        PrintLine(filenum, Best.Text)
        PrintLine(filenum, Highscore.Text)
        FileClose(filenum)
    End If
    Close()
End If

方式二:直接从Highscore.Text提取数字判断

如果不想新增变量,可在判断前清理Highscore.Text中的非数字内容:

If Val(Lives.Text) = 0 Then
    MsgBox("You Lose!")
    
    Dim currentScore As Integer = Val(score.Text)
    ' 提取Highscore.Text里的数字部分
    Dim highScoreStr As String = Highscore.Text.Replace("high Score: ", "")
    Dim highScoreValue As Integer = Val(highScoreStr)
    
    If currentScore > highScoreValue Then
        Highscore.Text = "high Score: " & currentScore.ToString()
        
        Dim playerName As String = InputBox("Enter your name")
        Best.Text = "best Player: " & playerName
        
        filenum = FreeFile()
        FileOpen(filenum, "score.txt", OpenMode.Output)
        PrintLine(filenum, Best.Text)
        PrintLine(filenum, Highscore.Text)
        FileClose(filenum)
    End If
    Close()
End If
额外建议
  • 替换Val()函数为Integer.TryParse(),更安全地解析数字,避免文本格式错误引发异常。
  • 把Close()移到If/Else结构外,减少冗余代码。

内容的提问来源于stack exchange,提问作者elfuegoeggo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:31:05