You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This class defines everything a player object can do and know.
1.1 Define required variables, fields and properties.
publicintScore{get;set;}=0;publicstringName{get;set;}publicdoubleX{get;privateset;}publicdoubleY{get;privateset;}publicdoubleRadius{get;set;}=10;publicCirclec;//For collision circle purposeprivateColorPlayerColor;privateintBoost=0;privateintSpeed=5;privateboolPlayerWrapAroundTheWindow=false;//Wrap around or stop at the edge of the windowprivateint_NameWidth;privateSoundEffectGoodSound=newSoundEffect("pop","pop.wav");//When eat smaller onesprivateSoundEffectBadSound=newSoundEffect("beep","beep.wav");//When bitten by bigger onespublicboolQuit{get;privateset;}
1.2 Create class constructor
//Player object need to know which window to draw on and remeber its own namepublicPlayer(Window gameWindow,string name){//Place the player object at the center of the screen.X=gameWindow.Width/2;Y=gameWindow.Height/2;Name=name;//Give the player object a random color using RandomRGBColor from SplashKitPlayerColor=SplashKit.RandomRGBColor(200);//Set width of name, so that we can align the name and player object in middle vertically_NameWidth=SplashKit.TextWidth(name,"Arial",10);}
1.3 Create the rest of the class
//Draw the player object on the game windowpublicvoidDraw(){SplashKit.FillCircle(PlayerColor,X,Y,Radius);//Draw the player object with random colorc=SplashKit.CircleAt(X,Y,Radius);//Draw circle for used of collision SplashKit.DrawText(Name,Color.Black,X-_NameWidth/2,Y-Radius-8);//Display NameSplashKit.DrawText(Convert.ToString(Score),Color.Black,X-3,Y+Radius);//Display score}//Process input from the keyboard for controlling the player object in the game//E.g. move the player with WASD keyspublicvoidHandleInput(){if(SplashKit.KeyReleased(SplashKitSDK.KeyCode.IKey)){if(Boost<=5){Boost++;if(Boost>=6){Boost=1;}}switch(Boost){case1:Speed=5;break;case2:Speed=10;break;case3:Speed=15;break;case4:Speed=20;break;case5:Speed=50;break;}}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.EscapeKey)){Quit=true;}if(SplashKit.QuitRequested()){Quit=true;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.LeftKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.AKey)){X-=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.RightKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.DKey)){X+=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.UpKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.WKey)){Y-=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.DownKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.SKey)){Y+=Speed;}}//Player will stay on the window or wrap around the windowpublicvoidStayOnWindow(WindowgameWindow){intwindowWidth=gameWindow.Width;intwindowHeight=gameWindow.Height;if(!PlayerWrapAroundTheWindow){//Player stops at Boundaryif(X-Radius<=0){X=Radius;}if(X+Radius>=(windowWidth)){X=windowWidth-Radius;}if(Y-Radius<=0){Y=Radius;}if(Y+Radius>=windowHeight){Y=windowHeight-Radius;}//Player stops at Boundary}else{//Player wrap around the screenif(X+Radius<0){X=windowWidth;}if(X>windowWidth){X=-Radius;}if(Y+Radius<0){Y=windowHeight;}if(Y>windowHeight){Y=-Radius;}//Player wrap around the screen}}//Return true if the circle of Player object intersect with Random dotspublicboolCollidedWithRandomDots(RandomDotsrandomDots){returnSplashKit.CirclesIntersect(c,randomDots.CollisionCircle);}//Return true if two players collided (Two local players in local game without network)publicboolCollidedWithPlayer(Playerplayer){//TODO: change it, make it workreturnfalse;}//Collided with player from the networkpublicboolCollidedWithPlayer(OtherPlayerop){returnSplashKit.CirclesIntersect(c,op.CollisionCircle);}//Play the pop sound when eat smaller dotspublicvoidPlayGoodSound(){GoodSound.Play();}//Play the beep sound when bitten by bigger dotspublicvoidPlayBadSound(){BadSound.Play();}
1.4 Complete code
usingSystem;usingSplashKitSDK;publicclassPlayer{publicintScore{get;set;}=0;publicstringName{get;set;}publicdoubleX{get;privateset;}publicdoubleY{get;privateset;}publicdoubleRadius{get;set;}=10;publicCirclec;privateColorPlayerColor;privateintBoost=0;privateintSpeed=5;privateboolPlayerWrapAroundTheWindow=false;privateint_NameWidth;privateSoundEffectGoodSound=newSoundEffect("pop","pop.wav");privateSoundEffectBadSound=newSoundEffect("beep","beep.wav");publicPlayer(WindowgameWindow,stringname){X=gameWindow.Width/2;Y=gameWindow.Height/2;Name=name;PlayerColor=SplashKit.RandomRGBColor(200);_NameWidth=SplashKit.TextWidth(name,"Arial",10);}publicvoidDraw(){SplashKit.FillCircle(PlayerColor,X,Y,Radius);c=SplashKit.CircleAt(X,Y,Radius);SplashKit.DrawText(Name,Color.Black,X-_NameWidth/2,Y-Radius-8);SplashKit.DrawText(Convert.ToString(Score),Color.Black,X-3,Y+Radius);}publicboolQuit{get;privateset;}publicvoidHandleInput(){if(SplashKit.KeyReleased(SplashKitSDK.KeyCode.IKey)){if(Boost<=5){Boost++;if(Boost>=6){Boost=1;}}switch(Boost){case1:Speed=5;break;case2:Speed=10;break;case3:Speed=15;break;case4:Speed=20;break;case5:Speed=50;break;}}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.EscapeKey)){Quit=true;}if(SplashKit.QuitRequested()){Quit=true;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.LeftKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.AKey)){X-=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.RightKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.DKey)){X+=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.UpKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.WKey)){Y-=Speed;}if(SplashKit.KeyDown(SplashKitSDK.KeyCode.DownKey)||SplashKit.KeyDown(SplashKitSDK.KeyCode.SKey)){Y+=Speed;}}publicvoidStayOnWindow(WindowgameWindow){intwindowWidth=gameWindow.Width;intwindowHeight=gameWindow.Height;if(!PlayerWrapAroundTheWindow){//Player stops at Boundaryif(X-Radius<=0){X=Radius;}if(X+Radius>=(windowWidth)){X=windowWidth-Radius;}if(Y-Radius<=0){Y=Radius;}if(Y+Radius>=windowHeight){Y=windowHeight-Radius;}//Player stops at Boundary}else{//Player wrap around the screenif(X+Radius<0){X=windowWidth;}if(X>windowWidth){X=-Radius;}if(Y+Radius<0){Y=windowHeight;}if(Y>windowHeight){Y=-Radius;}//Player wrap around the screen}}publicboolCollidedWithRandomDots(RandomDotsrandomDots){returnSplashKit.CirclesIntersect(c,randomDots.CollisionCircle);}publicboolCollidedWithPlayer(Playerplayer){//TODO: change it, make it workreturnfalse;}publicboolCollidedWithPlayer(OtherPlayerop){returnSplashKit.CirclesIntersect(c,op.CollisionCircle);}publicvoidPlayGoodSound(){GoodSound.Play();}publicvoidPlayBadSound(){BadSound.Play();}}
2. OtherPlayer.cs
This class defines everything an OtherPlayer object can do and know, this class will be used for showing the object and status of the player from the other end of the network
2.1 Define required variables, fields and properties.
//The variables and properties for other players is very similar with player class since they almost perform similar roles, other player class do not have HandleInput method since it's controlled by the other player over the network, in the future abstract class can be introduced to further optimize the codepublicstringName{get;set;}publicdoubleX{get;set;}publicdoubleY{get;set;}publicintScore{get;set;}=0;publicdoubleRadius{get;set;}=10;privateColorPlayerColor;privateint_NameWidth;publicCircleCollisionCircle{get{returnSplashKit.CircleAt(X,Y,Radius);}}
2.2 Create class constructor
//Player object need to know which window to draw on, its name, color, score, radius, and positoinpublicOtherPlayer(string name,double x,double y,double radius,int score,Color color){Name=name;X=x;Y=y;Radius=radius;PlayerColor=color;Score=score;_NameWidth=SplashKit.TextWidth(name,"Arial",10);}
2.3 Create the rest of the class
//Like player class, it can draw itself, but it has less code as mentioned previously, this is it for OtherPlayer classpublicvoidDraw(){SplashKit.FillCircle(PlayerColor,X,Y,Radius);SplashKit.DrawText(Name,Color.Red,X-_NameWidth/2,Y-Radius-8);SplashKit.DrawText(Convert.ToString(Score),Color.Black,X-3,Y+Radius);}
This class defines everything a random dot object can do and know and its properties
3.1 Define required variables, fields and properties.
//Similarly, the random dots have X,Y for position purpose, radius for the size of the dot, and color for different appearancepublicdoubleX{get;set;}publicdoubleY{get;set;}publicdoubleRadius{get;set;}publicColorMainColor;//Define the collision circle which will be used to determin collision between player and random dotspublicCircleCollisionCircle{get{returnSplashKit.CircleAt(X,Y,Radius);}}
3.2 Create class constructor
//To create a random dot, it needs to know the window width and height in order to draw within the window, it also needs to know the radius so that it can draw in different sizepublicRandomDots(Window gameWindow,double radius){MainColor=Color.RandomRGB(200);Radius=radius;//RdnInclusive is a staic method in Function class we created for returning number with given range inclusively, it will be discussed in section 4X=Function.RdnInclusive(1,gameWindow.Width-10);Y=Function.RdnInclusive(1,gameWindow.Height-10);}
3.3 Create the rest of the class
//Again, it will draw on screen once this Draw() method been calledpublicvoidDraw(){SplashKit.FillCircle(MainColor,X,Y,Radius);}
This static class stores function/method that does not belong to any classes but will be used in more than one classes, in this case it is RdnInclusive function which metioned in section 3
4.1 Complete code
usingSystem;publicstaticclassFunction{publicstaticintRdnInclusive(intmin,intmax){Randomrnd=newRandom();//E.g. min = 1, max = 5, returned number will be between 1 and 5 including 1 and 5inttmp=rnd.Next(min,max+1);returntmp;}}
5. Network.cs
This class contains everything we need for processing networking related tasks, only used when choose to play online game (Slightly modified based on Andrew's Chat program example)
5.1 Complete code
usingSystem;usingSplashKitSDK;usingSystem.Collections.Generic;publicclassGamePeer{publicstringName{get;set;}privateServerSocket_server;privateDictionary<string,Connection>_peers=newDictionary<string,Connection>();publicstringGetMsg{get;privateset;}publicServerSocketServer{get{return_server;}}publicGamePeer(ushortport){_server=newServerSocket("GameServer",port);}publicvoidConnectToGamePeer(stringaddress,ushortport){ConnectionnewConnection=newConnection($"{address }:{port}",address,port);if(newConnection.IsOpen){Console.WriteLine($"Conected to {address}:{port}");}}privatevoidEstablishConnection(Connectioncon){// Send my name...con.SendMessage(Name);// Wait for a message...SplashKit.CheckNetworkActivity();for(inti=0;i<10&&!con.HasMessages;i++){//SplashKit.Delay(200);SplashKit.CheckNetworkActivity();}if(!con.HasMessages){con.Close();thrownewException("Timeout waiting for name of peer");}// Read the namestringname=con.ReadMessageData();// See if we can register this...if(_peers.ContainsKey(name)){con.Close();thrownewException("Unable to connect to multiple peers with the same name");}// Register_peers[name]=con;Console.WriteLine($"Connected to {name} at {SplashKit.Ipv4ToStr(con.IP) }:{con.Port}");}//Check if there is new connectionpublicvoidCheckNewConnections(){while(_server.HasNewConnections){ConnectionnewConnection=_server.FetchNewConnection();try{EstablishConnection(newConnection);}catch{// ignore errors}}}//Broadcast message to everyone who connected to serverpublicvoidBroadcast(stringmessage){SplashKit.BroadcastMessage(message);}//Get message sent by peer over the networkpublicstringGetNewMessages(){SplashKit.CheckNetworkActivity();while(SplashKit.HasMessages()){using(Messagem=SplashKit.ReadMessage()){GetMsg=m.Data;}}returnGetMsg;}//Close the connection properlypublicvoidClose(){_server.Close();SplashKit.CloseAllConnections();}}
6. Game.cs
This class will handle the logic of the whole game, including local game and multiplayer networked game
6.1 Define required variables, fields and properties.
privatePlayer_player;privateWindow_gameWindow;//For storing instantized random dots objectprivateList<RandomDots>_randomDots=newList<RandomDots>();publicboolOnlineGame{get;privateset;}//Onlin/Offline game switcherpublicboolIsServer{get;privateset;}//The game is host (server) or clientpublicGamePeerThisPeer{get;privateset;}//For network usageprivatestring_otherPlayerMsg;//Store message received over networkprivateList<OtherPlayer>_otherPlayers=newList<OtherPlayer>();//Store OtherPlayer objects//Store name of the other player over the networkprivateList<string>_otherNetworkNames=newList<string>();//Maximum number of random dots on screen, avoid screen covered by random dotsprivateintNumOfRandomDotsOnScreen=15;privatestringname="";//Store name of the current playerprivatedoublex=0,y=0,radius=0;//Store position and radius information of OtherPlayerprivateintscore=0;//Store score of OtherPlayerprivateSoundEffectbgm=newSoundEffect("bgm","bgm.wav");//Background music for the game//If the current Player quit the game, then return truepublicboolQuit{get{return_player.Quit;}}
6.2 Create class constructor
//The game needs to know, where to draw objects like player, otherplayer random dots etcpublicGame(Window window){//Before starting the game, we need to know a couple of things from the user//Name of the userstringanswer;Console.Write("What is your name: ");stringname=Console.ReadLine();//Online or offline gamedo{Console.Write("Do you want to play it online? (Y/N) ");answer=Console.ReadLine();}while(answer.ToUpper()!="Y"&&answer.ToUpper()!="N");if(answer.ToUpper()=="N")// Not online game, offline game{OnlineGame=false;}elseif(answer.ToUpper()=="Y")// Online game{OnlineGame=true;Console.Write("Which port to run at: ");ushortport=Convert.ToUInt16(Console.ReadLine());GamePeerpeer=newGamePeer(port){Name=name};ThisPeer=peer;//This is the host/server for the game or clientstringisHost;do{Console.Write("Is this the host? (Y/N) ");isHost=Console.ReadLine();}while(isHost.ToUpper()!="Y"&&isHost.ToUpper()!="N");if(isHost.ToUpper()=="N")// Not host server, select server to connect to{IsServer=false;MakeNewConnection(peer);}elseif(isHost.ToUpper()=="Y")// Be the host server{IsServer=true;}}//After we gathered enough information, initialize the game and objects that needs to be created _gameWindow=window;PlayerPlayer=newPlayer(window,name);_player=Player;Console.WriteLine("Please switch back to game window!");}
6.3 Create the rest of the class
//Handle all inputs, in this case inputs from playerpublicvoidHandleInput(){_player.HandleInput();_player.StayOnWindow(_gameWindow);}//Draw player, OtherPlayer and random dot objects on the windowpublicvoidDraw(){_player.Draw();//Only draw if there are otherplayer existif(_otherPlayers.Count>0){foreach(OtherPlayeropin_otherPlayers){op.Draw();}}//Only draw if there are random dots existif(_randomDots.Count>0){foreach(RandomDotsrdin_randomDots){rd.Draw();}}}//Update the gamepublicvoidUpdate(){//If this is an online game, update network information, including get information of otherplayer//and broadcast informtion of current player over networkif(OnlineGame){UpdateNetworkInfo();UpdateOtherPlayerInfo();}//Check if there is any collisions between player, otherplayer and random dotsCheckCollisions();//If random dots on screen is less than pre-set value, add more.if(_randomDots.Count<NumOfRandomDotsOnScreen){//In order to make the game playable, there must be some smaller dots available//so that player can eat and grow bigger following code is to determine if new//smaller dots needs to be createdinttmp_small=0;for(inti=0;i<_randomDots.Count-1;i++){if(_randomDots[i].Radius<_player.Radius){tmp_small++;}}if(tmp_small<=2){//Use RdnInclusive we've created previously, we are able to create dots with various//radius/size but still smaller than player's size, so that player can eat and grow_randomDots.Add(newRandomDots(_gameWindow,Function.RdnInclusive(3,Convert.ToInt32(_player.Radius-2))));}else{do{//If there are dots smaller than player, then create bigger sized random dots_randomDots.Add(newRandomDots(_gameWindow,Function.RdnInclusive(Convert.ToInt32(_player.Radius+1),Convert.ToInt32(_player.Radius+20))));}while(_randomDots.Count<NumOfRandomDotsOnScreen);}}//Play the background music in a non-stop fashionif(!bgm.IsPlaying){PlayBgm();}}//Check collisions between player, otherplayer and random dotsprivatevoidCheckCollisions(){//This list will store all random dots which are ready to be removedList<RandomDots>rmRandomDots=newList<RandomDots>();foreach(OtherPlayeropin_otherPlayers){//If player collided with otherlayer, whoever is bigger gets more score//deduct the score of the other oneif(_player.CollidedWithPlayer(op)){if(_player.Radius<op.Radius){_player.Score--;}elseif(_player.Radius>op.Radius){_player.Score++;}}}//If player collided with random dots, if player is bigger than the dot, then player will//gain some score, if player is smaller than the dot, player will lose some score//If player collided with bigger dots a beep will sound, if collided with smaller dots//a pop will soundforeach(RandomDotsrdin_randomDots){if(_player.CollidedWithRandomDots(rd)){rmRandomDots.Add(rd);if(rd.Radius>_player.Radius){_player.PlayBadSound();if(_player.Radius-5>5){_player.Radius-=5;}_player.Score-=10;}elseif(rd.Radius<_player.Radius){_player.PlayGoodSound();_player.Score+=10;_player.Radius+=1;}}}//Remove those dots which player collided withif(_randomDots.Count>0){foreach(RandomDotsrdinrmRandomDots){_randomDots.Remove(rd);}}}//Method to play the background musicpublicvoidPlayBgm(){bgm.Play();}//Network related part
#region Network, OtherPlayer
//Process received message from network and broadcast message about current player's position//name, color informationpublicvoidUpdateNetworkInfo(){if(IsServer){//If this is the server, then listen on new incoming connectionSplashKit.AcceptAllNewConnections();}_otherPlayerMsg=ThisPeer.GetNewMessages();UpdateOtherPlayer();BroadcastMessage();}//Process received message over network, and apply to otherplayer objectpublicvoidUpdateOtherPlayer(){if(_otherPlayerMsg!=null&&_otherPlayerMsg.Length>0){name=_otherPlayerMsg.Split(',')[0];x=Convert.ToDouble(_otherPlayerMsg.Split(',')[1]);y=Convert.ToDouble(_otherPlayerMsg.Split(',')[2]);radius=Convert.ToDouble(_otherPlayerMsg.Split(',')[3]);score=Convert.ToInt32(_otherPlayerMsg.Split(',')[4]);}if(name.Length>0){if(!_otherNetworkNames.Contains(name)){_otherNetworkNames.Add(name);_otherPlayers.Add(newOtherPlayer(name,x,y,radius,score,Color.Gray));}}}//Update otherplayer object's position, size and score information, so that otherplayer will//appear on our screen and reflect what the the other user's status on our sidepublicvoidUpdateOtherPlayerInfo(){foreach(OtherPlayeropin_otherPlayers){op.X=x;op.Y=y;op.Radius=radius;op.Score=score;}}//Broadcast current player's name, X,Y, radius, and score information//Modified based on [Andrew](https://github.com/macite)'s Chat program exampleprivatevoidBroadcastMessage(){ThisPeer.Broadcast($"{_player.Name},{_player.X},{_player.Y},{_player.Radius},{_player.Score}");}//Make coneciton to game peer (host/server)privatevoidMakeNewConnection(GamePeerpeer){stringaddress;ushortport;Console.Write("Enter Host Server address: ");address=Console.ReadLine();Console.Write("Enter Host Server port: ");port=Convert.ToUInt16(Console.ReadLine());peer.ConnectToGamePeer(address,port);}
#endregion
6.4 Complete code
usingSplashKitSDK;usingSystem;usingSystem.Collections.Generic;publicclassGame{privatePlayer_player;privateWindow_gameWindow;privateList<RandomDots>_randomDots=newList<RandomDots>();publicboolOnlineGame{get;privateset;}publicboolIsServer{get;privateset;}publicGamePeerThisPeer{get;privateset;}privatestring_otherPlayerMsg;privateList<OtherPlayer>_otherPlayers=newList<OtherPlayer>();privateList<string>_otherNetworkNames=newList<string>();privateintNumOfRandomDotsOnScreen=15;privatestringname="";privatedoublex=0,y=0,radius=0;privateintscore=0;privateSoundEffectbgm=newSoundEffect("bgm","bgm.wav");publicboolQuit{get{return_player.Quit;}}publicGame(Windowwindow){stringanswer;Console.Write("What is your name: ");stringname=Console.ReadLine();do{Console.Write("Do you want to play it online? (Y/N) ");answer=Console.ReadLine();}while(answer.ToUpper()!="Y"&&answer.ToUpper()!="N");if(answer.ToUpper()=="N")// Not online game, offline game{OnlineGame=false;}elseif(answer.ToUpper()=="Y")// Online game{OnlineGame=true;Console.Write("Which port to run at: ");ushortport=Convert.ToUInt16(Console.ReadLine());GamePeerpeer=newGamePeer(port){Name=name};ThisPeer=peer;stringisHost;do{Console.Write("Is this the host? (Y/N) ");isHost=Console.ReadLine();}while(isHost.ToUpper()!="Y"&&isHost.ToUpper()!="N");if(isHost.ToUpper()=="N")// Not host server, select server to connect to{IsServer=false;MakeNewConnection(peer);}elseif(isHost.ToUpper()=="Y")// Be the host server{IsServer=true;}}_gameWindow=window;PlayerPlayer=newPlayer(window,name);_player=Player;Console.WriteLine("Please switch back to game window!");}publicvoidHandleInput(){_player.HandleInput();_player.StayOnWindow(_gameWindow);}publicvoidDraw(){_player.Draw();if(_otherPlayers.Count>0){foreach(OtherPlayeropin_otherPlayers){op.Draw();}}if(_randomDots.Count>0){foreach(RandomDotsrdin_randomDots){rd.Draw();}}}publicvoidUpdate(){if(OnlineGame){UpdateNetworkInfo();UpdateOtherPlayerInfo();}CheckCollisions();if(_randomDots.Count<NumOfRandomDotsOnScreen){inttmp_small=0;for(inti=0;i<_randomDots.Count-1;i++){if(_randomDots[i].Radius<_player.Radius){tmp_small++;}}if(tmp_small<=2){_randomDots.Add(newRandomDots(_gameWindow,Function.RdnInclusive(3,Convert.ToInt32(_player.Radius-2))));}else{do{_randomDots.Add(newRandomDots(_gameWindow,Function.RdnInclusive(Convert.ToInt32(_player.Radius+1),Convert.ToInt32(_player.Radius+20))));}while(_randomDots.Count<NumOfRandomDotsOnScreen);}}if(!bgm.IsPlaying){PlayBgm();}}privatevoidCheckCollisions(){List<RandomDots>rmRandomDots=newList<RandomDots>();foreach(OtherPlayeropin_otherPlayers){if(_player.CollidedWithPlayer(op)){if(_player.Radius<op.Radius){_player.Score--;}elseif(_player.Radius>op.Radius){_player.Score++;}}}foreach(RandomDotsrdin_randomDots){if(_player.CollidedWithRandomDots(rd)){rmRandomDots.Add(rd);if(rd.Radius>_player.Radius){_player.PlayBadSound();if(_player.Radius-5>5){_player.Radius-=5;}_player.Score-=10;}elseif(rd.Radius<_player.Radius){_player.PlayGoodSound();_player.Score+=10;_player.Radius+=1;}}}if(_randomDots.Count>0){foreach(RandomDotsrdinrmRandomDots){_randomDots.Remove(rd);}}}publicvoidPlayBgm(){bgm.Play();}
#region Network, OtherPlayer
publicvoidUpdateNetworkInfo(){if(IsServer){SplashKit.AcceptAllNewConnections();}_otherPlayerMsg=ThisPeer.GetNewMessages();UpdateOtherPlayer();BroadcastMessage();}publicvoidUpdateOtherPlayer(){if(_otherPlayerMsg!=null&&_otherPlayerMsg.Length>0){name=_otherPlayerMsg.Split(',')[0];x=Convert.ToDouble(_otherPlayerMsg.Split(',')[1]);y=Convert.ToDouble(_otherPlayerMsg.Split(',')[2]);radius=Convert.ToDouble(_otherPlayerMsg.Split(',')[3]);score=Convert.ToInt32(_otherPlayerMsg.Split(',')[4]);}if(name.Length>0){if(!_otherNetworkNames.Contains(name)){_otherNetworkNames.Add(name);_otherPlayers.Add(newOtherPlayer(name,x,y,radius,score,Color.Gray));}}}publicvoidUpdateOtherPlayerInfo(){foreach(OtherPlayeropin_otherPlayers){op.X=x;op.Y=y;op.Radius=radius;op.Score=score;}}privatevoidBroadcastMessage(){ThisPeer.Broadcast($"{_player.Name},{_player.X},{_player.Y},{_player.Radius},{_player.Score}");}privatevoidMakeNewConnection(GamePeerpeer){stringaddress;ushortport;Console.Write("Enter Host Server address: ");address=Console.ReadLine();Console.Write("Enter Host Server port: ");port=Convert.ToUInt16(Console.ReadLine());peer.ConnectToGamePeer(address,port);}
#endregion
}
7. Player.cs
This class is the entry point of the program
7.1 Complete code
usingSplashKitSDK;publicclassProgram{publicstaticvoidMain(){//Create new window object for drawing game objects onWindowgameWindow=newWindow("Big Eat Small",900,900);//Create the gameGamegame=newGame(gameWindow);//Start the game loop, until player requested to quitdo{SplashKit.ProcessEvents();gameWindow.Clear(Color.AliceBlue);game.HandleInput();game.Update();game.Draw();gameWindow.Refresh(60);}while(!game.Quit);}}
Results
About
Guide to create a simple multiplayer networked game with SplashKit