Sulprobil
Search…
Game of Nim
Here you can find a Perl implementation of the game of Nim:
Please read my Disclaimer.
1
########################################################################
2
#
3
# File: nim.pl
4
# Author: Bernd Plumhoff
5
# Version: 1.1
6
#
7
# Usage: Game of Nim
8
#
9
# Call: perl nim.pl
10
#
11
########################################################################
12
#
13
14
sub zuende {
15
$summe = $h[0];
16
for ($i=1; $i<$haufen; $i++) {
17
$summe += $h[$i];
18
}
19
$summe == 0;
20
}
21
22
sub zeigen {
23
print "\n";
24
for ($i=0; $i<$haufen; $i++) {
25
print "\tHeap ", $i, ":\t", $h[$i], "\n";
26
}
27
print "\n";
28
}
29
30
sub computer {
31
# Computer to move
32
33
$computer=0;
34
for ($i=0; $i<$haufen; $i++) {
35
$computer^=$h[$i];
36
}
37
38
if ($computer==0) {
39
# Computer is going to lose
40
for ($i=0; $h[$i]==0; $i++) {
41
;
42
}
43
$computer = $h[$i];
44
} else {
45
# Computer will win
46
for ($i=0; ($i<$haufen) && (($computer^$h[$i])>=$h[$i]); $i++) {
47
;
48
}
49
$computer = $h[$i] - ($computer ^ $h[$i]);
50
}
51
52
print "\tI take ", $computer, " stone(s) from heap ", $i, ".\n";
53
54
$h[$i] -= $computer;
55
56
}
57
58
sub mensch {
59
# Human to move
60
61
do {
62
print "\tWhich heap do you want to take stones from? ";
63
} while ((($hnr=<>)<0 || $hnr>=$haufen || $h[$hnr]==0) && print "\tWrong heap number!\n\n");
64
65
do {
66
print "\tHow many stones do you want to take from heap ", $hnr+0, "? ";
67
} while ((($anz=<>)<=0 || $h[$hnr]<$anz) && print "\tWrong number of stones!\n\n");
68
69
$h[$hnr] -= $anz;
70
}
71
72
# Main program
73
74
print "\n\t\t\tN I M\n\t\t\t=====\n\n\tThis is the game of Nim. You can take as ";
75
print "many stones from\n\tone heap as you like (at least one)";
76
print "\n\tIf you take the last stone of the last heap you win!\n";
77
print "\n\n";
78
79
do {
80
print "\tHow many heaps (at least 3)? ";
81
} while ((($haufen=<>) < 3) && print "\tYou need to choose at least 3 heaps!\n\n");
82
83
print "\n";
84
85
for ($i=0; $i<$haufen; $i++) {
86
do {
87
print "\tHow many stones for heap number ", $i, "? ";
88
} while ((($h[$i]=<>+0) <= 0) && print "\tYou need to have at least one!\n\n");
89
}
90
91
while () {
92
&zeigen();
93
94
&computer();
95
96
&zuende() && die "\tI won!\n";
97
98
&zeigen();
99
100
&mensch();
101
102
&zuende() && die "\tYou won!\n";
103
}
104
105
<>;
Copied!
Last modified 1yr ago
Copy link