[Tex/LaTex] TikZ: Using Loop to Draw Grid of Nodes

foreachnode-connectionsnodestikz-pgf

I am trying to draw an Ising model (in my case, a grid of nodes with an undirected edge between adjacent nodes on the same row or column) using TikZ. I have the grid of nodes working nicely using a foreach loop, but I am having trouble drawing the lines between nodes. The problem lies in the fact that I am getting a syntax error when I try to \draw lines between computed node names.

Here is what I have so far:

enter image description here

Here is the code I am using:


\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\scriptsize
\foreach \i in {1,...,25}
{
        \pgfmathtruncatemacro{\y}{(\i - 1) / 5};
        \pgfmathtruncatemacro{\x}{\i - 5 * \y};
        \pgfmathtruncatemacro{\label}{\x + 5 * (4 - \y)};
        \node[circle,draw=black,fill=white!80!black,minimum size=20]
        (\label) at (1.5*\x,1.5*\y) {\label};
}
% These draw commands are working as intended.
\draw (1) -- (2);
\draw (1) -- (6);
\draw (6) -- (7);
\draw (7) -- (2);
% The loop, however, is not =(
%\foreach \x in {1,...,4}
%\foreach \y in {0,...,4}
%{
%       \pgfmathtruncatemacro{\cur}{\x + 5 * \y};
%       \pgfmathtruncatemacro{\next}{\cur + 1};
%       \draw (\cur) -- (\next);
%}
\end{tikzpicture}
\end{document}

Thank you very much for your help!

Best Answer

It's possible to use a minimum code

\documentclass{minimal}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[darkstyle/.style={circle,draw,fill=gray!40,minimum size=20}]
  \foreach \x in {0,...,4}
    \foreach \y in {0,...,4} 
       {\pgfmathtruncatemacro{\label}{\x - 5 *  \y +21}
       \node [darkstyle]  (\x\y) at (1.5*\x,1.5*\y) {\label};} 

  \foreach \x in {0,...,4}
    \foreach \y [count=\yi] in {0,...,3}  
      \draw (\x\y)--(\x\yi) (\y\x)--(\yi\x) ;

\end{tikzpicture}
\end{document}  

enter image description here

Only for information you can get the grid with tkz-berge

\documentclass[border=0.25cm]{standalone}
\usepackage{tkz-berge}

\begin{document}

 \begin{tikzpicture}
      \GraphInit[vstyle=Shade]
   \grGrid[Math,RA=2,RB=2]{5}{5}
 \end{tikzpicture}

\end{document} 

enter image description here