-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHangmanGameInUnityEditorWindow.cs
113 lines (94 loc) · 2.9 KB
/
HangmanGameInUnityEditorWindow.cs
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
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
// - GitHub Organizations: https://github.com/Rimuru-Dev
//
// **************************************************************** //
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public sealed class HangmanGameInUnityEditorWindow : EditorWindow
{
private const string WindowName = "Hangman";
private string secretWord = "UNITY";
private char[] guessedWord;
private const int maxAttempts = 6;
private int attemptsLeft;
private readonly List<char> guessedLetters = new();
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[MenuItem("RimuruDev Games/Hangman Game")]
public static void ShowWindow() =>
GetWindow<HangmanGameInUnityEditorWindow>(false, WindowName, true);
private void OnEnable() =>
StartNewGame();
private void OnGUI()
{
DrawHeader();
DrawLetters();
CheckedGameState();
}
private void DrawHeader()
{
GUILayout.Label("Welcome to Hangman!", EditorStyles.boldLabel);
GUILayout.Label("Guess the word:");
GUILayout.Label(new string(guessedWord));
GUILayout.Label("Attempts left: " + attemptsLeft);
}
private void GameState(string label)
{
GUILayout.Label(label);
if (GUILayout.Button("Play Again"))
StartNewGame();
}
private void CheckedGameState()
{
if (attemptsLeft <= 0)
GameState("Game Over!");
else if (new string(guessedWord).Equals(secretWord))
GameState("You Win!");
}
private void DrawLetters()
{
GUILayout.BeginHorizontal();
foreach (var letter in Alphabet)
{
if (guessedLetters.Contains(letter))
continue;
if (GUILayout.Button(letter.ToString()))
{
guessedLetters.Add(letter);
GuessLetter(letter);
}
}
GUILayout.EndHorizontal();
}
private void GuessLetter(char letter)
{
var correctGuess = false;
for (var i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == letter)
{
guessedWord[i] = letter;
correctGuess = true;
}
}
if (!correctGuess)
attemptsLeft--;
}
private void StartNewGame()
{
secretWord = secretWord.ToUpper();
guessedWord = new char[secretWord.Length];
for (var i = 0; i < secretWord.Length; i++)
guessedWord[i] = '_';
attemptsLeft = maxAttempts;
guessedLetters.Clear();
}
}
#endif