My plan was to have a field of 3*3 with buttons and change the color (which is used to mark a button) by every turn. So i created a playerclass in which the color of the player should be stored and used this string to check, which color should be used in form1. Problem: Null reference exception in the method colorChoice. This is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TicTacToe
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace TicTacToe
{
public class Player
{
public String playerColor = "Red";
public int[,] storage;
public Player(String playerColor)
{
this.playerColor = playerColor;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TicTacToe
{
public partial class Form1 : Form
{
public static Player player1;
public static Player player2;
public static Player currentPlayer;
public Form1()
{
InitializeComponent();
Player player1 = new Player("Red");
Player player2 = new Player("Blue");
currentPlayer = player1;
}
private void button1_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button1);
}
private void button2_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button2);
}
private void button3_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button3);
}
private void button4_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button4);
}
private void button5_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button5);
}
private void button6_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button6);
}
private void button7_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button7);
}
private void button8_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button8);
}
private void button9_Click(object sender, EventArgs e)
{
playerSwitch();
colorChoice(button9);
}
private void colorChoice(Button button)
{
if(currentPlayer.playerColor == "Red") button.BackColor = Color.Red;
if (currentPlayer.playerColor == "Blue") button.BackColor = Color.Blue;
}
public static void playerSwitch()
{
if (currentPlayer == player1)
{
currentPlayer = player2;
}
else //if (currentPlayer == player2)
{
currentPlayer = player1;
}
}
}
}