hangman game java,试图用Java实现基于文本的Hangman游戏

I need to check if the user-input letter, along with the spaces they guess, is at a specific spot on the hidden word.

the variable one is equal to the space index the user guessed.. and letterGuess is the letter they guessed. How is my code wrong??

example: secret word is hello

hidden word is == -----

user guesses h 0 1 2 3

so, it needs to check if the spaces at indexes 0 1 2 3 at the word hello contain the user guessed "h"

if so, need to replace ----- to h---- .

String firstSpace = guessedSpaces.substring(0,1);

String secondSpace = guessedSpaces.substring(2,3);

String thirdSpace = guessedSpaces.substring(4,5);

String fourthSpace = guessedSpaces.substring(6,7);

int one = Integer.parseInt(firstSpace);

int two = Integer.parseInt(secondSpace);

int three = Integer.parseInt(thirdSpace);

int four = Integer.parseInt(fourthSpace);

(secretWord.charAt(one)==letterGuess)

(secretWord.charAt(one)==letterGuess)

(secretWord.charAt(one)==letterGuess)

(secretWord.charAt(one)==letterGuess)

解决方案

Here's a brief amount of code that is a complete hangman program:

static int MAX_MISSES = 5;

static String[] WORDS = { "QUICK", "BROWN", "JUMPS" }; // etc

public static void main(String[] args) throws Exception {

String word = WORDS[new Random().nextInt(WORDS.length)], guesses = " ";

int misses = -1;

for (Scanner in = new Scanner(System.in); !word.matches("[" + guesses + "]+") & (misses += word.contains(guesses.substring(0, 1)) ? 0 : 1) <= MAX_MISSES; guesses = in.nextLine().toUpperCase().charAt(0) + guesses)

System.out.println(word.replaceAll("(?<=.)", " ").replaceAll("[^" + guesses + "]", "_"));

System.out.println(word + (misses > MAX_MISSES ? " not" : "") + " solved with " + misses + " incorrect guesses");

}

Some notes:

Regex is used to both check for solution and display the current guess status

& is used instead of && in the loop termination to force both sides of the logic to be executed - thus always updating the misses correctly

Various other tricks have been used to deliberately increase code density

There is no error checking for input. If more than one letter is input by the user, only the first is used. If no letters are input, it will explode. Error checking could be added without adding much more code, but the for line would be a whopper - I leave that as an exercise for the reader.

Also, there is no checking for erroneously guessing the same letter multiple times. With this code, if you guess a correct letter twice, nothing bad happens, but if you guess a wrong letter twice, it counts as a separate "miss", so you'll burn one of your chances.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值