为了说明掷两个骰子并得到总和为 7 的概率是 1/6,我想使用 中的“foreach”选项制作一个表格TikZ
。以下代码为我提供了所有可能掷出的骰子的表格。
相邻对的矩形重叠。这看起来不太美观。如何添加水平空间来分隔矩形?
使用此代码,我可以用圆形或椭圆形替换包含总计为 7 的六对数字的矩形吗?
我怎样才能使第一个数字变成蓝色,第二个数字变成绿色?
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,angles,shapes,positioning,intersections,quotes,decorations.markings}
\begin{document}
\begin{tikzpicture}
\node foreach \x in {1,...,6} foreach \y in{1,...,6} [draw] at (\x-6,6-\y)
{(\x, \, \y)};
\end{tikzpicture}
\end{document}
答案1
% arara: pdflatex
\documentclass{amsart}
\usepackage{tikz}
\usepackage{xcolor}
\begin{document}
\begin{tikzpicture}[x=1.5cm,y=1.5cm]
\node foreach \x in {1,...,6} foreach \y in{1,...,6} [draw, circle] at (\x-6,6-\y)
{(\textcolor{blue}{\x}, \, \textcolor{green}{\y})};
\end{tikzpicture}
\end{document}
% arara: pdflatex
\documentclass{amsart}
\usepackage{tikz}
\usepackage{xcolor}
\begin{document}
\begin{tikzpicture}[x=1.8cm,y=1cm]
\foreach \x in {1,...,6} {%
\foreach \y in {1,...,6} {%
\draw (\x-6,6-\y) ellipse (.8cm and .3cm) node {$(\textcolor{blue}{\x},\textcolor{green}{\y})$};
}
}
\end{tikzpicture}
\end{document}
编辑:
抱歉,我一开始就误解你了。下面是:
% arara: pdflatex
\documentclass{amsart}
\usepackage{tikz}
\usepackage{xcolor}
\usepackage{xifthen}
\begin{document}
\begin{tikzpicture}[x=1.8cm,y=1cm]
\foreach \x in {1,...,6} {%
\foreach \y in {1,...,6} {%
\pgfmathtruncatemacro{\test}{\x+\y};
\ifthenelse{\test=7}
{\draw (\x-6,6-\y) ellipse (.8cm and .3cm) node {$(\textcolor{blue}{\x},\textcolor{green}{\y})$};}
{\draw (\x-6,6-\y) node [draw] {$(\textcolor{blue}{\x},\textcolor{green}{\y})$};}
}
}
\end{tikzpicture}
\end{document}
答案2
您还可以使用矩阵和空单元格指令
\documentclass[tikz]{standalone}
\usetikzlibrary{matrix,shapes.geometric}
% shorthand for less typing
\def\mcr{\pgfmatrixcurrentrow}\def\mcc{\pgfmatrixcurrentcolumn}
\begin{document}
\begin{tikzpicture}
\matrix (a) [execute at empty cell={\ifnum7=\numexpr\mcc+\mcr\relax
\node[ellipse,draw,inner sep=1pt]
{(\textcolor{blue}{\the\mcc},\textcolor{green}{\the\mcr})};
\else
\node[draw,inner sep=1pt]{(\textcolor{blue}{\the\mcc},\textcolor{green}{\the\mcr})};
\fi}]{&&&&&\\&&&&&\\&&&&&\\&&&&&\\&&&&&\\&&&&&\\};
\end{tikzpicture}
\end{document}
答案3
使用 MetaPost 进行尝试,尽可能简单。使用 LuaLaTeX 进行处理。
\documentclass[border=2mm]{standalone}
\usepackage{luamplib}
\mplibtextextlabel{enable}
\begin{document}
\begin{mplibcode}
u := 1.25cm; v := -cm; pair pos; path box; picture dices;
beginfig(1);
for i = 1 upto 6:
for j = 1 upto 6:
pos := ((i+1)*u, (j+1)*v);
dices := thelabel(decimal i & ", " & decimal j, pos);
box := bbox dices;
if i+j <> 7: draw box;
else:
d1 := xpart(lrcorner box - llcorner box) + labeloffset;
d2 := ypart(urcorner box - lrcorner box) + labeloffset;
draw fullcircle xscaled d1 yscaled d2 shifted pos;
fi
draw dices;
endfor
endfor
endfig;
\end{mplibcode}
\end{document}