Struggling with Classes

I am struggling to make use of classes in my coding, as I am new to C#. I’m trying to make a function that effectively says A += B; in a separate Class (Scoring) and when I run the game the changes aren’t showing up in the text. Here’s what I have right now. I’m not sure how formatting works either so if someone could tell me that would be great.

'public class Game1 : Game
{
KeyboardState state = Keyboard.GetState();
private KeyboardState oldState;

    private GraphicsDeviceManager graphics;
    private SpriteBatch spriteBatch;
    public SpriteFont font;

    public int score;
    public int multiplier;        

    Scoring Scoring = new Scoring();

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {
        score = 0;
        multiplier = 1;
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        font = Content.Load<SpriteFont>("File");
    }

    protected override void Update(GameTime gameTime)
    {
        KeyboardState newState = Keyboard.GetState();

        if (oldState.IsKeyUp(Keys.Q) && newState.IsKeyDown(Keys.Q ))
        {
            // It's not adding 1 every time I press Q
            Scoring.Add(score, multiplier);
             
        }
        if (newState.IsKeyDown(Keys.W) && score >= 100)
        {
            // You pay 100 score to get an extra multiplier, though what happens is you don't actually get it
            score -= 100;
            Scoring.Add(multiplier, 1);
        }

        oldState = newState;    
        
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Wheat);

        spriteBatch.Begin();
        spriteBatch.DrawString(font, score.ToString(), new Vector2(100,100), Color.Black);
        spriteBatch.DrawString(font, multiplier.ToString(), new Vector2(100, 150), Color.Black);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

public class Scoring
{
    public void Add(int A, int B) 
    {
        A += B;   
    }
}'

You need to declare member variables in your Scoring class. At the moment you only calculate the values in the Add method but you don’t save them.

Can you explain? I’m still new to C# and don’t know how to do that.

public class Scoring
{
    public int Score = 0;
    public void Add(int A, int B) 
    {
        Score = A + B;   
    }
}'

1 Like

Thanks!

Hey @Platydactyl and welcome to the monogame community!

The reason that your score integer doesn’t change when you pass it to your Add function is that integers in C# are what is called a “value type” and not a “reference type”. When you pass a value type as an argument only its value is sent and not a reference to your variable (in this case your public int score). So whatever you do to that value, it will not be reflected anywhere else.

You can edit your post and just add four spaces before any line with code. :slight_smile:

1 Like

I fixed the code by adding Scoring.Score to each instance of score in Game1 to make it work again, but is there a way I can change Scoring.Score into a variable so instead of typing Scoring.Score every time I want to access it I can just type Score? (or whatever the variable is named) same thing with Score.Add, can I make it just Add?

Yes, you could write a function that returns the resulting score. Something like this:

    ...

    int Score;
    int Multiplier = 1;

    protected override void Update(GameTime gameTime)
    {
        ...

        if (oldState.IsKeyUp(Keys.Q) && newState.IsKeyDown(Keys.Q))
        {
            Score = Add(Score, Multiplier);
        }
        if (newState.IsKeyDown(Keys.W) && Score >= 100)
        {
            Score -= 100;
            Multiplier++;
        }
        ...
     }

    static int Add(int A, int B)
    {
        return A + B;
    }

However, in most cases it’s redundant to write a function for adding two integers together, as it can be done with the + operator right away.

If the whole point is that you want to have a class that takes care of scoring, I’d suggest something more like this:

public class Game1 : Game
{
    ...

    Scoring _scoring = new Scoring();

    protected override void Update(GameTime gameTime)
    {
        ...

        if (oldState.IsKeyUp(Keys.Q) && newState.IsKeyDown(Keys.Q))
        {
            _scoring.IncreaseScore(1);
        }

        if (newState.IsKeyDown(Keys.W) && score.Score >= 100)
        {
            _scoring.PurchaseMultiplier();
        }
        ...
    }
}

class Scoring
{
    public int Score { get { return _score; } }
    public int Multiplier { get { return _multiplier; } }

    int _score = 0;
    int _multiplier = 1;

    public void IncreaseScore(int a)
	{
        _score += a * _multiplier;
	}

    public void PurchaseMultiplier()
	{
        if (_score >= 100)
		{
            _score -= 100;
            _multiplier++;
		}
	}
}

EDITS: Sorry, I’m tired… cleaned up now:)

In my designs I have a Player class that keeps track of everything specific to that player. Number of Lives, Score, Multipliers, objects, etc… There is a lot more information I keep track of but that’s because it’s specific to my game but those are the basics.

Essentially you should design your classes to encapsulate information about the object. You have to decide does this go with Object A or Object B. You’ll want to spend time learning about Object Oriented Design. Learn about Inheritance, Encapsulation, Interfaces, etc…

1 Like

Where should I go to learn about those things?

There are plenty of fantastic resources online but buying a book is never a bad idea.

One of my personal favorites when it comes to youtube is Jamie King. Underrated channel imo! Short and to the point with little bloat. He’s got some great C# playlists and you can tell that he’s been teaching it for years.

If you prefer reading, maybe this is a good place to start?

W3 Schools is very beginner friendly too I think.

I also enjoyed the free android and iOS app SoloLearn. They have interactive quizzes in many languages including C# that takes you through the fundamentals (seems like you can do them in the browser too).

1 Like

A good site that you might keep as a reference for and as a tutorial for, C# would be:

C# Tutorial