Click here to Skip to main content
15,881,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    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!
Posted
Updated 7-Dec-22 22:45pm

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

First find out what is null, then you can start to look at why - but it needs your code running on your system to find that out!

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
When posting questions, especially with such a large code dump, what helps us to help you is:
1. The line of code that threw the error
2. The exact error message

Taking a stab at your issue, there are two possibilities:
1. field variable is null in this line:
C#
if (!field.Equals(value))

Change to:
C#
if (!field?.Equals(value))

2. If there are no listeners to the PropertyChanged, then it will be null and throw an error.
C#
PropertyChanged(this, new PropertyChangedEventArgs(propName));

Typically you call an event as nullable:
C#
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));

If it is neither of these lines, please update your question with the above two details mentioned at the start of this solution.
 
Share this answer
 
v3
Comments
Richard Deeming 8-Dec-22 9:42am    
A cleaner version for the field.Equals line would be:
if (!Equals(field, value))
Graeme_Grant 8-Dec-22 10:05am    
There are a number of different ways, I just tried to keep it inline with his code. My goto is:
if (!EqualityComparer<TValue>.Default.Equals(field, default)
    && field!.Equals(newValue))
    return;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900