第一次编码(Java 刽子手游戏)——从基于控制台到 GUI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22768544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Coding for the first time (Java hangman game)- going from console-based to GUI
提问by NewGirl
I am completely new to programmingand I have to complete some tasks in Java (I'm using Eclipse). This one is a hangman game. My code is below. I have written a console-based program that basically works (counting lives instead of drawing a hangman graphic).
我对编程完全陌生,我必须用 Java 完成一些任务(我使用的是 Eclipse)。这是一个刽子手游戏。我的代码如下。我编写了一个基于控制台的程序,它基本上可以工作(计算生命而不是绘制刽子手图形)。
I think this question will seem very simple to most people, but I would really appreciate your help.
我认为这个问题对大多数人来说似乎很简单,但我非常感谢您的帮助。
I am trying my best to look for answers online, but as a complete novice it is hard to know where to start. I would really just like to know if I am on the right track so that I don't waste too much time.
我正在尽我最大的努力在网上寻找答案,但作为一个完整的新手,很难知道从哪里开始。我真的很想知道我是否在正确的轨道上,这样我就不会浪费太多时间。
I am supposed to (and want to!) do this myself, so ideally I would like hints on what to focus on.
我应该(并且想要!)自己做这件事,所以理想情况下,我希望得到关于要关注什么的提示。
The questions I have are:
我的问题是:
- I now need to create a GUI(which I have never done before): how useful is this code that I have already worked out? Is everything completely different once I start creating the game with a GUI?
- I used a
StringBuffer
to store the previously guessed letters. I wanted to searchthis in order to display the word with all the previously guessed letters filled in (as it stands it only prints out the current guess with all the other letters obscured). Is that possible?
- 我现在需要创建一个 GUI(我以前从未做过): 我已经制定的这段代码有多大用处?一旦我开始使用 GUI 创建游戏,一切就完全不同了吗?
- 我用 a
StringBuffer
来存储之前猜出的字母。我想搜索这个以显示填充了所有先前猜测的字母的单词(目前它只打印出当前猜测的所有其他字母)。那可能吗?
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer buffer = new StringBuffer();
String secretWord;
int secretWordLength;
int position;
int livesLost = 0;
int totalLives = 10;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//prompt user to enter a word and set as an instance of the secretWord variable
System.out.println("Enter a word:");
secretWord = myScanner.next();
//determine the length of the word entered
secretWordLength = secretWord.length();
System.out.println(secretWordLength);
lettersRemaining = secretWordLength;
for (position = 0; position < secretWordLength; position++) {
System.out.print("*");
}
System.out.println();
//loop starts
while (lettersRemaining > 0 && livesLost < 10) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < secretWordLength; position++) {
if (secretWord.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("*");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(secretWord);
}
}
回答by 2rs2ts
Java comes with a GUI toolkit called Swing, which you should learn to use for the purposes of your task at hand.
Java 附带了一个名为Swing的 GUI 工具包,您应该学会将其用于您手头的任务。
As far as searching for previously guessed letters, you may be better served by the Set
, which is a Collection
of unique elements. You could use a Set
of Character
s, i.e. a Set<Character>
.
至于搜索以前猜到的字母,您可能会更好地使用Set
,这是一个Collection
独特的元素。您可以使用 a Set
of Character
s,即 a Set<Character>
。
A crude example:
一个粗略的例子:
Set<Character> guesses = new HashSet<Character>();
Character guess;
// etc.
while (lettersRemaining > 0 && livesLost < 10)
{
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".",0).charAt(0);
if (guesses.contains(guess)) {
System.out.println("You have already guessed this character!");
} else {
guesses.add(guess);
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess))!= -1;
// etc.
}
}
Actually, you can get some extra mileage out of the add
method by taking advantage of the fact that it returns true
if the element was not already in the set:
实际上,如果元素不在集合中,您可以add
利用它返回的事实,从该方法中获得一些额外的好处true
:
if (guesses.add(guess)) {
//check if the letter guessed is in the secretWord
guessInWord = (secretWord.indexOf(guess))!= -1;
// etc.
} else {
System.out.println("You have already guessed this character!");
}
回答by Ivan Verges
Well, for your first question:
那么,对于你的第一个问题:
-Your code it's useful to your goal, so keep it up. Search about Swing library which it's a graphical lib for java, it will let you make a GUI without so much hard work.
- 你的代码对你的目标很有用,所以坚持下去。搜索 Swing 库,它是 Java 的图形库,它可以让您轻松制作 GUI。
About your second question:
关于你的第二个问题:
-Right now i can't help you with it but it's not so hard so keep looking for it.
-现在我无法帮助你,但它并不难,所以继续寻找它。
回答by zyzo
By adding a GUI, your application will be longer and more structurally complex. It might not be a good idea to have all the code in 1 main method like your current program. So you might want to re-arrange your code into several different methods (also called procedures/sub-routines in other languages). This technique is call procedural programming which is intended to make your coding life easier.
That being told, your code is not completely wasted when switching to GUI. The game logic remains the same. Nothing changes except the way the program interacts with users. This time, you receives guesses and outputs answers using Swing objects like JTextField(Swingis the default graphic library of Java. There's a lot out there but it's a good start). You'll also want to look at JPanel and JFrame (ways of telling the graphic window where exactly you want to put your stuff - so called layout).
StringBuffer is just a modifiable version of String. To perform searching/read through operations, try an array-like data structure. Here I use
ArrayList
which is the very basic data structure in Java:ArrayList<String> buffer; boolean addGuess(String inputString){ boolean isNewGuess = true; for (String s: buffer){ if (s.equals(inputString)){ isNewGuess = false; break; } } if (isNewGuess) buffer.add(inputString); return isNewGuess; }
通过添加 GUI,您的应用程序将变得更长且结构更复杂。像当前程序一样将所有代码放在 1 个 main 方法中可能不是一个好主意。因此,您可能希望将代码重新排列为几种不同的方法(在其他语言中也称为过程/子例程)。这种技术称为过程式编程,旨在使您的编码生活更轻松。
话虽如此,切换到 GUI 时您的代码并没有完全浪费。游戏逻辑保持不变。除了程序与用户交互的方式外,没有任何变化。这一次,您使用JTextField 之类的 Swing 对象接收猜测并输出答案(Swing是 Java 的默认图形库。那里有很多,但这是一个好的开始)。您还需要查看 JPanel 和 JFrame(告诉图形窗口您想把东西放在哪里的方法 - 所谓的布局)。
StringBuffer 只是 String 的一个可修改版本。要执行搜索/读取操作,请尝试类似数组的数据结构。这里我使用
ArrayList
了 Java 中最基本的数据结构:ArrayList<String> buffer; boolean addGuess(String inputString){ boolean isNewGuess = true; for (String s: buffer){ if (s.equals(inputString)){ isNewGuess = false; break; } } if (isNewGuess) buffer.add(inputString); return isNewGuess; }
回答by Muhammad Abbas
using Hang-Man Game simple logic
使用吊人游戏简单逻辑
optional this is package name
package arr_game;
可选 这是包名
包 arr_game;
import java.util.Random;
import java.util.Scanner;
public class HangMan {
public static char[] star;
public static void main (String args[])
{
char game[];
Scanner input = new Scanner(System.in);
Random r = new Random();
String[] arr = { "pakistan", "india", "jarmany", "america", "rashia", "iran", "iraq", "japan", "sudan", "canada"};
String word = arr[r.nextInt(arr.length)];
int count = word.length();
char[] CharArr=word.toCharArray();
char[] star = word.toCharArray();
for(int i=0;i<star.length;i++)
{
star[i] = '*';
System.out.print(star[i]);
}
for (int i=1; i<=3; i++)
{
System.out.printf ("\nGuess a Letter:");
char letter= input.next().charAt(0);
for (int j=0;j<CharArr.length; j++)
{
if(letter == star[j])
{
System.out.println("this word already exist");
}
else
{
if(letter==CharArr[j])
{
star[j]=letter;
i--;
System.out.printf("CORRECT GUESS!\n");
}
}
}
System.out.print(star);
switch(i+0)
{
case 1: System.err.printf("Strike 1\n");
break;
case 2: System.err.printf("Strike 2\n");
break;
case 3: System.err.printf("Strike 3\n");
System.err.printf("You're out!!! The word is Not_Matched\n");
break;
}
System.out.printf("\n");
if((new String(word)).equals(new String(star)))
{
System.err.printf("Winner Winner, Chicken Dinner!\n");
break;
}
}
}
}