Creating AI Logic for Computer-Controlled Bat in C#

I need help with implementing automated movement for the AI bat in my game. The human player’s bat works fine with mouse input, but I can’t get the computer bat to track the ball properly. I want the AI to follow the ball but still have some imperfection so it can miss sometimes.

MainForm.cs

private void MainForm_MouseMove(object sender, MouseEventArgs e)
{
    gameManager.UpdatePlayerBat(e.Location.Y);
}

GameManager.cs

public void UpdatePlayerBat(int mouseY)   
{
    playerBat.SetBatPosition(mouseY);
}

Bat.cs

public void SetBatPosition(int yCoordinate)
{
    location.Y = yCoordinate;   
}

For the AI bat, I tried this approach but it doesn’t work correctly:

Bat.cs

public void SetAIBatPosition(int newYCoord)
{
    location.Y = newYCoord;   
}

GameManager.cs

public void UpdateAIBat(int currentAIPosition)
{
    if (gameBall.Location.Y >= aiBat.Location.Y)
    {
        currentAIPosition += SPEED_CONSTANT;
    }
    else if (gameBall.Location.Y <= aiBat.Location.Y)
    {
        currentAIPosition -= gameBall.Direction.Y;
    }
}

public void GameLoop()
{
   UpdateAIBat(aiBat.Location.Y);    
}

The bat doesn’t move at all. What am I doing wrong with the AI movement logic?

Your UpdateAIBat method isn’t updating the bat position. You’re calculating a new position but never actually applying it.

Here’s what I use in similar projects:

public void UpdateAIBat()
{
    int targetY = gameBall.Location.Y;
    int currentY = aiBat.Location.Y;
    
    if (Math.Abs(targetY - currentY) > 5) // Dead zone to prevent jittering
    {
        if (targetY > currentY)
        {
            aiBat.SetAIBatPosition(currentY + SPEED_CONSTANT);
        }
        else
        {
            aiBat.SetAIBatPosition(currentY - SPEED_CONSTANT);
        }
    }
}

For imperfection, I add reaction delay and occasional mistakes:

private int reactionDelay = 0;
private Random rand = new Random();

public void UpdateAIBat()
{
    reactionDelay--;
    
    if (reactionDelay <= 0)
    {
        // 10% chance to make a wrong move
        int targetY = rand.Next(100) < 10 ? 
            gameBall.Location.Y + rand.Next(-50, 50) : 
            gameBall.Location.Y;
            
        // Move towards target
        int currentY = aiBat.Location.Y;
        if (Math.Abs(targetY - currentY) > 5)
        {
            if (targetY > currentY)
                aiBat.SetAIBatPosition(currentY + SPEED_CONSTANT);
            else
                aiBat.SetAIBatPosition(currentY - SPEED_CONSTANT);
        }
        
        reactionDelay = rand.Next(2, 8); // Random delay between moves
    }
}

This makes the AI feel human-like but still competitive.