Visual Studio Archives - SoftUni Global https://softuni.org/tag/visual-studio/ Learn Programming and Start a Developer Job Mon, 17 Oct 2022 06:57:59 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.3 https://softuni.org/wp-content/uploads/2022/04/cropped-SoftUni-Global-Logo-Square-notext-32x32.png Visual Studio Archives - SoftUni Global https://softuni.org/tag/visual-studio/ 32 32 How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/ https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/#respond Thu, 01 Sep 2022 14:15:30 +0000 https://softuni.org/?p=23082 In this edition of the Project Tutorial series, we will create a simple Pong game with C#.

The post How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>

Pong is a two-dimensional sports game that is similar to table tennis. It is one of the earliest video games, first released in 1972. Since then, it has been recreated multiple times in different programming languages. Today, you will learn how to make your own version of the game using simple programming concepts in C#.

Let’s begin.

Creating the Field

First, you need to prepare the field with an upper and a lower border and two rackets. Declare two constants of type int that define the dimensions of the field – fieldWidth and fieldLength. To visualize the upper and the lower border, use the string method Repeat on the fieldTile character variable.

				
					const int fieldLength = 50, fieldWidth = 15;
const char fieldTile = '#';
string line = string.Concat(Enumerable.Repeat(fieldTile, fieldLength));
				
			

Then create the game loop and print the borders on the console. The first line starts from coordinates 0,0 and the second one – 0, fieldWidth(15).

				
					while(true) 
{ 
    Console.SetCursorPosition(0,0);
    Console.WriteLine(line);

    Console.SetCursorPosition(0,fieldWidth);
    Console.WriteLine(line);
}

				
			

Next, make a variable for the rackets’ size – racketLength, for the character used to visualize them – racketTile, and for their positions – leftRacketHeight and rightRacketHeight.

				
					const int racketLength = fieldWidth / 4;
const char racketTile = '|';
            
int leftRacketHeight = 0;
int rightRacketHeight = 0;
				
			

To make the rackets appear on the field,add a for loop in the game loop.

				
					for(int i = 0; i < racketLength; i++)
{
    Console.SetCursorPosition(0, i + 1 + leftRacketHeight);
    Console.WriteLine(racketTile);
    Console.SetCursorPosition(fieldLength - 1, i + 1 + rightRacketHeight);
    Console.WriteLine(racketTile);
}
				
			

Player Movement

Make a loop that will continue until a key is pressed. After the loop, check which key has been pressed using a switch and update the rackets’ positions based on that. Clear the previous positions with another for loop.

				
					while(!Console.KeyAvailable)
{
    
}
           
//Check which key has been pressed
switch(Console.ReadKey().Key)
{
    case ConsoleKey.UpArrow:
    if(rightRacketHeight > 0)
    {
        rightRacketHeight--;
    }
    break;

    case ConsoleKey.DownArrow:
    if(rightRacketHeight < fieldWidth - racketLength - 1)
    {
        rightRacketHeight++;
    }
    break;

    case ConsoleKey.W:
    if(leftRacketHeight > 0)
    {
        leftRacketHeight--;
    }
    break;
    
    case ConsoleKey.S:
    if(leftRacketHeight < fieldWidth - racketLength - 1)
    {
        leftRacketHeight++;
    }
    break;
}

//Clear the rackets’ previous positions
for(int i = 1; i < fieldWidth; i++)             
{
Console.SetCursorPosition(0,i);
Console.WriteLine(" ");
Console.SetCursorPosition(fieldLength - 1,i);
Console.WriteLine(" ");
}
				
			

Adding a Ball

What you need to know about the ball is its coordinates, the character representation on the field, and its direction.

				
					int ballX = fieldLength / 2;
    int ballY = fieldWidth / 2;
    const char ballTile = 'O';

    bool isBallGoingDown = true;
    bool isBallGoingRight = true;
				
			

Let’s go back to the empty while loop that waits for a key to be pressed. It has to update the ball’s position.

				
					while(!Console.KeyAvailable)
{
    Console.SetCursorPosition(ballX, ballY);
    Console.WriteLine(ballTile);
    Thread.Sleep(100); //Adds a timer so that the players have time to react
    
    Console.SetCursorPosition(ballX, ballY);
    Console.WriteLine(" "); //Clears the previous position of the ball
    
    //Update position of the ball
    if(isBallGoingDown)
    {
    ballY++;
    } else
    {
    ballY--;
    }
    if(isBallGoingRight)
    {
    ballX++;
    } else
    {
    ballX--;
    }
}
				
			

However, this code does not limit the movement of the ball to the borders of the field. You need to add more conditions to the same while loop and declare variables to store the players’ points.

				
					int leftPlayerPoints = 0;
int rightPlayerPoints = 0;

				
			
				
					if(ballY == 1 || ballY == fieldWidth - 1)
{
isBallGoingDown = !isBallGoingDown; //Change direction
}

if(ballX == 1)
{
    //Left racket hits the ball and it bounces
   if(ballY >= leftRacketHeight + 1 && ballY <= leftRacketHeight + racketLength) 
   {
       isBallGoingRight = !isBallGoingRight;
   }
   else //Ball goes out of the field; Right player scores
   {
      rightPlayerPoints++;
      ballY = fieldWidth / 2;
      ballX = fieldLength / 2;
      Console.SetCursorPosition(scoreboardX, scoreboardY);
      Console.WriteLine($"{leftPlayerPoints} | {rightPlayerPoints}");
      if(rightPlayerPoints == 10)
      {
          goto outer;
      }
   }
}

if(ballX == fieldLength - 2)
{
    //Right racket hits the ball and it bounces
   if(ballY >= rightRacketHeight + 1 && ballY <= rightRacketHeight + racketLength) 
   {
       isBallGoingRight = !isBallGoingRight;
   }
   else //Ball goes out of the field; Left player scores
   {
      leftPlayerPoints++;
      ballY = fieldWidth / 2;
      ballX = fieldLength / 2;
      Console.SetCursorPosition(scoreboardX, scoreboardY);
      Console.WriteLine($"{leftPlayerPoints} | {rightPlayerPoints}");
      if(leftPlayerPoints == 10)
      {
          goto outer;
      }
       
   }
}
				
			

Scoreboard Visualization

To add a scoreboard, you need variables that store its position.

				
					int scoreboardX = fieldLength / 2 -2;
int scoreboardY = fieldWidth + 1;

				
			

The scoreboard is printed on the console every time a player increases their score. Let’s say the game ends when one of the players reaches 10 points. You need to break out of the game loop with the goto command.

				
					//Left Player
leftPlayerPoints++;
ballY = fieldWidth / 2;
ballX = fieldLength / 2;
Console.SetCursorPosition(scoreboardX, scoreboardY);
Console.WriteLine("${leftPlayerPoints} | {rightPlayerPoints}")

if(leftPlayerPoints == 10)
{
      goto outer;
}

//Right Player
rightPlayerPoints++;
ballY = fieldWidth / 2;
ballX = fieldLength / 2;
Console.SetCursorPosition(scoreboardX, scoreboardY);
Console.WriteLine("${leftPlayerPoints} | {rightPlayerPoints}")
if(rightPlayerPoints == 10)
{
      goto outer;
}

				
			

Outside of the game loop put a marker, clear the console and reset the cursor. Check who the winner is and print the appropriate message.

				
					outer:;
        Console.Clear();
        Console.SetCursorPosition(0,0);
        
        if(rightPlayerPoints == 10)
        {
        Console.WriteLine("Right player won!");
        } 
        else 
        {
        Console.WriteLine("Left player won!");
        }
				
			

If you’ve followed all the steps your project should be finished and working now. You can always adjust the values of the variables. For example, you can make the field bigger or smaller or increase the speed of the ball to make the game more challenging.

To check out the final code and compare it to yours click the link below.

Lesson Topics

In this tutorial we cover the following steps:
  • Creating a Field
  • Implementing Player Movement
  • Adding a Ball
  • Scoreboard Visualization

The post How To Make A Pong Game in C#: Step-by-step Guide [Project Tutorials] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/how-to-make-a-pong-game-in-csharp-guide/feed/ 0
How to Make Our Own Flappy Bird in Unity [Project Tutorials] https://softuni.org/project-tutorials/how-to-make-our-own-flappy-bird-in-unity/ https://softuni.org/project-tutorials/how-to-make-our-own-flappy-bird-in-unity/#respond Tue, 08 Feb 2022 04:58:00 +0000 https://softuni.org/?p=11648 In this article of the Project Tutorial series, we will create a simple Flappy Bird game, using Unity.

The post How to Make Our Own Flappy Bird in Unity [Project Tutorials] appeared first on SoftUni Global.

]]>

In this demo, we will create our own Flappy Bird game using Unity and C#.

  • Unity is, essentially, a well-rounded game engine that truly does simplify game development. While there may be better engines to choose from, learning Unity will only help you grow as a game developer.

For this project, we are using the 2020.3 LTS table release. To create this project you will need to have Unity and Unity Hub installed. You can download them from here. To get the completed project, you can download it from the link below. (Link is available after successful registration)

  • First, we open the Unity Hub and Create a 2D Project.setup-path

  • We create a Sprites folder in the game directory, and we import all the needed images for the game.

  • After we import the needed images, you can see that you have more than one bird. We slice it save it in a new folder called Animations.
  • We set it on the scheme, we can start the application and see if the bird will fall.
  • What we need to do next is create a script for our bird. We create a Bird.cs file in the Assets/Scripts folder. We create methods for the Bird to fly and set boundaries so it cannot fly outside our screen.
				
					using System;
using UnityEngine;

public class Bird : MonoBehaviour
{
    [SerializeField] private Rigidbody2D _rigidbody;
    [SerializeField] private float _force;
    [SerializeField] private float _yBound;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && _rigidbody.position.y < _yBound)
        {
            Flap();
        }
    }

    private void Flap()
    {
        _rigidbody.velocity = Vector2.zero;
        _rigidbody.AddForce(Vector2.up * _force);
    }
}

				
			
  • Now we need to create pipes. We create Upper and Lower pipes. If the bird hits them the game will be over.
  • After we are done we create a MovingObject infinity runner. We need to constantly move the objects to the left. The speed increased by one, for every second that passes. We set boundaries for when the object is destroyed. We attach the script to the pipe. We can check if our scripts work.
				
					using UnityEngine;

public class MovingObject : MonoBehaviour
{
    [SerializeField] private float _speed;
    [SerializeField] private float _xBound;

    private void Update()
    {
        this.transform.position -= Vector3.right * _speed * Time.deltaTime;

        if (this.transform.position.x < _xBound)
        {
            Destroy(this.gameObject);
        }
    }
}
				
			
  • We can move to the spawner script. We create the class in the same scripts folder. We need a prefab to be spawned, and a time interval arrange by 1 axis with a name – _yClamp. If enough time has elapsed, the object will spawn, and the elapsed time will reset.
				
					using System;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    [SerializeField] private GameObject _prefab;
    [SerializeField] private float _time;
    [SerializeField] private float _yClamp;

    private float _elapsedTime;

    private void Update()
    {
        _elapsedTime += Time.deltaTime;

        if (_elapsedTime > _time)
        {
            SpawnObject();

            _elapsedTime = 0f;
        }
    }

    private void SpawnObject()
    {
        float offsetY = UnityEngine.Random.Range(-_yClamp, _yClamp);

        Vector2 pos = new Vector2(this.transform.position.x, this.transform.position.y + offsetY);

        Instantiate(_prefab, pos, Quaternion.identity, this.transform);
    }
}

				
			
  • After we are done we can put the spawner into action.  We create a spawner to spawn pipes, evey 2 seconds in the y-axis.
  • We add the functionality to the ground as well. If we hit play we can see the pipes and ground spawning infinitely.
  • In our next step, we need to make the game end. We add events to the Bird inside the Bird.cs class. As a bonus you can add sounds for different events. With OnCollisionEnter2D, our bird dies and we freeze the time.
				
					    [SerializeField] private AudioSource _audioSource;
    [SerializeField] private AudioClip _flapSound;
    [SerializeField] private AudioClip _hitSound;
    [SerializeField] private AudioClip _scoreSound;
    public static event Action OnDeath;

    private void OnCollisionEnter2D()
    {
        OnDeath?.Invoke();

        _audioSource.PlayOneShot(_hitSound);

        Time.timeScale = 0f;
    }
    
    private void Start()
    {
        Time.timeScale = 1f;
    }

				
			
  • We need to create a button,  which starts our game.

  • We use the Observer Design Pattern and it’s commonly used in game development.
  • We create a new class called UIManager. In our class we add the following play button logic:

				
					    [SerializeField] private GameObject _playButton;
    [SerializeField] private TMP_Text _score;

    private void Awake()
    {
        Bird.OnDeath += OnGameOver;
    }
    
    
    private void OnDestroy()
    {
        Bird.OnDeath -= OnGameOver;
    }

    public void RestartGame() => SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

    private void OnGameOver() => _playButton.SetActive(true);


				
			
  • What we need to do is create a text mesh for the score on our screen. In the Bird class, we add functionality so that the score will change. The OnTrigger event will trigger and play a sound.
				
					public static event Action OnScore;

    private void OnTriggerEnter2D()
    {
        OnScore?.Invoke();

        _audioSource.PlayOneShot(_scoreSound);
    }
				
			
  • In the UI Manager we also need to add the functionality for the score. Each time the bird passes a pipe depending on the state we will get Awake() or OnDestroy() event. We increment the current number of the score when the score increases.
				
					private void Awake()
{
    Bird.OnDeath += OnGameOver;
    Bird.OnScore += OnScore;
}
    
private void OnDestroy()
{
    Bird.OnDeath -= OnGameOver;
    Bird.OnScore -= OnScore;
}
private void OnScore() => _score.text = (int.Parse(_score.text) + 1).ToString();
				
			

final-look-app

If we followed all the steps as shown in the video tutorial, our project should be working. What you learned in this tutorial will work for most of your projects in any engine. Unity‘s pipeline is smooth, yet complex. Unity is, simply put, the world’s most popular game engine. It packs a lot of features together and is flexible enough to make almost any game you can imagine. Unity packs tools for 2D and 3D game development.

Lesson Topics

In this tutorial we cover the following steps:
  • Project Creation
  • Project Setup
  • Creating a Bird
  • Adding the Bird Script
  • Prefabs
  • Adding Moving Object
  • Defining Spawner
  • Setup Spawners Usage
  • Implementing Game Over Feature
  • Adding Score
  • Adding SFX
  • Testing Project

The post How to Make Our Own Flappy Bird in Unity [Project Tutorials] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/how-to-make-our-own-flappy-bird-in-unity/feed/ 0