Pong.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Godot;
  2. using System;
  3. public partial class Pong : Node2D
  4. {
  5. [Signal]
  6. private delegate void GameFinished(string withError);
  7. private const int ScoreToWin = 10;
  8. private int _scoreLeft = 0;
  9. private int _scoreRight = 0;
  10. private Paddle _playerTwo;
  11. private Label _scoreLeftNode;
  12. private Label _scoreRightNode;
  13. private Label _winnerLeft;
  14. private Label _winnerRight;
  15. public override void _Ready()
  16. {
  17. // Get nodes. The generic is the class, argument is path to the node.
  18. _playerTwo = GetNode<Paddle>("Player2");
  19. _scoreLeftNode = GetNode<Label>("ScoreLeft");
  20. _scoreRightNode = GetNode<Label>("ScoreRight");
  21. _winnerLeft = GetNode<Label>("WinnerLeft");
  22. _winnerRight = GetNode<Label>("WinnerRight");
  23. // By default, all nodes in server inherit from master,
  24. // while all nodes in clients inherit from puppet.
  25. // SetNetworkMaster is tree-recursive by default.
  26. if (GetTree().IsNetworkServer())
  27. {
  28. _playerTwo.SetNetworkMaster(GetTree().GetNetworkConnectedPeers()[0]);
  29. }
  30. else
  31. {
  32. _playerTwo.SetNetworkMaster(GetTree().GetNetworkUniqueId());
  33. }
  34. GD.Print("Unique id: ", GetTree().GetNetworkUniqueId());
  35. }
  36. [Sync]
  37. private void UpdateScore(bool addToLeft)
  38. {
  39. if (addToLeft)
  40. {
  41. _scoreLeft += 1;
  42. _scoreLeftNode.Text = _scoreLeft.ToString();
  43. }
  44. else
  45. {
  46. _scoreRight += 1;
  47. _scoreRightNode.Text = _scoreRight.ToString();
  48. }
  49. var gameEnded = false;
  50. if (_scoreLeft == ScoreToWin)
  51. {
  52. _winnerLeft.Show();
  53. gameEnded = true;
  54. }
  55. else if (_scoreRight == ScoreToWin)
  56. {
  57. _winnerRight.Show();
  58. gameEnded = true;
  59. }
  60. if (gameEnded)
  61. {
  62. GetNode<Button>("ExitGame").Show();
  63. GetNode<Ball>("Ball").Rpc("Stop");
  64. }
  65. }
  66. private void OnExitGamePressed()
  67. {
  68. EmitSignal(nameof(GameFinished), "");
  69. }
  70. }