I am a beginner and I am creating a game. I am trying to use a variable (userOption) from another procedure (Weapons) in an if statement in the main procedure. The if statement is supposed to say that if userOption is 2 (a wooden stake) and if the Monster is a Werewolf then the wooden stake works and kills the Werewolf. I would like to do this for the other Monsters. Is it possible to do so? If so, how do you do it?
using System;
namespace Halloween
{
class Program
{
static void Weapons()
{
int userOption = 0;
Console.WriteLine("What weapon will you choose?");
Console.WriteLine("1. A silver bullet");
Console.WriteLine("2. A wooden stake");
Console.WriteLine("3. A priest");
Console.WriteLine();
userOption = Convert.ToInt32(Console.ReadLine());
if (userOption == 1)
{
Console.WriteLine("You have chosen a silver bullet as your weapon");
YesOrNo();
}
else if (userOption == 2)
{
Console.WriteLine("You have chosen a wooden stake as your weapon");
YesOrNo();
}
else if (userOption == 3)
{
Console.WriteLine("You have chosen a priest as your weapon");
YesOrNo();
}
else
{
Console.WriteLine("You have chosen not to arm yourself as you did not enter 3, 2 or 1");
YesOrNo();
}
Console.ReadLine();
}
static void YesOrNo()
{
string userChoice = "";
Console.WriteLine("Are you sure? Y or N?");
userChoice = Console.ReadLine();
if (userChoice == "Y")
return;
else if (userChoice == "N")
Weapons();
}
static void Main(string[] args)
{
string userName = "";
Console.WriteLine("Hey stop!");
Console.ReadLine();
Console.WriteLine("What is your name?");
userName = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("There is something lurking in the shadows {0}, you have a choice of three weapons",
userName);
Weapons();
Console.WriteLine("A shape has emerged from the shadow!");
Console.Read();
Console.WriteLine("It is moving towards you. It comes closer and closer until you can tell it is a...");
Console.Read();
Random rnd = new Random();
int monsterNumber = rnd.Next(3);
string[] arrayMonsters = {"Werewolf", "Vampire", "Ghost"};
string Monster = arrayMonsters[monsterNumber];
Console.WriteLine(Monster);
if (Monster == "Werewolf")
(userOption == 2)
Console.WriteLine("You drove the wooden stake through the Werewolf and successfully killed it");
}
}
}
Related
Im having trouble figuring out some compiler errors such as illegal start to expression in my if and else statements and an else without an if.
import java.util.Scanner;
public class A3Q1
{
public static void main(String[]args)
{
System.out.println("Perfect square identifier (Enter -1 to quit program)");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
String squareNumStr = sc.nextLine(); //taking user input
int squareNum = Integer.parseInt(squareNumStr); // taking string turning it into int
boolean exitCommand = true;
while(exitCommand)
{
if(squareNum >= 0) // will run method if int is a positive
{
perfectSquareIdentifier();
if(return == true) // using boolean return to print
{
System.out.println(squareNum + " is a perfect square.");
}
else if(return == false)
{
System.out.println(squareNum + " is not a perfect square");
}
}
else if(squareNum == -1)
{
exitCommand = false;
System.out.println();
}
}
System.ou.println("End of processing...");
}
public static boolean perfectSquareIdentifier(int squareNum)
{
int squareRoot = Math.sqrt(squareNum); //taking square root of user input
if (squareRoot*squareRoot == squareNum) // testing if the root provided is a root or a number with remainders
{
return true;
}
else
{
return false;
}
}
}
I'm writing board game and I need following functionality: player rolls two dices, if he rolled doubles (same number on both dice), he gets to roll again, if he rolled doubles again, he goes to jail.
In my Game class it looks like that
void logic::Game::rollTheDice() {
m_throwsInCurrentTurn++;
int firstThrow = m_firstDice.roll();
int secondThrow = m_secondDice.roll();
m_totalRollResult += firstThrow + secondThrow;
if (firstThrow == secondThrow) m_doublesInCurrentTurn++;
}
std::string logic::Game::checkForDoubles() {
std::string message;
if (m_doublesInCurrentTurn == 0 && m_throwsInCurrentTurn == 1) {
m_canThrow = false;
m_canMove = true;
}
if (m_doublesInCurrentTurn == 1 && m_throwsInCurrentTurn == 1) {
message = "Doubles! Roll again.";
m_canThrow = true;
m_canMove = false;
}
if (m_doublesInCurrentTurn == 1 && m_throwsInCurrentTurn == 2) {
m_canThrow = false;
m_canMove = true;
}
if (m_doublesInCurrentTurn == 2 && m_throwsInCurrentTurn == 2) {
message = "Doubles again! You are going to jail.";
m_canThrow = false;
m_canMove = false;
getActivePlayer().lockInJail();
}
return message;
}
void logic::Game::setInMotion(unsigned number) {
m_players[m_activePlayer].startMoving();
m_players[m_activePlayer].incrementPosition(number);
}
m_canThrow basicly enables or disables ability to click "Roll the Dice" button, m_canMove decides if player token can start moving, m_players[m_activePlayer] is std::vector<Player>, startMoving() does that,
void logic::Player::startMoving() {
m_isMoving = true;
}
needed for token movement, so baiscly not relevant here.
Last function from Game class I need to show you is reset(), used mainly for testing purposes
void logic::Game::reset() {
m_throwsInCurrentTurn = 0;
m_doublesInCurrentTurn = 0;
m_totalRollResult = 0;
}
Now finnaly Unit Test that sometimes goes wrong. Sometimes, I mean completely random, like 1 out of 10-20 times.
//first throw is double, second throw is not
TEST_F(GameTestSuite, shouldFinishAfterSecondRollAndMove) {
auto game = m_sut.get();
do {
if (game.getThrowsInCurrentTurn() == 2) game.reset();
game.rollTheDice();
game.checkForDoubles();
if (game.getThrowsInCurrentTurn() == 1 && game.getDoublesInCurrentTurn() == 1) {
ASSERT_EQ(game.canThrow(), true);
ASSERT_EQ(game.canMove(), false);
}
} while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() != 1);
ASSERT_EQ(game.canThrow(), false);
ASSERT_EQ(game.canMove(), true);
game.setInMotion(game.getTotalRollResult());
ASSERT_EQ(game.getActivePlayer().isMoving(), true);
ASSERT_EQ(game.getActivePlayer().getPosition(), game.getTotalRollResult());
}
This line exactly, ASSERT_EQ(game.canThrow(), false); sometimes is equal true after do-while loop that should end once m_canThrow is set to false
Shouldn't:
} while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() != 1);
be
} while (game.getThrowsInCurrentTurn() != 2 && game.getDoublesInCurrentTurn() <= 1);
You want to allow up to two turns but 0 or 1 doubles.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I'm really new to java and I was trying to practice using while and if statements through a guessing game app.
Everything seemed to work until I'm promped to play again. When I type Y, the loop ends. This isn't supposed to happen as the while argument at the beginning of the code says to keepPlaying if true.
I've tried playing with the argument to make it: while (answer == "Y"). I've played around with it but it always keeps exiting. Please help!!
Here's the code:
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
// TODO Auto-generated method stub
String answer = "Y";
int guess;
int number;
String again;
boolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepPlaying)
{
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = sc.nextInt();
while (guess > 10 || guess < 1)
{
System.out.print("I said, between 1 and 10. Try again: ");
guess = sc.nextInt();
}
number = (int)(Math.random() *10 + 1);
if (guess == number)
{
System.out.println("You're right!");
}
else
{
System.out.println("You're wrong! the number was " + number);
}
System.out.print("Play again? (Y or N)");
answer = sc.next();
if (answer == "Y")
{
keepPlaying = true;
}
else
{
break;
}
}
System.out.println("Thank you for playing");
}
}
In the comparison, you should compare using the String requirements:
if (answer.equals("Y")) // NOTE: I'd use .equalsIgnoreCase(...)
{
keepPlaying = true;
}
else
{
break;
}
Also note that since this comparison is at the end of the loop, you could simplify to:
keepPlaying = answer.equalsIgnoreCase("Y");
As you do not need the break statement since the loop will be re-evaluated.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
EDIT: Solved now thank you triple_r and AJNeufield for your help on this problem I was having.
I've looked around multiple websites and YouTube about this and I can't seem to find anything on what I am specifically looking for this as my format for the program is a good bit different than others. Therefore, it's hard to decipher where I need to put the things I do need that I know of.
Please note that I'm relatively new to C++ so I'd appreciate all the feedback or criticism you might provide me.
Also, note my code does compile and run it just does not allow me to put in more than one input and more than likely does not allow for a switch of player turns.
Quick Edit: Switched the code with the new setup suggested by triple_r but I seemed to have messed it up somewhere along the line and it does compile(with the exception of x and y not being utilized and one other error) but it always starts off with player 2 going first and as soon as it receives input it ends automatically with a segmentation fault.
#include <iostream>
#include <cstdlib>
using namespace std;
//////////////////////////////////////////////////////////
void initboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
for (y=0;y<3;y++)
board[x][y]=' ';
return;
}
//////////////////////////////////////////////////////////
void printboard(char board[3][3])
{
int x,y;
for (x=0;x<3;x++)
{
cout<<"\n";
for (y=0;y<3;y++)
{
cout<<" "<<board[x][y]<<" ";
if (y<2) cout<<"|";
}
if (x<2) cout<<"\n===========";
}
return;
}
//////////////////////////////////////////////////////////
void getmove(char board[3][3], int player)
{
return;
}
//////////////////////////////////////////////////////////
int main()
{
bool done=false;
char board[3][3];
int x,y,player=1,turn,playerchoice,playermark;
initboard(board);
turn=0;
do
{
if (player==1)
playermark='X';
else
playermark='O';
if (turn%2)
player=1;
else
player=2;
cout<<"Player "<<player<<" where do you want to move?: ";
cin>>playerchoice;
if (playerchoice==1)
{
board[0][0]=playermark;
}
else if (playerchoice==2)
{
board[0][1]=playermark;
}
else if (playerchoice==3)
{
board[0][2]=playermark;
}
else if (playerchoice==4)
{
board[1][0]=playermark;
}
else if (playerchoice==5)
{
board[1][1]=playermark;
}
else if (playerchoice==6)
{
board[1][2]=playermark;
}
else if (playerchoice==7)
{
board[2][0]=playermark;
}
else if (playerchoice==8)
{
board[2][1]=playermark;
}
else if (playerchoice==9)
{
board[2][2]=playermark;
}
else
{
cout<<"Invalid move ";
}
if (board[x][y]!=' ')
cout<<"Move is already taken.";
board[x][y]=playermark;
if(board[x][y]==' ')
turn++;
}while (!done);
void printboard(char board[3][3]);
return 0;
}
EDIT: based on the updated code
So, the first thing I can see is that you are using x and y in your program but you don't initialize them or assign any values to them. Also, try to use functions/classes/... yo make your code more readable. You already have a function for player move but you are not using it. You can move the large if statement inside that function and that will make your main code shorter and more readable.
Here are my comments on the main part of your program:
int main()
{
// add a new variable to see if the move was valid or not:
bool done=false, validmove = true;
char board[3][3];
int x, y, player = 1, turn = 0, playerchoice, playermark;
initboard(board);
do
{
// swap the two `if`s so you decide who`s turn it is then assign the player mark,
// also, reverse the condition to make sure turn '0' is player 1's turn.
if (!(turn % 2))
player = 1;
else
player = 2;
if (player == 1)
playermark = 'X';
else
playermark = 'O';
cout << "Player " << player << " where do you want to move?: ";
cin >> playerchoice;
// Assign `x` and `y` here instead of updating the board, because you want to make
// sure that the move is valid before putting the mark:
validmove = true;
if (playerchoice == 1)
{
x = 0; y = 0;
}
else if (playerchoice == 2)
{
x = 0; y = 1;
}
else if (playerchoice == 3)
{
x = 0; y = 2;
}
else if (playerchoice == 4)
{
x = 1; y = 0;
}
else if (playerchoice == 5)
{
x = 1; y = 1;
}
else if (playerchoice == 6)
{
x = 1; y = 2;
}
else if (playerchoice == 7)
{
x = 2; y = 0;
}
else if (playerchoice == 8)
{
x = 2; y = 1;
}
else if (playerchoice == 9)
{
x = 2; y = 2;
}
else
{
cout << "Invalid move, try again!";
// Make sure to mark the move as invalid so they get a chance to
// change their move:
validmove = false;
}
// check to see if the turn was valid:
if(validmove)
{
if (board[x][y] != ' ')
{
cout << "Move is already taken, try again";
}
else
{
board[x][y] = playermark;
turn++;
}
}
// have to make sure you have a condition for end of game. A simple
// one is to check if turn is less than `9`, otherwise the board is
// full:
if(turn == 9)
done = true;
// you probably want to add a few more checks to see who won the game.
}while (!done);
// when calling a function, no need to put the return type or parameter type:
printboard(board);
return 0;
}
========================================================================
There are two do-while loops in your program and both seem to be meant as a game loop. What I would do is:
initboard(...);
turn = 0;
do{
//this is the game loop
...;
if( validturn )
turn++;
}while(!done);
release_resources(...);
return 0;
so, you fold everything into one loop. In that loop, you want to:
find who's turn it is:
if (turn % 2)
player = 1;
else
player = 2;
get users input:
std::cin >> playerchoice;
...
convert player choice to grid location:
switch ( move )
{
case 0:
x = 0;
y = 0;
break;
case 1:
...;
...
default:
//invalid move
}
see if the move is valid:
if( board[x][y] != ' ' )
//already taken, invalid move
then apply the move:
board[x][y] = playermark;
I hope this helps.
Your cin >> playerchoice is outside your do { ... } while ( moves != 9); loop. Move it inside.
import javax.swing.JOptionPane;
public class sam{
public static void main(String[]args){
String a;
String b;
int c;
sam s1 = new sam();
a=s1.getInfo();
c=s1.getBalance();
b=s1.getMenu(a,c);
}
//menu method starts here
public String getMenu (String c, Integer d) {
String[] a;
String[] choices = { "Account Balance", "Deposit", "Withdraw", "User Account", "Exit options"};
String input = (String) JOptionPane.showInputDialog(null, "What would you like to do?",
"ATM menu", JOptionPane.QUESTION_MESSAGE, null,choices,choices[0]);
if ((choices[0] == choices[0])){
JOptionPane.showMessageDialog(null,"Your Account Balance is: "+d,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//the if statement is executing properly
else if ((choices[1] == choices[1])){
String in=JOptionPane.showInputDialog("Deposit: ");
int deposit=Integer.parseInt(in);
int add=d+deposit;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+add,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//but when I chose account balance it displays the if statement not the else-if one
else if ((choices[2] == choices[2])){
String in=JOptionPane.showInputDialog("Withdraw: ");
int withdraw=Integer.parseInt(in);
int sub=d+withdraw;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+sub,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[3] == choices[3])){
JOptionPane.showMessageDialog(null," "+c,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[4] == choices[4])){
JOptionPane.showMessageDialog(null,"The program will be terminated in a few seconds","ATM machine",JOptionPane.INFORMATION_MESSAGE);
}
return input;
}
//I'm quite new to programming, I rushed coded it for finals.
All of your if statements will evaluate to true. I think your intentions were to compare String c with each of the Strings in the choices array.
When comparing Strings always use .equals() not ==.
Example:
if (c.equals(choices[0])) {
// code
} else if (c.equals(choices[1])) {
//code
} else if (c.equals(choices[2])) {
// code
}