i want to repeat this game until user enters a invalid input other than r/R , p/P or s/S
i created the ur_choice function so that i can get a negative value in case a wrong input is submitted now how do i loop this ur_choice() function until it returns -1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int ur_choice(){
printf ("choose r/R for Rock p/P for Paper s/S for Scissor : ");
char choice = getchar();
if (choice == 'r' || choice == 'R')
return 0;
if (choice == 'p' || choice == 'P')
return 1;
if (choice == 's' || choice == 'S')
return 2;
else{
return -1;
}
}
int pc_choice(){
srand(time(0));
int random = rand() % 3;
return random;
}
int game(int pc, int you){
if (pc == you)
return -1;
if (pc == 0 && you == 1 || pc == 1 && you == 2 || pc == 2 && you == 0)
return 0;
else if (pc == 0 && you == 2 || pc == 1 && you == 0 || pc == 2 && you == 1)
return 1;
return 2;
}
int main(){
char symbol[3][10] = {"rock","paper","scissor"};
int a,b,result;
a=ur_choice();
if (a>=0){
b=pc_choice();
printf ("You choosed : %s\nPC choosed : %s\n",symbol[a],symbol[b]);
result=game(a,b);
if (result == -1) {
printf("Game Draw!\n");
}
else if (result == 1) {
printf("Wow! You have won the game!\n");
}
else {
printf("Oh! You have lost the game!\n");
}
}
else{
printf("Invalid choice!\n");
exit(0);
}
}
When you want to repeat something, you can use a while statement.
Hence, you can assign a value to your variable a and check whether it returns -1 or not at the same time using this syntax.
while ((a = ur_choice()) != -1) {
// game's content
}
Related
I'm new to C and I'm trying to make a tic-tac-toe game for my college project and I'm struggling on how to reset my array in my game.
Every time I play again it does not reset the array. Can anyone help me with this?
Here is the code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
char space[3][3] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
void board();
int checkWin();
int game();
void reset();
int main(){
int choice = -1;
do{
printf("\n\n\n\n\n\n\n\t\t\t ================\n");
printf("\t\t\t Tic Tac Toe\n");
printf("\t\t\t ================\n");
printf("\t\t -----------Menu-----------\n\n");
printf("\t\t 1. Play\n");
printf("\t\t 2. Exit\n");
scanf("%d", &choice);
switch(choice){
case 1: game();
break;
case 2: printf("Goodbye!!");
exit(0);
break;
default: printf(".......Wrong Key !.......Try Again!......");
break;
}
}while(choice != 0);
}
int game(){
int player = 1, i, choice;
char mark;
do
{
system("cls");
board();
player = (player % 2) ? 1 : 2;
printf("Player %d, enter a number: ", player);
scanf("%d", &choice);
mark = (player == 1) ? 'X' : 'O';
if (choice == 1)
space[0][0] = mark;
else if (choice == 2)
space[0][1] = mark;
else if (choice == 3)
space[0][2] = mark;
else if (choice == 4)
space[1][0] = mark;
else if (choice == 5)
space[1][1] = mark;
else if (choice == 6)
space[1][2] = mark;
else if (choice == 7)
space[2][0] = mark;
else if (choice == 8)
space[2][1] = mark;
else if (choice == 9)
space[2][2] = mark;
else
{
printf("Invalid move ");
player--;
getch();
}
i = checkWin();
player++;
}while (i == - 1);
board();
reset();
if (i == 1)
printf("==>\aPlayer %d win \n\n", --player);
else
printf("==>\aGame draw\n\n");
getch();
return 0;
}
int checkWin(){
if (space[0][0] == space[0][1] && space[0][1] == space[0][2])
return 1;
else if (space[1][0] == space[1][1] && space[1][1] == space[1][2])
return 1;
else if (space[2][0] == space[2][1] && space[2][1] == space[2][2])
return 1;
else if (space[0][0] == space[1][0] && space[1][0] == space[2][0])
return 1;
else if (space[0][1] == space[1][1] && space[1][1] == space[2][1])
return 1;
else if (space[0][2] == space[1][2] && space[1][2] == space[2][2])
return 1;
else if (space[0][0] == space[1][1] && space[1][1] == space[2][2])
return 1;
else if (space[0][2] == space[1][1] && space[1][1] == space[2][0])
return 1;
else if (space[0][0] != space[0][0] && space[0][1] != space[0][1] && space[0][2] != space[0][2] &&
space[1][0] != space[1][0] && space[1][1] != space[1][1] && space[1][2] != space[1][2] && space[2][0]
!= space[2][0] && space[2][1] != space[2][1] && space[2][2] != space[2][1])
return 0;
else
return - 1;
}
void reset(){
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
space[i][j] = 0;
}
}
}
void board(){
system("cls");
printf("\n\n\tTic Tac Toe\n\n");
printf("Player 1 (X) - Player 2 (O)\n\n\n");
printf(" | | \n");
printf(" %c | %c | %c \n", space[0][0], space[0][1], space[0][2]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", space[1][0], space[1][1], space[1][2]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", space[2][0], space[2][1], space[2][2]);
printf(" | | \n\n");
}
I tried using for loop but it does not work; how can I solve this?
void reset(){
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
space[i][j] = 0;
}
}
}
Your reset function is filling the entire 3x3 board matrix with zeros; these represent the nul character, not the character representing the '0' digit. Those nul characters aren't printed (and cannot be), so the board looks 'wrong' after a reset.
However, simply changing the space[i][j] = 0; line to space[i][j] = '0'; won't work! Although you will then initially see a board full of 0 digits, the way your checkWin() function works will then ensure that "Player 1" will have won the new game immediately after their first move, because there will already be rows/columns/diagonals of three identical characters.
So, to get the original ('1' thru '9') display, write your reset() function as below. (Note that the C Standard requires that the characters representing the numerical digits be in order and contiguous, so adding a value of 1 thru 9 to the '0' character will yield the appropriate digit character.)
void reset()
{
int number = 1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
space[i][j] = number++ + '0';
}
}
}
Alternatively, you can just declare and initialize a new 'board array' with the data in it, then just use memcpy to rest the space array with the contents of that:
#include <string.h> // For "memcpy"
void reset()
{
char empty[3][3] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'} };
memcpy(space, empty, sizeof(space));
}
Note, also that all the tests in the following statement are wrong:
else if (space[0][0] != space[0][0] && space[0][1] != space[0][1] && space[0][2] != space[0][2] &&
space[1][0] != space[1][0] && space[1][1] != space[1][1] && space[1][2] != space[1][2] && space[2][0]
!= space[2][0] && space[2][1] != space[2][1] && space[2][2] != space[2][1])
Each one of these is testing if an element is not equal to itself. This can never be true, so that else if block (the return 0; line) is never executed. But you don't actually need it, so you can just delete that block.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generaterandomno(int n)
{
srand(time(NULL));
return rand() % n;
}
int greater(char char1, char char2)
{
//For Rock, Paper, Scissors - Returns 1 if c1>c2 and 0 otherwise. If c1 == c2 it will return -1
if (char1 == char2)
{
return -1;
}
else if ((char1 == 'r') && (char2 == 's'))
{
return 1;
}
else if ((char2 == 'r') && (char1 == 's'))
{
return 0;
}
else if ((char1 == 'p') && (char2 == 'r'))
{
return 1;
}
else if ((char2 == 'p') && (char1 == 'r'))
{
return 0;
}
else if ((char1 == 's') && (char2 == 'p'))
{
return 1;
}
else if ((char2 == 's') && (char1 == 'p'))
{
return 0;
}
}
int main()
{
int playerscore = 0, compscore = 0, temp;
char playerchar, compchar;
char dict[] = {'r', 'p', 's'};
printf("Welcome to The Rock, Paper, Scissors Game, I hope you will enjoy\n");
for (int i = 0; i < 3; i++)
{
// Take Player 1's input
printf("Player 1:\n");
printf("Choose 1 for Rock, 2 for Paper and 3 for Scissors\n");
scanf("%d", &temp);
getchar();
playerchar = dict[temp - 1];
printf("You chose %c\n\n", playerchar);
// Generate computer's input
printf("Computer's Turn:\n");
printf("Choose 1 for Rock, 2 for Paper and 3 for Scissors\n");
temp = generaterandomno(3) + 1;
compchar = dict[temp - 1];
printf("Computer chose %c\n\n", compchar);
// Compare the scores
if (greater(compchar, playerchar) == 1)
{
compscore += 1;
printf("Computer got it!!!\n");
}
else if (greater(compchar, playerchar) == -1)
{
compscore += 1;
playerscore += 1;
printf("It's a Draw!!!\n");
}
else
{
playerscore += 1;
printf("You got it!!!\n");
}
printf("You: %d\nComp: %d\n\n",playerscore, compscore);
}
if (playerscore > compscore)
{
printf("----------------------\n");
printf("------You Won!!!------\n");
printf("----------------------\n");
}
else if (compscore > playerscore)
{
printf("---------------------\n");
printf("---Computer Won!!!---\n");
printf("---------------------\n");
}
else
{
printf("----------------------\n");
printf("----It's a Draw!!!----\n");
printf("----------------------\n");
}
return 0;
}
char dict[] = {'r', 'p', 's'};
I have a problem with this 👆 how can I write multiple characters inside an array in c please get me a solution. I want to write rock paper and scissors replacing this please get a solution for me.....
I think what you are asking is about outputting 'rock' instead of 'r' when confirming the choice.
You could create a 2 dimensional array to hold the strings instead of a one dimensional array. For example...
char rps[][] = { "rock", "paper", "scissors" };
This would allow you to get at both the initials for example...
rps[0][0] would be 'r'
or the whole string...
rps[0] is "rock"
The important thing to note is that a string is just a char array with a null terminator.
These links will help explain a bit more.
https://www.programiz.com/c-programming/c-strings
https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/array-of-c-string
I'm really having a difficult time to make my counter to not count if the numbers are different than {1,-1,-2,-2}.
Here is what I'm trying to do:
if(n == 1 || -1 || 2 || -2){
cont++;
}
else{
}
But it's not working, the program continues to count even when the numbers are different than those above.
Here is the entire code:
int main(void){
int n,pri,ult,dir,esq,cima,baixo;
int cont = 0;
int soma = 0;
scanf("%d", &n);
while (n != 0){
soma = cont;
if (n == 1)
{
dir = n;
}
if (n == -1)
{
esq = n ;
}
if (n == 2){
cima = n;
}
if (n == -2)
{
baixo = n;
}
if(cont == 1)
{
pri = n;
}
if(n == 1 || -1 || 2 || -2){
cont++;
}
else{
}
ult = n;
scanf("%d", &n);
}
printf("cont %d\n", cont);
if (soma == 0){
printf("O veiculo fez um caminho fechado");
}
else{
printf("O veiculo fez um caminho aberto");
}
}
No, chaining of logical OR operators (||) is not possible. You need to check each one of them individually. Change
if(n == 1 || -1 || 2 || -2)
to
if(n == 1 || n == -1 || n == 2 || n == -2)
Otherwise, due to left-to-right evaluation rule (associativity), what you're end up getting is
if ( (n == 1) || -1 || 2 || -2)
which is same as either
if( 0 || -1 || 2 || -2)
or
if( 1 || -1 || 2 || -2)
both of which yields 1 as result as the other operands of || are non-zero (TRUE).
Why is it that when I start the program, I will start by doing the first printf statement, and then i input, then it simultaneously does two printf statements.
Is this what's causing the infinite loop as well?
Starting the program
Player 1: Choose your symbol:
a
This part, they both output simultaneously
Player 2: Choose your symbol:
player1, enter placement:
And then I get an infinite loop. Is it due to the simultaneous output?
code
include <stdio.h>
int check(char player);
void move(char player);
char board[3][3] ;
int main(void)
{
int first;
char player1, player2;
printf("Player 1: Choose your symbol: \n");
player1 = getchar();
printf("Player 2: Choose your symbol: \n");
player2 = getchar();
int i=0;
int win;char turn;
while(win == 0)
{
if((i%2) == 0){
turn = player1;
move(player1);
win = check(player1);
print();}
else {
turn = player2;
move(player2);
win = check(player2);
print();}
i++;
}
if (i == 8)
printf("its a tie");
else
printf("the winner is %c", turn);
return 0;
}
/*printing the board that takes in a placement int*/
void print(void)
{
int r;
printf("\n");
for (r = 0; r < 3; r++){
printf(" %c | %c | %c \n" , board[r][0], board[r][2], board[r][3]);
if (r != 2)
printf("___________\n");
}
printf("\n");
return;
}
/*check to see if someone won*/
int check(char player)
{
int r, c;
for ( r = 0 ; r <3 ; r++)
{
if ((board[r][0] == player) && (board[r][1] == player) && (board[r][2] == player))
return 1;
}
for ( c = 0 ; c <3 ; c++)
{
if ((board[0][c] == player) && (board[1][c] == player) && (board[2][c] == player))
return 1;
}
if((board[0][0] == player) && (board[1][1] == player) && (board[2][2] == player))
return 1;
if((board[0][2] == player) && (board[1][1] == player) && (board[2][0] == player))
return 1;
return 0;
}
void move(char player)
{
int place;
printf("player1, enter placement: \n");
scanf("%d", &place);
if (place == 1)
board[0][0] = player;
else if (place == 2)
board[0][1] = player;
else if (place == 3)
board[0][2] = player;
else if (place == 4)
board[1][0] = player;
else if (place == 5)
board[1][1] = player;
else if (place == 6)
board[1][2] = player;
else if (place == 7)
board[2][0] = player;
else if (place == 8)
board[2][1] = player;
else if (place == 9)
board[2][2] = player;
}
Because first getchar() leaves a newline character in the input stream which consumed by the subsequent getchar(). One way is to use another getchar() to consume the unwanted newline chars.
printf("Player 1: Choose your symbol: \n");
player1 = getchar();
getchar(); // consume a newline
printf("Player 2: Choose your symbol: \n");
player2 = getchar();
getchar(); // consume a newline
You're probably getting the '\n' character from getchar();
You could do something like:
printf("Player 2: Choose your symbol: \n");
player2 = getchar();
while ( player2 != '\n' ) { player2 = getchar(); }
to clear standard input before reading again with the next getchar();
/*
Program to calculate trip and plan flights
*/
#define TRIP 6
#define NUMLEG 10
#include <stdio.h>
#include <string.h>
int input_trip(void);
int input_leg(int travel_leg[NUMLEG], int index);
char input_travel_type(char leg_type[TRIP][NUMLEG], int n, int index, int leg_num);
int main(void)
{
int row, col, trip_num, index, travel_leg[NUMLEG], leg_num, n;
char leg_type[TRIP][NUMLEG];
trip_num = input_trip();
for (index =0; index < trip_num; index++)
{
leg_num = input_leg(travel_leg,index);
printf("At Trip Number:%d\n", index);
printf("Number of legs %d\n", leg_num );
printf("A Airplane\n");
printf("R Train and rail travel\n");
printf("B Bus\n");
printf("C Car\n");
printf("F Ferry\n");
printf("S Cruise ship\n");
printf("M Motorcycle\n");
printf("Y Bicycle\n");
printf("T Boat other than a ferry or cruise ship\n");
printf("D Dirigible\n");
printf("O Other\n");
printf("NOTE!!:Please using capital letters (case sensitive).\n");
for (n = 0; n < leg_num; n ++)
{
printf("At leg Number%d\n", n);
input_travel_type(leg_type, n, index, leg_num);
}
}
for (index = 0; index < trip_num; index++)
{
printf("Trip#:%d Num_leg:%d ", index+1, travel_leg[index]);
for (n = 0; n < leg_num ; n++)
printf("Leg_type(#%d):%c ",n+1, leg_type[index][n]);
printf("\n");
}
return 0;
}
int input_trip(void)
{
int trip_num;
printf("Please enter the number of trips:");
scanf("%d", &trip_num);
// if( (trip_num <= TRIP) && (trip_num >= 3))
if( (trip_num <= TRIP) && (trip_num >=1) )
{
return trip_num;
}
else
{
while ((trip_num < 1) || ( trip_num > TRIP))
{
printf("Invalid number of trip. (Min of 3 trips and Max 6 trips).\n"); /*input number of trips*/
printf("Please enter the number of trips:");
scanf("%d", &trip_num);
if( (trip_num <= TRIP) && (trip_num >= 1))
{
return trip_num;
}
}
}
}
int input_leg(int travel_leg[NUMLEG], int index)
{
int leg_num, i;
char travel_type, checkA, A, R, B, C, F, S, M, Y, T, D, O;
printf("Please enter the number of legs in your trip:");
scanf("%d", &leg_num);
if ( (leg_num <= NUMLEG) && (leg_num > 0) )
{
travel_leg[index]=leg_num;
return leg_num;
}
else
{
while ( (leg_num < 0) || (leg_num > NUMLEG))
{
printf("Invalid number of legs(min 1 and max 10 legs).\n");
printf("Please enter the number of legs in your trip:");
scanf("%d", &leg_num);
if ( (leg_num <= NUMLEG) && (leg_num > 0) )
{
travel_leg[index]=leg_num;
return leg_num;
}
}
}
}
char input_travel_type(char leg_type[TRIP][NUMLEG], int n, int index, int leg_num)
{
char travel_type, checkA;
printf("Please enter the leg type for leg#%d:", n+1);
scanf("%c", &travel_type);
checkA = ( (travel_type == 'A') || (travel_type == 'R') || (travel_type == 'B') ||
(travel_type == 'C') || (travel_type == 'F') || (travel_type == 'S') ||
(travel_type == 'M') || (travel_type == 'Y') || (travel_type == 'T') ||
(travel_type == 'D') || (travel_type == '0') );
if (checkA == 1)
{
leg_type[index][n]=travel_type;
}
else
{
while (checkA != 1)
{
printf("Please enter the leg type for leg#%d:", n+1);
scanf("%c", &travel_type);
checkA = ( (travel_type == 'A') || (travel_type == 'R') || (travel_type == 'B') ||
(travel_type == 'C') || (travel_type == 'F') || (travel_type == 'S') ||
(travel_type == 'M') || (travel_type == 'Y') || (travel_type == 'T') ||
(travel_type == 'D') || (travel_type == '0') );
if (checkA == 1)
leg_type[index][n]=travel_type;
}
}
}
(I ask this question a while back but my code was too messy so I re-wrote it in functions so it was easier to read)
The problem I'm having is that my leg_num is getting over written every time I step out of the loop, so when I try to print out in the printf the last leg_num I put in is the number that is being use at:
for (n = 0; n < leg_num ; n++) the 2nd one in the printing loop
EDITED
So when I put in 2 trips trip# 1 has 3 legs trip# 2 has 2 legs when it runs through the printing loops it will only print 2 legs for each trip.
Trip#:1 Num_leg:3 Leg_type(#1):C Leg_type(#2):B
Trip#:2 Num_leg:2 Leg_type(#1):A Leg_type(#2):R
Trip#:1 Num_leg:1 Leg_type(#1):S Leg_type(#2):
Trip#:2 Num_leg:2 Leg_type(#1):F Leg_type(#2):S
Everything else works fine because I put printf statements along the way to check if that was the issue but it wasn't. I was thinking of saving the leg_num into a array and using that but not sure how to do it, plus the fact that this is part of a homework and our professor is restricting almost everything but the basic loops simple arrays.
printf("Trip#:%d Num_leg:%d ", index+1, travel_leg[index]);
for (n = 0; n < leg_num ; n++)
Change to
printf("Trip#:%d Num_leg:%d ", index+1, travel_leg[index]);
for (n = 0; n < travel_leg[index] ; n++)