Debian Codegraph @

itl/hangman

raw
1 // SPDX-FileCopyrightText: 2012 Icinga GmbH <https://icinga.com>
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 if (!globals.contains("irc")) {
5 globals.irc = log
6 }
7
8 hm = {
9 max_errors = 6
10
11 h_word = null
12 h_arr = null
13 guesses = 0
14 errors = 0
15 a_arr = null
16 misses = ""
17
18 if (irc) {
19 hangman_output = irc
20 } else {
21 hangman_output = log
22 }
23
24 function str2arr(str) {
25 var arr = []
26
27 for (i in range(str.len())) {
28 arr.add(str.substr(i, 1))
29 }
30
31 return arr
32 }
33
34 function init(s) {
35 s = s.upper()
36 h_word = s
37 h_arr = str2arr(h_word)
38 guesses = 0
39 errors = 0
40 a_arr = h_arr.clone()
41 misses = ""
42
43 for (x in range(a_arr.len())) {
44 a_arr[x] = (h_arr[x] == " ")
45 }
46 }
47
48 function print_progress() {
49 var ir
50
51 for (x in range(a_arr.len())) {
52 if (a_arr[x]) {
53 ir += h_arr[x]
54 } else {
55 ir += "_"
56 }
57
58 ir += " "
59 }
60
61 hangman_output(ir)
62 hangman_output(errors + "/" + (max_errors + 1) + " errors made: " + misses)
63 }
64
65 function create_hint() {
66 var r = Math.floor(Math.random() * a_arr.len())
67 if (!a_arr[r]) {
68 a_arr[r] = true
69 for (x in range(h_arr.len())) {
70 if (h_arr[x] == h_arr[r]) {
71 a_arr[x]=true
72 }
73 }
74 } else {
75 if (a_arr.contains(false)) {
76 create_hint()
77 } else {
78 winner()
79 }
80 }
81
82 if (!a_arr.contains(false)) {
83 winner()
84 }
85 }
86
87 function hint(i) {
88 for (x in range(i)) {
89 create_hint()
90 }
91
92 print_progress()
93 }
94
95 function winner() {
96 if (h_word) {
97 hangman_output("Congratulations, you are a winner in " + guesses + " guesses.")
98 h_word = null
99 }
100 }
101
102 function guess(s) {
103 if (!h_word) {
104 hangman_output("Please set a word with hm.init(\"word\")")
105 return
106 }
107
108 s = s.upper()
109
110 if (s.len() != 1) {
111 hangman_output("NEIN!")
112 return
113 }
114
115 var correct = false
116 for (x in range(h_arr.len())) {
117 if (h_arr[x] == s) {
118 a_arr[x] = true
119 correct = true
120 }
121 }
122
123 if (!correct) {
124 misses += s + " "
125 errors += 1
126 }
127
128 print_progress()
129
130 guesses += 1
131
132 if (!a_arr.contains(false)) {
133 winner()
134 return
135 }
136
137 if (errors > max_errors) {
138 hangman_output("You died...")
139 hangman_output(" ________")
140 hangman_output(" |/ |")
141 hangman_output(" | (_)")
142 hangman_output(" | \\|/")
143 hangman_output(" | |")
144 hangman_output(" | / \\")
145 hangman_output(" |")
146 hangman_output("_|___")
147 remove("h_word")
148 return
149 }
150 }
151
152 function clone() {
153 var n = Dictionary.prototype.clone.call(this)
154
155 if (h_arr) {
156 n.h_arr = h_arr.clone()
157 }
158
159 if (a_arr) {
160 n.a_arr = a_arr.clone()
161 }
162
163 return n
164 }
165 }
166