-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
115 lines (91 loc) · 2.36 KB
/
Copy pathscript.js
File metadata and controls
115 lines (91 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
$(document).ready(function() {
window.fails = 0;
window.max_fails = 5;
window.possible_words = [
"romania",
"italy",
"france",
"spain",
"hungary",
"moldova",
"two words",
"lorem ipsum dolor",
"lorem ipsum dolor sit amet"
];
window.secret_word = "hangman";
window.public_word = "_______";
window.game_is_finished = false;
window.wrong_letters = [];
function replace_str(str, pos, value){
var arr = str.split('');
arr[pos]=value;
return arr.join('');
}
function choose_word() {
var random_number = Math.floor(Math.random() * possible_words.length);
secret_word = possible_words[random_number];
public_word = Array(secret_word.length + 1).join("_");
for(var i = 0; i <= secret_word.length; i++) {
if(secret_word[i] == " ") {
public_word = replace_str(public_word, i, " ");
}
}
}
function game_over() {
$("p#status").text("Game over! The word was: " + secret_word);
game_is_finished = true;
}
function fail() {
$("img#main-image").attr("src", "./images/" + fails.toString() + ".png");
$("p#status").text("Wrong letters: " + wrong_letters);
if(fails > max_fails) {
game_over();
} else {
fails++;
}
}
function win() {
$("p#status").text("Congrats!");
game_is_finished = true;
}
function test_letter(letter) {
return secret_word.indexOf(letter);
}
function refresh_public_word() {
$("p#public-word").text(public_word);
}
function add_wrong_letter(letter) {
if (wrong_letters.indexOf(letter) > -1)
return false;
else {
wrong_letters.push(letter);
return true;
}
}
function start_game() {
choose_word();
refresh_public_word();
$(document).keypress(function(event) {
if(!game_is_finished) {
var key = String.fromCharCode(event.which).toLowerCase();
if (key.match(/[a-z]/g)){
var test = test_letter(key);
if(test != -1) {
for(var i = 0; i <= secret_word.length; i++) {
if(secret_word[i] == key) {
public_word = replace_str(public_word, i, key);
}
}
refresh_public_word();
if(public_word == secret_word) {
win();
}
} else if (add_wrong_letter(key)){
fail();
}
}
}
});
}
start_game();
});