I am trying to make a battleship game in WPF C# and whenever I click on a cell within the Border to fire at the enemy ship I get a nullreferenceexception within my INotifyPropertyChanged.
class BattleshipVM : ViewModelBase
{
string time = "";
public CellModel[][] OurMap {get; private set;}
public CellModel[][] EnemyMap { get; private set; }
public string Time
{
get => time;
private set => Set(ref time, value);
}
DispatcherTimer timer;
DateTime startTime;
string ourMap =
@"**********
XXXX**X**X
******X***
X*******X*
X*********
X****XX***
***X******
******X***
*******X**
***X****X*
**********
";
string enemyMap =
@"*X******X*
*******X**
**XX******
X*****X***
**********
*XXX***X**
**********
*X***XXX**
**X*******
***X***XX*
****X*****
";
public BattleshipVM()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Tick += Timer_Tick;
OurMap = MapFabric(ourMap);
EnemyMap = MapFabric(enemyMap);
}
CellModel[][] MapFabric(string str)
{
var mp = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var map = new CellModel[10][];
for (int i = 0; i < 10; i++)
{
map[i] = new CellModel[10];
for (int j = 0; j < 10; j++)
{
map[i][j] = new CellModel(mp[i][j]);
}
}
return map;
}
internal void ShotToOurMap(int X, int Y)
{
OurMap[X][Y].SetState();
}
private void Timer_Tick(object sender, EventArgs e)
{
var now = DateTime.Now;
var dt = now - startTime;
Time = dt.ToString(@"mm\:ss");
}
public void Start()
{
startTime = DateTime.Now;
timer.Start();
}
public void Stop()
{
timer.Stop();
}
}
public class CellModel : ViewModelBase
{
Visibility visibility = Visibility.Collapsed;
bool ship;
public CellModel(char state)
{
ship = state == 'X';
}
public Visibility Miss { get => visibility; private set => Set(ref visibility, value); }
public void SetMiss()
{
Miss = Visibility.Visible;
}
public Visibility Shot { get => visibility; private set => Set(ref visibility, value); }
public void SetState()
{
if (ship)
Shot = Visibility.Visible;
else
Miss = Visibility.Visible;
}
}
}
this is the mainwindow xaml
<Window x:Class="Battleship.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Battleship" d:DataContext="{d:DesignInstance Type=local:BattleshipVM}"
mc:Ignorable="d"
FontSize="24"
Title="Battleship Game" Height="450" Width="900">
<Window.Resources>
<DataTemplate DataType="{x:Type local:CellModel}">
<Border BorderBrush="DarkSalmon"
Width="30" Height="30"
BorderThickness="1"
Margin="0,0,-1,-1"
MouseDown="Border_MouseDown"
Background="NavajoWhite">
<Grid>
<Ellipse Width="7" Height="7"
Fill="Tomato"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Visibility="{Binding Miss}">
</Ellipse>
<Path
Stroke="#8F00" Data="M4,4L25,25M25,4L4, 25" StrokeThickness="3"
Visibility="{Binding Shot}"></Path>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Margin="20">
<TextBlock Text="{Binding Time}" FontSize="36"
HorizontalAlignment="Center" Margin="0,0,0,10"
x:Name="TimeShow">
0:00 </TextBlock>
<TextBlock Text="{Binding Steps}" HorizontalAlignment="Center" > Step: 5:
</TextBlock>
<TextBlock Text="{Binding Goal}" HorizontalAlignment="Center" > Goal 3:
</TextBlock>
</StackPanel>
<Button Content=" Start " Grid.Column="1" Click="btnStart"/>
<Button Content=" Stop " Grid.Column="2" Click="btnStop"/>
<ItemsControl
Grid.Column="1" ItemsSource="{Binding OurMap}" HorizontalAlignment="Center"
VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal">
</StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl
Grid.Column="2" ItemsSource="{Binding EnemyMap}" HorizontalAlignment="Center"
VerticalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal">
</StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
This is the cs for the main window file. If I comment out the bs.ShoutToOurMap method it runs but only as a 2 player game but I want it as a computer vs player game thus the method but it gives a nullreferenceexception when I click on any cell in the Border
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Battleship
{
public partial class MainWindow : Window
{
BattleshipVM bs = new BattleshipVM();
Random rnd = new Random();
public MainWindow()
{
DataContext = bs;
bs = new BattleshipVM();
InitializeComponent();
}
private void btnStart(object sender, RoutedEventArgs e)
{
bs.Start();
}
private void btnStop(object sender, RoutedEventArgs e)
{
bs.Stop();
}
private void Border_MouseDown(object sender, MouseButtonEventArgs e)
{
var bor = sender as Border;
var cellModel = bor.DataContext as CellModel;
cellModel.SetState();
var X = rnd.Next(10);
var Y = rnd.Next(10);
bs.ShotToOurMap(X, Y);
}
}
}
And this is the viewBaseModel with the INotifyPropertyChanged interface
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Battleship
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T field, T value, [CallerMemberName] string propName = "")
{
if (!field.Equals(value))
{
field = value;
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
protected void Fire(params string[] names)
{
foreach (var name in names)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
What I have tried:
I've tried putting the Data Template into Windows.Resources so it would be available to the entire program and made the DataTemplates DataType as the local class CellModel that is the one that makes the hits and misses visible when the player hit but this is all to not avail. Been at it for three days with this error and still cannot figure it out. Thanks!