Push-push

Game development specific discussions.
Post Reply
Kot
Posts: 336
Joined: Dec 28, 2006 10:34

Push-push

Post by Kot »

This is a very simple network game. I didn't remember its name, so I called it push-push. I tested it only on localhost, so I don't know if it works on the real network.
As you may see, I took server and client from TSNE library examples, cut out pretty much of code and put a bit of mine, so to make it work you need TSNE_V3.BI file.
The rules are simple: you bet, your opponent bets and the winner moves the token into the opponent's area. There's only one trick: no matter how much you beat your oponent in bidding, you always move the token only ONE unit forward. So, plan your expenses wisely ;-)
pp-server:

Code: Select all

'##############################################################################################################
'TEST-SERVER für TSNE Version 3
'##############################################################################################################



'##############################################################################################################
#include once "TSNE_V3.bi"							'Die TCP Netzwerkbibliotek integrieren

'**********************************************************************************

'**********************************************************************************

'##############################################################################################################
Dim Shared G_Server		as UInteger					'Eine Variable für den Server-Handel erstellen



'##############################################################################################################
Type Client_Type									'Ein UDT welches die einzelnen Verbindungen und deren Parameter hält
	V_InUse				as UByte					'Wird verwendet um zu überprüfen ob der Eintrag belegt ist
	V_TSNEID				As UInteger					'Speicher die TSNEID der Verbindung
	V_IPA					As String					'Die IP der Verbindung
	V_ConTime			as Double					'Hier speichern wir die Uhrzeit des verbindungsaufbaus ab
	V_Data				as String					'Speicher die eingehenden Daten zwischen, (Blocktransfer)
End Type

Dim Shared ClientD As Client_Type				'Das UDT-Array für die Clienten
Dim Shared ClientMutex	as Any Ptr					'Wir erstellen ein MUTEX welches verhindert das mehrere verbindugen gleichzeitg auf das UDT zugreifen
Dim KeyPressd As String
Dim Shared As Integer MyBet, MyBetSent, OpBet, MyPool=50, OpPool=50, TokenPos

'##############################################################################################################
'	Deklarationen für die Empfänger Sub Routinen erstellen
Declare Sub	TSNE_Disconnected			(ByVal V_TSNEID as UInteger)
Declare Sub	TSNE_Connected				(ByVal V_TSNEID as UInteger)
Declare Sub	TSNE_NewData				(ByVal V_TSNEID as UInteger, ByRef V_Data as String)
Declare Sub TSNE_NewConnection			(ByVal V_TSNEID as UInteger, ByVal V_RequestID as Socket, ByVal V_IPA as String)
Declare Sub TSNE_NewConnectionCanceled	(ByVal V_TSNEID as UInteger, ByVal V_IPA as String)

Declare Sub PrintAll
Declare Sub WinCondition

'##############################################################################################################
Print "[INIT] Setup..."								'Signalisieren das wir das Programm starten
ClientMutex = MutexCreate()							'Ein neues MUTEX erstellen
Dim RV as Long										'Eine Statusrückgabe Variable
Print "[SERVER] Init..."							'Signalisieren das wir den Server jetzt inizialisieren
RV = TSNE_Create_Server(G_Server, 12345, 10, @TSNE_NewConnection, @TSNE_NewConnectionCanceled)	'Server erstellen
If RV <> TSNE_Const_NoError Then					'Prüfen ob dabei Fehler entstanden sind
	Print "[SERVER] [ERROR] " & TSNE_GetGURUCode(RV)	'Irgend ein Fehler trat beim erstellen des Server auf
	MutexDestroy(ClientMutex)						'MUTEX zerstören. Wird jetzt nimmer gebraucht
	Print "[END]"									'Wir sind fertig
	End	0											'Und beenden das Programm mit dem Returncode: 0
End if
Print "[SERVER] OK!"								'Wenn nicht, dann ausgaben das alle OK war
RV = TSNE_BW_SetEnable(G_Server, TSNE_BW_Mode_Black)	'Wir aktivieren eine IPA-Blockliste des Types: BlackList (Alle IPAs in der Liste werden blockiert)
If RV <> TSNE_Const_NoError Then					'Prüfen ob dabei Fehler entstanden sind
	Print "[SERVER] [ERROR] BWL: " & TSNE_GetGURUCode(RV)	'Irgend ein Fehler trat beim erstellen des BWL auf
	MutexDestroy(ClientMutex)						'MUTEX zerstören. Wird jetzt nimmer gebraucht
	Print "[END]"									'Wir sind fertig
	End	0											'Und beenden das Programm mit dem Returncode: 0
End If
Print "[SERVER] wait for ESC push..."				'Ausgeben das wir auf ein ESC Tastendruck warten
Do													'Wir poolen den Tastenabfrage
	If MyBetSent=FALSE Then KeyPressd=InKey		'no bet changes after pressing Enter
	Select Case Len (KeyPressd)
		Case 2
			If KeyPressd=Chr(255)+"H" Then		'up
				If MyPool>0 Then
					MyBet+=1
					MyPool-=1
					PrintAll
				EndIf
			ElseIf KeyPressd=Chr(255)+"P" Then			'down
				If MyBet>0 Then
					MyBet-=1
					MyPool+=1
					PrintAll
				EndIf
			EndIf
		Case 1
			If KeyPressd=Chr(13) And MyBet>0 Then			'return
				Dim BV as Integer = TSNE_Data_Send(ClientD.V_TSNEID, Str(MyBet))
				If BV <> TSNE_Const_NoError Then
					Print "[ERROR] " & TSNE_GetGURUCode(BV)		'Print error
				Else
					MyBetSent=TRUE
				End If
				Sleep 500,1				'I don't know why this is necessary, but otherwise OpBet isn't zeroed, buffer or so?
			EndIf
	End Select
	If OpBet>0 And MyBetSent=TRUE Then
		If OpBet>MyBet Then
			TokenPos-=1
		ElseIf OpBet<MyBet Then
			TokenPos+=1
		Else				'draw
			'print "Draw"
		EndIf
		MyBetSent=FALSE
		OpPool-=OpBet
		OpBet=0
		MyBet=0
		Do While InKey<>"":Loop		'clear the keyboard buffer
		PrintAll
		WinCondition
	EndIf
	Sleep 1, 1										'Kurz warten um die CPU auslastung massiv zu verringern
Loop Until KeyPressd=Chr(27)
Print "[SERVER] ESC pushed!"						'Und ausgeben was wir das ESC erkannt haben
Print "[SERVER] Disconnecting..."					'Mitteilen das wir den Server beenden
RV = TSNE_Disconnect(G_Server)						'Server-Socket beenden
If RV <> TSNE_Const_NoError Then Print "[SERVER] [ERROR] " & TSNE_GetGURUCode(RV)	'Wenn ein Fehler entstand, dann geben wir diesen aus
Print "[SERVER] Wait disconnected..."				'Ausgeben das wir trotzdem auf den Disconnect warten
TSNE_WaitClose(G_Server)							'Wir warten auf das ende der serververbindung
Print "[SERVER] Disconnected!"						'Server wurde beendet
MutexLock(ClientMutex)								'MUTEX sperren um zugriff darauf zu verhinden
Dim TID as UInteger									'Eine Variable erstellen welche die TSNEID zwischenspeichert
TID = ClientD.V_TSNEID					'Wir hohlen die TSNEID der Verbindung udn speichern sie zwischen
MutexUnLock(ClientMutex)					'Da wir jetzt die CLientverbindung trennen wird auch das Disconnect event aufgerufen. Darum Müssen wir das MUTEX entsperren
TSNE_Disconnect(TID)						'Verbindung trennen
MutexDestroy(ClientMutex)							'MUTEX zerstören. Wird jetzt nimmer gebraucht
Print "[END]"										'Wir sind fertig

End	0												'Und beenden das Programm mit dem Returncode: 0


Sub PrintAll
Color 7
Dim StartY As Integer=12
Locate StartY-3,15
If ClientD.V_InUse = 0 Then
	Print "Waiting for client connection..."
Else
	Print "        Press Esc to end        "
EndIf
Locate StartY,20
Print Chr(177,196,197,196,197,196,197,196,197,196,178,196,197,196,197,196,197,196,197,196,177)
Locate StartY+1,20:Print Space(25)
Color 12:Locate StartY+1,30+2*TokenPos:Print Chr(30)
Locate StartY+4,15
Color 7:Print "Your pool: "; Format(MyPool,"00"); "   Your bet: ";
Color 2:Print Chr(24);
Color 7:print " "; Format(MyBet,"00");" ";
Color 2: Print Chr(25)
Color 7
End Sub


'##############################################################################################################
Sub TSNE_Disconnected(ByVal V_TSNEID as UInteger)	'Empfänger für das Disconnect Signal (Verbindung beendet)
MutexLock(ClientMutex)								'Mutex Sperren um auf das Array zugreifen zu können
ClientD.V_InUse = 0					'Da dieses Element nun nicht mehr gebraucht wird können wir dieses als 'Nicht in nutzung' markieren
ClientD.V_Data = ""					'Daten-variable leeren. Verbraucht nur speicher
Print "[CLIENT] Disconnected >_<"	'und ausgeben das wir die verbindung beendet haben
MutexUnLock(ClientMutex)				'Mutex Sperre kann jetz taufgehoben werden, da es sonst zu einem MUTEX Leak kommt wenn wir die Sub direkt verlassen
End Sub



'##############################################################################################################
Sub TSNE_Connected(ByVal V_TSNEID as UInteger)		'Empfänger für das Connect Signal (Verbindung besteht)
MutexLock(ClientMutex)								'Mutex Sperren um auf das Array zugreifen zu können
ClientD.V_TSNEID=V_TSNEID
ClientD.V_ConTime = Timer()			'Wir speichern die aktuelle Uhrzeit ab
Print "[CLIENT] Connected >_<"	'und ausgeben das die client-verbindung vollständig hergestellt wurde
MutexUnLock(ClientMutex)							'Mutex Sperren aufheben
PrintAll
End Sub



'##############################################################################################################
Sub TSNE_NewConnection(ByVal V_TSNEID as UInteger, ByVal V_RequestID as Socket, ByVal V_IPA as String)		'Empfänger für das NewConnection Signal (Neue Verbindung)
Dim TNewTSNEID as UInteger							'Eine Variable welche die Neue TSNEID beinhaltet
Dim TReturnIPA as String							'Eine Variable welche die IP-Adresse des clienten beinhaltet
Dim CIndex as UInteger								'Eine Variable erstellen welche einen freien Array index speichert
Dim RV as Long										'Die Statusrückgabe variable
MutexLock(ClientMutex)								'Mutex Sperren um auf das Array zugreifen zu können
If ClientD.V_InUse<>0 Then
	'client already connected error and exit sub
EndIf
RV = TSNE_Create_Accept(V_RequestID, TNewTSNEID, TReturnIPA, @TSNE_Disconnected, @TSNE_Connected, @TSNE_NewData)	'Da wir noch platz haben akzeptieren wir die verbindung mit den Callbacks
If RV <> TSNE_Const_NoError Then					'Gab es einen Fehler beim 'Accept'?
	Print "[CLIENT] [ERROR] " & TSNE_GetGURUCode(RV)	'Dann geben wir diesen aus
	MutexUnLock(ClientMutex)						'Entsperren das Mutex
	Exit Sub										'und verlassen auf direktem wege die sub
End If
With ClientD								'Kein fehler entsanden? dann das freie Element selektieren
	.V_InUse	= 1									'und markieren es als 'In Nutzung'
	.V_TSNEID	= TNewTSNEID						'TSNEID der neuen Verbindung speichern
	.V_IPA		= V_IPA								'Die IPA (IP-Adresse) der neuen Verbindung speichern
	.V_ConTime	= 0									'Wir sind noch nicht ganz verbunden (Connect-event fehltnoch) darum Zeit auf 0 setzen
	.V_Data		= ""								'Daten Variable leeren. Könnte durch eine vorherige verbindung noch gefüllt sein
End With
Print "[CLIENT] New Connect >" "<   IPA:" & V_IPA	'Anzeigen das Verbindung akzeptiert wurde.
MutexUnLock(ClientMutex)							'Mutex Sperren aufheben
End Sub



'##############################################################################################################
Sub TSNE_NewConnectionCanceled(ByVal V_TSNEID as UInteger, ByVal V_IPA as String)
Print "[CLIENT] Request Blocked   IPA:" & V_IPA		'Anzeigen das Verbindungsanfrage Blockiert wurde
End Sub



'##############################################################################################################
Sub TSNE_NewData(ByVal V_TSNEID as UInteger, ByRef V_Data as String)	'Empfänger für neue Daten
Dim RV as Long										'Die Statusrückgabe variable
MutexLock(ClientMutex)								'Mutex Sperren um auf das Array zugreifen zu können
Dim TData as String = ClientD.V_Data & V_Data	'Die eingehenden Daten hängen wir an die bestehenden an udn speichern dies in eine Temporäre Variable
ClientD.V_Data = ""							'Die Bereits vorhandenen Daten werden gelöscht. Sollten noch welche übrig bleiben, beim Parsen können wir diese wieder hinzufügen.
OpBet=Val(TData)				'Wir haben Daten erhalten udn geben diesen Zustand aus.
MutexUnLock(ClientMutex)							'Mutex Sperren aufheben
'*****************************************************************
End Sub

Sub WinCondition
Dim EndGame As Integer		'1-lost, 2-won, 3-draw
If TokenPos=5 Then
	EndGame=2
ElseIf TokenPos=-5 Then
	EndGame=1
EndIf
If MyPool=0 And OpPool>0  Then
	If TokenPos<0 Then
		If Abs(TokenPos)+5<OpPool Then EndGame=2 Else EndGame=3
	ElseIf TokenPos>=0 Then
		If TokenPos+5<OpPool Then EndGame=1 Else EndGame=3
	EndIf
ElseIf OpPool=0 And MyPool>0 Then
	If TokenPos<0 Then
		If Abs(TokenPos)+5<MyPool Then EndGame=2 Else EndGame=3
	ElseIf TokenPos>=0 Then
		If TokenPos-5<MyPool Then EndGame=1 Else EndGame=3
	EndIf
ElseIf MyPool=0 And OpPool=0 Then
	EndGame=3
EndIf
Select Case EndGame
	Case 1
		Color 2,4
		Locate 20,26
		Print "You lost!"
		Sleep
		End
	Case 2
		Color 2,4
		Locate 20,26
		Print "You won!"
		Sleep
		End
	Case 3
		Color 2,4
		Locate 20,26
		Print "Draw!"
		Sleep
		End
End Select
End Sub
pp-client:

Code: Select all

'##############################################################################################################
'TEST-CLIENT für TSNE_V3
'##############################################################################################################



'##############################################################################################################
#include once "TSNE_V3.bi"							'Include TCP Network modul


'*************************************************************************

'*************************************************************************



'##############################################################################################################
Dim G_Client as UInteger							'Create var for the Client-Handel



'##############################################################################################################
'	declarations of each callback routine
Declare Sub	TSNE_Disconnected	(ByVal V_TSNEID as UInteger)
Declare Sub	TSNE_Connected		(ByVal V_TSNEID as UInteger)
Declare Sub	TSNE_NewData		(ByVal V_TSNEID as UInteger, ByRef V_Data as String)

Declare Sub PrintAll()
Declare Sub WinCondition

Dim KeyPressd As String
Dim Shared As Integer MyBet, MyBetSent, OpBet, MyPool=50, OpPool=50, TokenPos
Dim Shared ServNo As UInteger

'##############################################################################################################
Print "[INIT] Client..."							'begin App
Dim BV as Integer									'Var for state return of function calls


'This Function creates a connection to "www.google.de" on port 80.
'xxx_Create_Client automaticle translate the hostname into a valid IP-Adress. U can use a IP-Adress too.
'U can set a Timeout at the end of the Function to define a timeout for the establishing. But 60seconds
'are by default for internet connections. If u work on the local network, u can reduce the value to 10 secons or lower.
'Just experiment whis these value in the local network. But, how i say, for the internet its recommend u use 60 seconds.
'this is intenaly the default value too for this function. So u can ignor this parameter, if u want.
'G_Client is the returning connection-ID what need each TSNE_xxx funtion.
'the @ Parameter are Callacks what TSNE will automaticle call if a state change raised.
'How the name say's, its TSNE_Disconnected a callback for the close-state of the connection
'TSNE_Connected is for a successfully creating this connection
'TSNE_NewData is a Routine if new data avaible.

Print "[Connecting]"
BV = TSNE_Create_Client(G_Client, "127.0.0.1", 12345, @TSNE_Disconnected, @TSNE_Connected, @TSNE_NewData, 60)

'Checking the return value
If BV <> TSNE_Const_NoError Then					'If a error
	Print "[ERROR] " & TSNE_GetGURUCode(BV)		'Print the Human-Readable error message
	End -1											'Terminate app
End If
Print "[OK]"										'Else, it was ok
PrintAll
Do													'Wir poolen den Tastenabfrage
	If MyBetSent=FALSE Then KeyPressd=InKey		'no bet changes after pressing Enter
	Select Case Len (KeyPressd)
		Case 2
			If KeyPressd=Chr(255)+"H" Then		'up
				If MyPool>0 Then
					MyBet+=1
					MyPool-=1
					PrintAll
				EndIf
			ElseIf KeyPressd=Chr(255)+"P" Then			'down
				If MyBet>0 Then
					MyBet-=1
					MyPool+=1
					PrintAll
				EndIf
			EndIf
		Case 1
			If KeyPressd=Chr(13) And MyBet>0 Then			'return
				Dim BV as Integer = TSNE_Data_Send(ServNo, Str(MyBet))
				If BV <> TSNE_Const_NoError Then
					Print "[ERROR] " & TSNE_GetGURUCode(BV)		'Print error
				Else
					MyBetSent=TRUE
				End If
				Sleep 500,1				'I don't know why this is necessary, but otherwise OpBet isn't zeroed, buffer or so?
			EndIf
	End Select
	If OpBet>0 And MyBetSent=TRUE Then
		If OpBet>MyBet Then
			TokenPos-=1
		ElseIf OpBet<MyBet Then
			TokenPos+=1
		Else				'draw
			'print "Draw"
		EndIf
		MyBetSent=FALSE
		OpBet=0
		MyBet=0
		Do While InKey<>"":Loop		'clear the keyboard buffer
		PrintAll
		WinCondition
	EndIf
	Sleep 1, 1										'Kurz warten um die CPU auslastung massiv zu verringern
Loop Until KeyPressd=Chr(27)

Print "[WAIT] ..."
TSNE_WaitClose(G_Client)							'here we wait for the close of the connection
Print "[WAIT] OK"

Print "[END]"
Sleep 5000,1
End													'Terminate app.

Sub PrintAll()
Dim StartY As Integer=12
Locate StartY-3,15
Color 7
Print "        Press Esc to end        "
Locate StartY,20
Print Chr(177,196,197,196,197,196,197,196,197,196,178,196,197,196,197,196,197,196,197,196,177)
Locate StartY+1,20:Print Space(25)
Color 12:Locate StartY+1,30+2*TokenPos:Print Chr(30)
Locate StartY+4,17
Color 7:Print "Your pool: "; Format(MyPool,"00"); "   Your bet: ";
Color 2:Print Chr(24);
Color 7:print " "; Format(MyBet,"00");" ";
Color 2: Print Chr(25)
Color 7
End Sub



'##############################################################################################################
Sub TSNE_Disconnected(ByVal V_TSNEID as UInteger)	'Receiver for Disconnect
'If a connection was closed, this routin will fired.
'We print shortly this state
Print "[DIS]"
'In other cases here we can remove previous created things like allocated memmory for this connection or others
End Sub



'##############################################################################################################
Sub TSNE_Connected(ByVal V_TSNEID as UInteger)		'Receiver for a stable created connection
'Print this success
Print "[CON]"

'Prepare data to send 

'here we use the V_TSNEID so send the data.
'This callback comes from TSNE and TSNE give us the Client-ID of this connection by V_TSNEID.
'So we can use this instead of the G_Client var.
Dim BV as Integer = TSNE_Data_Send(V_TSNEID, "Connected!!")
If BV <> TSNE_Const_NoError Then
	Print "[ERROR] " & TSNE_GetGURUCode(BV)		'Print error
Else: Print "[SEND] OK"
End If
ServNo=V_TSNEID		'for future use?
End Sub



'##############################################################################################################
Sub TSNE_NewData (ByVal V_TSNEID as UInteger, ByRef V_Data as String)	'Receiver for new incomming data
'If new Data is avaible, TSNE will fire this callback and give us the new data in V_Data
'The Client who has sent will identifyd by V_TSNEID.
OpBet=Val(V_Data)
End Sub

Sub WinCondition
Dim EndGame As Integer		'1-lost, 2-won, 3-draw
If TokenPos=5 Then
	EndGame=2
ElseIf TokenPos=-5 Then
	EndGame=1
EndIf
If MyPool=0 And OpPool>0  Then
	If TokenPos<0 Then
		If Abs(TokenPos)+5<OpPool Then EndGame=2 Else EndGame=3
	ElseIf TokenPos>=0 Then
		If TokenPos+5<OpPool Then EndGame=1 Else EndGame=3
	EndIf
ElseIf OpPool=0 And MyPool>0 Then
	If TokenPos<0 Then
		If Abs(TokenPos)+5<MyPool Then EndGame=2 Else EndGame=3
	ElseIf TokenPos>=0 Then
		If TokenPos-5<MyPool Then EndGame=1 Else EndGame=3
	EndIf
ElseIf MyPool=0 And OpPool=0 Then
	EndGame=3
EndIf
Select Case EndGame
	Case 1
		Color 2,4
		Locate 20,26
		Print "You lost!"
		Sleep
		End
	Case 2
		Color 2,4
		Locate 20,26
		Print "You won!"
		Sleep
		End
	Case 3
		Color 2,4
		Locate 20,26
		Print "Draw!"
		Sleep
		End
End Select
End Sub
Post Reply