[英]How do I add a keypress action in my program?
我正在制作一个非常基本的基于Java的RPG游戏,随着您的前进有很多选择,我想制作它,因此当您具有键入功能时,如果按“ x”,它将自动退出游戏。 我不想每次用户进步时都不断添加“ if-then”语句。
我不想做的事情(我必须做50次以上:库存,退出游戏,角色信息等等)
switch (choice1)
{
case "x":
System.out.println("\nYou quit the game!");
System.exit(0);
break;
}
我所拥有的:(不起作用)
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
public class TheDungeon extends KeyAdapter
{
public void keyPressed(KeyEvent e) {
char ch = e.getKeyChar();
if (ch == 'a')
{
System.out.println("You pressed A");
}
}
public static void main(String[] args)
{
/* My variables...
*/
System.out.println("e: Check experience and level");
System.out.println("c: Character Information");
System.out.println("i: Inventory");
System.out.println("x: Quit Game");
choice1 = keyboard.nextLine();
switch (choice1)
{
case "x": //This section
System.out.println("\nYou quit the game!"); //here works
System.exit(0); //but I don't
break; //want to add this section
} //every time the user
//progresses.
要使用KeyAdapters
和/或KeyListeners
您将需要构造一个Gui,在其中也要添加这些Adapters / Listners。
您当前在用户操作中阅读的方式是对控制台应用程序执行此操作的有效方式。
编辑上BlakeP的答案扩展,如果你有你的determineAction
方法你可以有一个地图打印出来一样,那么你只需要添加特殊动作的键文本。
Map<Character, String> actionText = new HashMap<Character, String>();
actionText.put('x', "\nYou quit the game!");
actionText.put('i', "\nInventory Items:\n Things are here");
private void determineAction(char choice) {
System.out.println(actionText.get(choice));
switch (choice1)
{
case "x":
System.exit(0);
break;
}
}
或者,您应该使用另一种方法来执行每个特殊操作,这将使您的开关更短且更易于阅读。 像这样
private void determineAction(char choice) {
System.out.println(actionText.get(choice));
switch (choice1)
{
case "x":
doExit();
break;
case "i":
printInventory();
break;
}
}
private void doExit()
{
System.out.println("\nYou quit the game!");
System.exit(0);
}
private void printInventory()
{
System.out.println("\nInventory Items:");
System.out.println("\n Things are here");
}
KeyAdapter类用于GUI应用程序(请注意它所在的AWT程序包),听起来好像您只是在做一个控制台应用程序。 据我所知,控制台应用程序没有“按键”监听器。
我建议将switch语句放入诸如“ determineAction”之类的方法中,然后返回您需要的内容(如果有的话)。
示例方法:
private void determineAction(char choice) {
switch (choice1)
{
case "x":
System.out.println("\nYou quit the game!");
System.exit(0);
break;
case "i":
System.out.println("\nInventory Items:");
System.out.println("\n Things are here");
break;
}
}
因此,每次您要求选择之后,请输入以下行:
determineAction(choice);
并且它将运行switch语句,而无需每次都复制它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.