Browse Source

Added a guessing game.

Stan Hebben 6 years ago
parent
commit
4669cc7d62
2 changed files with 21 additions and 1 deletions
  1. 11
    0
      scripts/guessing.zs
  2. 10
    1
      src/main/java/org/openzen/javascriptingexample/Globals.java

+ 11
- 0
scripts/guessing.zs View File

1
+var correct = false;
2
+while !correct {
3
+	val value = randomInt(10);
4
+	val guess = readLine("Guess a number 0-9: ");
5
+	if value == int.parse(guess) {
6
+		println("You were right!");
7
+		correct = true;
8
+	} else {
9
+		println("Nope, try again...");
10
+	}
11
+}

+ 10
- 1
src/main/java/org/openzen/javascriptingexample/Globals.java View File

8
 import java.io.BufferedReader;
8
 import java.io.BufferedReader;
9
 import java.io.IOException;
9
 import java.io.IOException;
10
 import java.io.InputStreamReader;
10
 import java.io.InputStreamReader;
11
+import java.util.Random;
11
 import org.openzen.zencode.java.ZenCodeGlobals;
12
 import org.openzen.zencode.java.ZenCodeGlobals;
12
 
13
 
13
 /**
14
 /**
15
  * @author Hoofdgebruiker
16
  * @author Hoofdgebruiker
16
  */
17
  */
17
 public class Globals implements ZenCodeGlobals {
18
 public class Globals implements ZenCodeGlobals {
19
+	private static final Random RANDOM = new Random();
20
+	
18
 	@Global
21
 	@Global
19
 	public static void println(String message) {
22
 	public static void println(String message) {
20
 		System.out.println(message);
23
 		System.out.println(message);
23
 	@Global
26
 	@Global
24
 	public static String readLine(String prompt) {
27
 	public static String readLine(String prompt) {
25
 		System.out.print(prompt);
28
 		System.out.print(prompt);
26
-		try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
29
+		try {
30
+			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
27
 			return reader.readLine();
31
 			return reader.readLine();
28
 		} catch (IOException ex) {
32
 		} catch (IOException ex) {
29
 			ex.printStackTrace();
33
 			ex.printStackTrace();
30
 			return "";
34
 			return "";
31
 		}
35
 		}
32
 	}
36
 	}
37
+	
38
+	@Global
39
+	public static int randomInt(int limit) {
40
+		return RANDOM.nextInt(limit);
41
+	}
33
 }
42
 }

Loading…
Cancel
Save