我是编程和 OOP 的新手,所以请原谅我缺乏知识。
作为我的 Rock, Paper and Scissors 游戏的一部分,我有一个抽象超类(Weapon ),它在 VB.NET中有子类(Rock, Paper 和 Scissors ),例如:
Public MustInherit Class Weapons
Public Class Paper
Inherits Weapons
Public Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Paper Then
Return 0
ElseIf TypeOf Weapons Is Rock Then
Return 1
Else
Return -1
End If
End Function
End Class
Public Class Rock
Inherits Weapons
Public Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Rock Then
Return 0
ElseIf TypeOf Weapons Is Scissors Then
Return 1
Else
Return -1
End If
End Function
End Class
Public Class Scissors
Inherits Weapons
Public Function compareTo(ByVal Weapons As Object) As Integer
If TypeOf Weapons Is Scissors Then
Return 0
ElseIf TypeOf Weapons Is Paper Then
Return 1
Else
Return -1
End If
End Function
End Class
End Class
还有一个超类Player,它具有子类(PlayerComputerRandom和PlayerHumanPlayer),例如:
Imports RockPaperScissors.Weapons
Public Class Player
Private pName As String
Private pNumberOfGamesWon As String
Public pWeapon As Weapons
Property Name() As String
Get
Return pName
End Get
Set(ByVal value As String)
pName = value
End Set
End Property
Property NumberOfGamesWon As String
Get
Return pNumberOfGamesWon
End Get
Set(ByVal value As String)
pNumberOfGamesWon = value
End Set
End Property
Property getWeapon As Weapons
Get
Return pWeapon
End Get
Set(ByVal value As Weapons)
pWeapon = value
End Set
End Property
Public Sub pickWeapon(ByVal WeaponType As String)
If WeaponType = "Rock" Then
pWeapon = New Rock()
ElseIf WeaponType = "Paper" Then
pWeapon = New Paper()
Else
pWeapon = New Scissors()
End If
End Sub
End Class
Imports RockPaperScissors.Weapons
Public Class PlayerComputerRandom
Inherits Player
Private Enum weaponsList
Rock
Paper
Scissors
End Enum
Public Overloads Sub pickWeapon()
Dim randomChoice = New Random()
Dim CompChoice As Integer = randomChoice.Next(0, [Enum].GetValues(GetType(weaponsList)).Length)
If CompChoice = "0" Then
pWeapon = New Rock()
ElseIf CompChoice = "1" Then
pWeapon = New Paper()
Else
pWeapon = New Scissors()
End If
End Sub
End Class
Public Class PlayerHumanPlayer
Inherits Player
End Class
但是,在单击 btnRock 后尝试比较结果时,我收到错误“compareTo”不是“RockPaperScissors.Weapons”的成员。代码是:
Public Class GameForm
Private Sub btnRock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRock.Click
Dim player1 = New PlayerHumanPlayer()
Dim player2 = New PlayerComputerRandom()
player1.Name = "HumanPlayer"
player1.pickWeapon("Rock")
player2.Name = "Computer"
player2.pickWeapon()
Dim winner As Integer = player1.getWeapon().compareTo(player2.getWeapon())
Select Case winner
Case 1
Console.WriteLine(player1.Name() + " wins!")
Case -1
Console.WriteLine(player2.Name() + " wins!")
Case 0
Console.WriteLine("Draw!")
End Select
End Sub
End Class
' Dim Winner As Integer = player1.getWeapon().compareTo(player2.getWeapon()) 行似乎是导致问题的原因。
知道如何对此进行排序,以确保返回正确的获胜者结果吗?任何帮助将不胜感激。
提前谢谢