gambas-source-code/app/examples/Games/Pong/.src/NPC.class
2019-05-22 05:57:48 +03:00

116 lines
2.3 KiB
Text

' Gambas class file
Public Const Normal As Integer = 0
Public Const Master As Integer = 1
Property Mode As Integer
Private $hWindow As Window
' Ball is needed to calculate movements, of course >:-)
Private $hBall As Ball
Private $hPaddle As Paddle
Private $iMode As Integer
' This is the Y coordinate we wish to reach with the middle of our paddle
Private $iY As Integer
Private $bReady As Boolean
' Master's control data
Private $iLastDir As Integer
Private $hMyPaddle As Paddle
Public Sub _new(hWnd As Window, hBall As Ball, hPaddle As Paddle, Optional iMode As Integer = Normal)
$hWindow = hWnd
$hBall = hBall
$hPaddle = hPaddle
$iMode = iMode
End
Public Sub Init()
$bReady = False
$iLastDir = $hBall.HDir
' We need to insert an opponent paddle that would block everything to not
' go into an infinite loop when trying to calculate the ball's positions
$hMyPaddle = New Paddle($hWindow, -$hPaddle.Dir)
$hMyPaddle.Reset()
$hMyPaddle.Y = 0
$hMyPaddle.Height = $hWindow.Height
End
Public Sub Move()
If $iMode = Normal Then
Move_Normal()
Else If $iMode = Master Then
Move_Master()
Endif
End
Private Sub Move_Normal()
' Make him beatable...
If CInt(Rnd(0, 2)) Then Return
' Just follow the ball
$iY = $hBall.Y
Move_Generic()
End
Private Sub Move_Master()
' Calculate the future ball's position and move accordingly
If Not $bReady Then MasterCalc()
Move_Generic()
' If the ball hits this paddle, we can begin calculating again
If $hBall.HDir <> $iLastDir And $iLastDir = -$hPaddle.Dir Then
$bReady = False
Endif
$iLastDir = $hBall.HDir
End
Private Sub Move_Generic()
Dim iMid As Integer = $hPaddle.Y + ($hPaddle.Height / 2)
Dim iDiff As Integer = $iY - iMid
If Abs(iDiff) <= 1 Then Return
$hPaddle.Y += 2 * Sgn(iDiff)
End
Private Sub MasterCalc()
Dim hMyBall As New Ball($hWindow, True)
' Use the CBall class to sneakily get the position we have to sit on
' when the ball arrives at this end
hMyBall.HDir = $hBall.HDir
hMyBall.VDir = $hBall.VDir
hMyBall.X = $hBall.X
hMyBall.Y = $hBall.Y
' Simulate the ball flying thither and back again
While hMyBall.X <> $hPaddle.X
hMyBall.Move($hMyPaddle, Null)
Wend
$iY = hMyBall.Y
$bReady = True
End
Private Sub Mode_Read() As Integer
Return $iMode
End
Private Sub Mode_Write(Value As Integer)
$iMode = Value
End