Bladeren bron

Code enhancements for mono pong demo.

- Use pattern matching instead of check-and-cast.
- Rename constants to fit the usual c# code-style.
Andreas Haas 7 jaren geleden
bovenliggende
commit
111c0d4eee
4 gewijzigde bestanden met toevoegingen van 9 en 12 verwijderingen
  1. 3 3
      mono/monkey_pong/Ball.cs
  2. 1 2
      mono/monkey_pong/CeilingFloor.cs
  3. 4 5
      mono/monkey_pong/Paddle.cs
  4. 1 2
      mono/monkey_pong/Wall.cs

+ 3 - 3
mono/monkey_pong/Ball.cs

@@ -3,10 +3,10 @@ using System;
 
 public class Ball : Area2D
 {
-    private const int BALL_SPEED = 100;
+    private const int BallSpeed = 100;
 
     private Vector2 direction = new Vector2(-1, 0);
-    private int speed = BALL_SPEED;
+    private int speed = BallSpeed;
 
     private Vector2 initialPos;
 
@@ -22,7 +22,7 @@ public class Ball : Area2D
     public void Reset()
     {
         SetPosition(initialPos);
-        speed = BALL_SPEED;
+        speed = BallSpeed;
         direction = new Vector2(-1, 0);
     }
 

+ 1 - 2
mono/monkey_pong/CeilingFloor.cs

@@ -8,9 +8,8 @@ public class CeilingFloor : Area2D
 
     public void OnAreaEntered(Area2D area)
     {
-        if (area is Ball)
+        if (area is Ball ball)
         {
-            Ball ball = (Ball)area;
             ball.SetDirection(ball.GetDirection() + new Vector2(0, yDirection));
         }
     }

+ 4 - 5
mono/monkey_pong/Paddle.cs

@@ -6,7 +6,7 @@ public class Paddle : Area2D
     [Export]
     private int ballDir = 1;
 
-    private const int MOVE_SPEED = 100;
+    private const int MoveSpeed = 100;
 
     public override void _Process(float delta)
     {
@@ -16,23 +16,22 @@ public class Paddle : Area2D
         if (Input.IsActionPressed(which + "_move_up") && GetPosition().y > 0)
         {
             Vector2 pos = GetPosition();
-            pos.y -= MOVE_SPEED * delta;
+            pos.y -= MoveSpeed * delta;
             SetPosition(pos);
         }
         if (Input.IsActionPressed(which + "_move_down") && GetPosition().y < GetViewportRect().Size.y)
         {
             Vector2 pos = GetPosition();
-            pos.y += MOVE_SPEED * delta;
+            pos.y += MoveSpeed * delta;
             SetPosition(pos);
         }
     }
 
     public void OnAreaEntered(Area2D area)
     {
-        if (area is Ball)
+        if (area is Ball ball)
         {
             // Assign new direction
-            Ball ball = (Ball)area;
             ball.SetDirection(new Vector2(ballDir, (float)new Random().NextDouble() * 2 - 1).normalized());
         }
     }

+ 1 - 2
mono/monkey_pong/Wall.cs

@@ -5,10 +5,9 @@ public class Wall : Area2D
 {
     public void OnWallAreaEntered(Area2D area)
     {
-        if (area is Ball)
+        if (area is Ball ball)
         {
             // Oops, ball went out of game place, reset
-            Ball ball = (Ball)area;
             ball.Reset();
         }
     }