% template file for the bonus problem on geometric geometric sums of
% https://loeh.app.ur.de/teaching/fids_ws2324/blatt4.pdf
% 11/2023
\documentclass{standalone}

% a graphics library for LaTeX
\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
% a basic square [needs to be adapted!]
% * \draw: a basic drawing command that draws the specified path
% * \filldraw: a basic drawing command that draws the specified path
%   and fills it with the "fill" colour
% * rectangle: specifies a rectangle path
% * -- : connects points in a path
\newcommand{\badbasicsquare}{%
  \filldraw[fill=yellow] (0,0) rectangle +(1,1);
  \draw (0,0.5) -- (0.5,0);
}
% the actual macro [needs to be adapted in several ways!]
% * [1]: declares that this is a macro with a single argument
% * #1: in the body of the definition refers to the first argument
% * \foreach: a loop construct;
%   will loop over the implicitly introduced variable (in this case, \j)
%   over the specified range (in this case, {#1,...,1}, i.e., from #1 (down) to 1)
% * scope: environment that creates a new scope
% * scale: scales the scope by the specified factor
\newcommand{\badgeomsum}[1]{%
  \foreach \j in {#1,...,1} {%
    \begin{scope}[scale={0.42^2*\j}]
      \badbasicsquare
    \end{scope}
  }
}

% testing the macro \badgeomsum
% * shift: shifts the scope by the specified vector
% * \edef: a technicality because \LaTeX is a macro expansion language
%   that sometimes needs tweaking/forcing of the expansion order
\begin{tikzpicture}[thick,x=1.5cm,y=1.5cm]
  \foreach \j in {1,...,4}{%
    \begin{scope}[shift={(\j*2,0)}]
      \edef\evalarg{\j}
      \badgeomsum{\evalarg}
      % in addition, we display the argument:
      \draw (0,-0.5) node {$\j$};
    \end{scope}
  }
\end{tikzpicture}
\end{document}
