I made a simple game(well not really a game yet) in which the player can move in a room 4x20 characters in size. It runs in console.
But in my game loop I want to be able to move around in the room without pressing enter every time I want to move. The player should be able to press w/a/s/d and have the screen update instantly, but I don't know how to do that.
public class Main{
public static void main(String[] args){
MovementLoop();
}
public static void MovementLoop(){
Scanner input = new Scanner(System.in);
int pos=10, linepos=2;
String keypressed;
boolean playing = true;
while(playing == true){
display dObj = new display(linepos, pos);
dObj.drawImage();
keypressed=input.nextLine();
if(keypressed.equals("w")){
linepos -= 1;
}
else if(keypressed.equals("s")){
linepos += 1;
}
else if(keypressed.equals("a")){
pos -= 1;
}
else if(keypressed.equals("d")){
pos += 1;
}
else if(keypressed.equals("q")){
System.out.println("You have quit the game.");
playing = false;
}
else{
System.out.println("\nplease use w a s d\n");
}
}
}
}
public class display{
private String lines[][] = new String[4][20];
private String hWalls = "+--------------------+";
private String vWalls = "|";
private int linepos, pos;
public display(int linepos1, int pos1){
pos = pos1 - 1;
linepos = linepos1 - 1;
}
public void drawImage(){
for(int x1=0;x1<lines.length;x1++){
for(int x2=0;x2<lines[x1].length;x2++){
lines[x1][x2]="#";
}
}
lines[linepos][pos]="O";
System.out.println(hWalls);
for(int x2=0;x2<lines.length;x2++){
System.out.print(vWalls);
for(int x3=0;x3<lines[x2].length;x3++){
System.out.print(lines[x2][x3]);
}
System.out.println(vWalls);
}
System.out.println(hWalls);
}
}
The answer is simple
You can't do that
Because command line environment is different from swing, as swing can do such a thing as it deals with events and object, whereas, command line have no events.
So, maybe it's a right time to leave command line.
Related
So, I've created a simple app for moving a bug along a wire. The code works well (for the most part) though, I am having a few issues.
When reaching the end of the wire, the program terminates all well and good but I'm getting a double output that it's fallen off the wire when it reaches the end.
I am supposed to be writing a toString for this, but am having a bit of a hard time grasping why and how I should go about doing this.
If someone could assist with this, I'd greatly appreciate it.
import java.util.Scanner;
public class ClassPracticeMain {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int userInput;
Bug bug1 = new Bug();
bug1.setInitialPosition();
bug1.setInitialDirection();
System.out.println("Your starting position is " + bug1.initialPosition
+ " and you are facing " + bug1.getCurrentDirection()
);
while (bug1.getExit(1) != 0) {
System.out.println("Which way would you like to move? 1 for left/ 2 for right or 0 for exit");
userInput = input.nextInt();
bug1.move(userInput);
bug1.getCurrentDirection();
bug1.getCurrentPosition();
System.out.println("You are now at " + bug1.currentPosition + " and you are facing " + bug1.getCurrentDirection());
bug1.getExit(userInput);
}
}
}
public class Bug {
final int WIRELEFTEND=-15;
final int WIRERIGHTEND=15;
int initialPosition=0, currentPosition=0, direction,exit=1;
String currentDirection;
String left = "left";
String right = "right";
public int setInitialPosition(){
return initialPosition;
}
public int setInitialDirection(){
direction=1;
return direction;
}
public int getCurrentPosition(){
return currentPosition;
}
public String getCurrentDirection(){
if (direction== 1){
currentDirection=left;
} else if (direction == 2){
currentDirection=right;
}
return currentDirection;
}
public int move(int move){
if(move==1 && direction==1){
currentPosition=currentPosition-1;
return currentPosition;
} else if (move==1 && direction==2){
direction=1;
return currentPosition;
} else if (move==2 && direction==1){
direction=2;
return currentPosition;
} else if (move==2 && direction ==2){
currentPosition=currentPosition+1;
return currentPosition;
}
return 0;
}
public int getExit(int exit){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
exit=0;
} else{
exit=exit;
}
return 1;
}
}
You probably want to write
public int getExitStatus(){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
return 0;
}
return 1;
}
instead of your current getExist(int) function. It always returns 1, and setting the exit argument doesn't do anything.
I need to make a counter array for a Rock Paper Scissors game but can not figure out how to make user input call the enum, and i need to make the moves for the game a counter for them to be used and compared to.
This is my enum
public enum Moves {
Rock(1),
Paper(2),
Scissors(3),
Lizard(4),
Spock(5), ;
private int countOf = 0;
private int moveVal;
private ArrayList<Moves> movesList = new ArrayList<>();
Moves(int moveVal) {
}
public int getmoveVal() {
return moveVal;
}
public int getCountOf() {
for(Moves moveList : Moves.values()) {
countOf++;
}
return countOf;
}
And this is my class that would call it
public static void main(String[] args) {
RockPaperScissorGame rsg = new RockPaperScissorGame(3);
Moves move[] = Moves.values();
int playerMove = 0;
for(int i = 0; i < move.length; i++) {
}
boolean continueGame = true;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
while(continueGame)
{
System.out.println(rsg.moveChoices());
System.out.println("Enter Move:(1,2,3,4 or 5):");
playerMove = keyboard.nextInt();
rsg.playRound(move);
System.out.printf("AI %s!%n", rsg.getAIOutcome().toString());
System.out.printf("Player %s!%n", rsg.getPlayerOutcome().toString());
System.out.println(rsg.moveOutcome());
System.out.println(rsg.currentScore());
if(rsg.isGameOver())
{
System.out.println(rsg.currentWinTotal());
System.out.println("Do you want to Play Again(1 - Yes , 2 - No):");
int answer = keyboard.nextInt();
if(answer == 2)
{
continueGame = false;
}
else
{
rsg.reset();
}
}
}
You can iterate through values to find a Move matching that moveVal:
public Move fromMoveVal(int moveVal) {
for (Move m : Move.values()) if (m.moveVal == moveVal) return m;
return null;
}
I started my first java project and I get stuck in class scope. I cant initiate below code:
if (guessAttemts = MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.)
I will be appreciate if someone will help me to clarify what I doing wrong with that code: This NewGame class look like below.
class NewGame {
GuessAttempts GuessAttempts = new GuessAttempts();
private String WordToGuess;
private String CorrectGuesses;
private String misses;
int guessAttempts;
int MAX_Guesses = 9;
public NewGame(String WordToGuess) {
this.WordToGuess = WordToGuess;
CorrectGuesses = "";
misses = "";
guessAttempts = 0;
}
public boolean UserGuessing(char letter) {
boolean isHit = WordToGuess.indexOf(letter) != -1;
if (isHit) {
CorrectGuesses += letter;
} else {
misses += letter;
}
guessAttempts =+ 1;
return isHit;
}
if (guessAttemts = MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.");
}
}
To compare to values, you should use ==.
That means that your if-statement should look so:
if (guessAttemts == MaxGuesses) {
System.out.println("Sorry you used all your nine chances. Game Over.");
}
I'm a beginner/intermediate java programmer that is attempting to code something that is "out-of-my-league". The program is supposed to judge a boxing/MMA match in real time by pressing keys that correspond to different scoring values. I've figured out that I need a KeyListener, and the only way I've found to use that is with an applet.
The problem I've run into is the only cues I have to print out a score come from keyPresses and keyReleases. I want the score to print EVERY second, along with the time. I'm made a clock function and can print every second using another class with a main method, but I don't know how to do this in the applet.
Here's what I have so far:
import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.*;
public class KeyPressTwo
extends Applet
implements KeyListener{
private long t;
private ArrayList<Integer> keysDown = new ArrayList<Integer>();
private double controlOnlyValue = 1; //Stores the score per second for control only
private double threateningValue = 2.5; //Score for threatening with strikes, i.e. landing sig strikes, or sub attempts
private double damagingValue = 4; //Score for doing significant damage and dominating hea
private static double redTotal = 0; //Stores fighter score
private static double blueTotal = 0;
private static boolean firstRun = true;
private static boolean start = false;
private static boolean releasePressed = false; //Tells KeysReleased method when to wipe keysDown list
private static long roundBeganAt = 0; //System time when the round began 5
private static String redName;
private static String blueName;
public void init(){
this.addKeyListener(this);
//If names aren't hardcoded in, get them when the program is run
if (redName == null){
redName = JOptionPane.showInputDialog("Enter the red corner fighter's name.");
blueName = JOptionPane.showInputDialog("Enter the blue corner fighter's name.");
}
}
public void paint(){
setSize(500,500);
}
#Override
public void keyPressed(KeyEvent e) {
if(!keysDown.contains(e.getKeyCode()))
keysDown.add(e.getKeyCode());
//Starts the timer, don't print anything until started
if(keysDown.contains(KeyEvent.VK_SPACE)){
start = true;
roundBeganAt = System.currentTimeMillis();
}
//If it's been more than 1s
if(nextStep()){
//If space has been pushed
if(start){
if(keysDown.contains(KeyEvent.VK_Z) || keysDown.contains(KeyEvent.VK_NUMPAD1)){
redTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_X) || keysDown.contains(KeyEvent.VK_NUMPAD4)){
redTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_C) || keysDown.contains(KeyEvent.VK_NUMPAD7)){
redTotal += damagingValue;
}
if(keysDown.contains(KeyEvent.VK_COMMA) || keysDown.contains(KeyEvent.VK_NUMPAD3)){
blueTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_M) || keysDown.contains(KeyEvent.VK_NUMPAD6)){
blueTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_N) || keysDown.contains(KeyEvent.VK_NUMPAD9)){
blueTotal += damagingValue;
}
System.out.print("\n" +redName +": " +redTotal +" \t" +blueName +": " +blueTotal +"\t\t" +time());
releasePressed = true;
}
}
}
//Prints time since start (e.g. 2:05)
private static String time() {
String minutes = "";
String seconds = "";
int sRaw; //Gets time directly from system, will go above 60
int s; //Gets time from sRaw, (0 - 59)
sRaw = (int)((System.currentTimeMillis() - roundBeganAt))/1000;
s = sRaw%60;
minutes = Integer.toString(sRaw/60);
if(s < 10)
seconds = "0" +Integer.toString(s);
else seconds = Integer.toString(s);
return minutes +":" +seconds;
}
//Returns true if it's been more than1s since the last time it ran
public boolean nextStep() {
if(firstRun){
t = System.currentTimeMillis();
firstRun = false;
return true;
}
if(System.currentTimeMillis() > t + 1000){
t = System.currentTimeMillis();
return true;
}else
return false;
}
public void printList(){
for(int i : keysDown)
System.out.print(i +" ");
System.out.println();
}
#Override
public void keyReleased(KeyEvent e) {
if(releasePressed){
keysDown.clear();
releasePressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Maybe something along these lines would work for you:
Thread timerOutputThread = new Thread(new Runnable(){
public boolean running = true;
public void run(){
output();
}
private void output(){
try {
Thread.sleep(1000);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("PRINT THE SCORE HERE");
if(running){
output();
}
}
});
timerOutputThread.start();
Stick that code wherever you want the Thread timer to be started, and then fill in that spot where it says "PRINT THE SCORE HERE".
I've figured out that I need a KeyListener,.."
Or preferably key bindings.
..and the only way I've found to use that is with an applet.
Where on Earth did you hear that?!? It is definitely wrong. Start using a JFrame for this app. and it will work better because focus will be more reliable.
I am to create a game in cmd (not gui) in java, its a larger project, but for now, I'd love to know how would I create a 12x12 grid, spawn a player at 0,0 (left top corner) and move him around using keys?
I have attempted to create an array, but didn't seem to get movement to work. I'm a newbie, so would welcome any suggestions.
package hunters;
import java.io.*;
import java.util.*;
import java.awt.*;
public class Hunters {
private static int score;
private static String player = "P";
private static String move;
private static String emptyfield = "X";
private static String [][]a2 = new String [12][12];
private static int pr,cr;
public static void paint_board(){
for (int r = 0 ; r < a2.length; r++){
for (int c= 0; c <a2[r].length; c++){
a2 [r][c] = emptyfield;
a2[pr][cr] = player;
System.out.print(" "+a2[r][c]);
}
System.out.println("");
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
score = 0;
paint_board();
do{
System.out.println("Input your move");
move = in.nextLine();
if (move.equalsIgnoreCase("w")){
//move up
a2[pr-1][cr]= player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("s")){
//move down
a2[pr+1][cr]= player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("d")){
//move right
a2[pr][cr+1] = player;
//repaint
paint_board();
//check for collision
//check for health
}else if(move.equalsIgnoreCase("a")){
//move left
a2[pr][cr-1]=player;
//repaint
paint_board();
//check for collision
//check for health
}
}while(score !=5);
}
}
this is the way i'd like it to work. I have tried to create a separate Position class but I have failed in the process...`
Create a 2D array, have a way to paint a cell in the 2D array (which might contain different objects as defined by the value of the cell). So you might check the square to paint, and if the value is HUMAN (pre-defined constant) then draw a human at that location on the screen.
void paint_cell(int x, int y) {
if (array[x][y] == HUMAN) {
printf("H");
} else if (array[x][y] == ENEMY) {
printf("E");
} else if (array[x][y] == EMPTY) {
printf(" ");
}
}
void paint_maze() {
for (int j = 0; j < 12; j++) {
printf("|");
for (int i = 0; i < 12; i++) {
paint_cell(i,j);
}
printf("|\n");
}
}
When you receive a key event, go to the cell that contains the human and move it to a new destination depending on the key. Then draw the maze again.
"An Array" is definitely the right idea -- a two-dimensional array is probably what I would use to contain the spaces of the grid. But -- what is going to be in the array? Objects that represent the spaces that the user moves through? That's cool; you will have to figure out how to define those spaces, and figure out how to display each one on the screen.
You probably can't use a KeyListener to check for user keystrokes, since KeyListener is part of AWT/Swing, but you will need a way to get input from the keyboard. Reading from stdin is the easy way to go here. You will need to run a loop that listens for user input at the keyboard, and moves the user's "gamepiece" from square to square depending on which key they hit.