Re-assign value to variable if rand() repeats a number - c

I am making a tic tac toe game in which the user competes against the computer. Whenever the person chooses a spot between 1 and 9, the computer needs to choose one too. For this, I am using rand(). However, if the spot is already taken, I need the computer to calculate a new one. I've tried using while and do-while loops but when I apply them, cmd stops working and doesn't let me continue the game.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct symbol{
int marcado;
char simbolo;
} SPOT;
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
void table();
void User();
void AI();
int main(){
system("cls");
User();
AI();
Check();
return 0;
}
void table(){
printf("\n %c | %c | %c ",spot1.symbol,spot2.symbol,spot3.symbol);
}
this is the function in which the user chooses a spot:
void User(){
char choice;
do{
do{
board();
printf("\n\nChoose a spot: ");
fflush(stdin);
scanf("%c",&choice);
}while(choice < '1' || choice > '3');
switch(choice){
case '1': if(choice == '1'){
system("cls");
if(casilla1.marcado == 1){
printf("\noccupied\n");
}
else if(casilla1.marcado == 0){
casilla1.marcado = 1;
casilla1.simbolo = 'X';
AI();
}
}
break;
case '2': if(choice == '2'){
system("cls");
if(casilla2.marcado == 1){
printf("\noccupied\n");
}
else if(casilla2.marcado == 0){
casilla2.marcado = 1;
casilla2.simbolo = 'X';
AI();
}
}
break;
case '3': if(choice == '3'){
system("cls");
if(casilla3.marcado == 1){
printf("\noccupied");
}
else if(casilla3.marcado == 0){
casilla3.marcado = 1;
casilla3.simbolo = 'X';
AI();
}
}
break;
}while(Check() != 0 && Check() != 1);
}
and this is the function for the computer. In which I am having trouble in the 'else if' statements since I don't know what to put in them.
void AI(){
int random;
srand(time(NULL));
random = rand() % 3 + 1;
if (random == 1){
if(casilla1.marcado == 0){
casilla1.simbolo = 'O';
casilla1.marcado = 1;
}
else if(casilla1.marcado == 1){
random = rand() % 3 + 1
}
}
if (random == 2){
if(casilla2.marcado == 0){
casilla2.simbolo = 'O';
casilla2.marcado = 1;
}
else if(casilla2.marcado == 1){
random = rand() % 3 + 1;
}
}
if (random == 3){
if(casilla3.marcado == 0){
casilla3.simbolo = 'O';
casilla3.marcado = 1;
}
else if(casilla3.marcado == 1){
random = rand() % 3 + 1;
}
}
}
As I said before, I've tried putting the whole AI() inside the different types of loops, putting only rand() inside them, and so on, and still can't get it to work.

First, choose your data structures better. Instead of:
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
use
SPOT casilla[3] = { {0,'1'}, {0,'2'}, {0,'3'} };
As a consequence, the switch constructs are not needed any longer. Instead of:
if(casilla1.marcado == 0){
if(casilla2.marcado == 0){
if(casilla3.marcado == 0){
use:
if(casilla[random-1].marcado == 0){
the person chooses a spot between 1 and 9
and
random = rand() % 9 + 1;
You only have 3 casilla. Where are the other 6?
I've tried using while and do-while loops
In AI() there are no loops. Maybe you can show us a code with loops?
printf("\n\nChoose a spot: ");
fflush(stdin);
You probably wanted to fflush() stdout?

Related

Rock Paper .. game

This code runs just fine.
but there is some minor mistake in the program. I don't know what's the problem 'cause it's like I keep on winning the game and the computer just loses the game every time. 3
the game Rock, Paper, Scissors. My problem is if I execute the program, I just keep winning.I need the game to let the computer win. How can I rectify this?
#include <stdio.h
#include <time.h>
int Random(int n) {
srand(time(NULL));
printf("%d\n", rand() % 3); }
int greater(char ch1, char ch2) {
if (ch1 == ch2)
{
return -1;
}
else if ((ch1 == 'R') && (ch2 == 's'))
{
return 1;
}
else if ((ch2 == 'R') && (ch1 == 's'))
{
return 0;
}
else if ((ch1 == 's') && (ch2 == 'p'))
{
return 1;
}
else if ((ch2 == 's') && (ch1 == 'p'))
{
return 0;
}
else if ((ch1 == 'p') && (ch2 == 'r'))
{
return 1;
}
else if ((ch2 == 'p') && (ch1 == 'r'))
{
return 0;
}
}
int main() {
char playerchar, computerchar, a;
int playerscore = 0, compscore = 0, b;
char ch[] = {'R', 'P', 'S'};
printf("\n");
printf("~~~~~Welcome to the Rock, Paper, Scissors Game~~~~~\n\n");
printf("Choose a number\n 1. for Rock\n 2. for Paper\n 3. for Scissiors\n");
for (int i = 0; i < 3; i++)
{
printf("Player's Turn :\n");
scanf("%d", &b);
getchar();
playerchar = ch[b - 1];
printf("You chose %c\n", playerchar);
printf("Computer's Turn :\n");
b = Random(3) + 1;
computerchar = ch[b - 1];
printf("Computer chose %c\n", computerchar);
if ((greater(computerchar, playerchar) == 1))
{
compscore += 1;
printf("Computer got it!\n\n");
}
else if ((greater(computerchar, playerchar) == -1))
{
compscore += 1;
playerscore += 1;
printf("It's a draw\n");
}
else
{
playerscore += 1;
printf("You got it!\n\n");
}
printf("You : %d\nComputer: %d\n\n",playerscore,compscore);
}
if (compscore > playerscore)
{
printf("Computer win the game!\n\n");
}
else if (playerscore > compscore)
{
printf("You win the game!\n\n");
}
else
{
printf("The game is draw\n");
}
return 0;}
There's really no point complex if statements for determining the winner. Just realize that rock paper scissors is basically just a directed cycle graph.
// Returns winner in rock paper scissors
// 0 - Rock, 1 - Paper, 2 - Scissors
// Return values:
// 0 - draw
// 1 - a win, b loose
// -1 - b win, a loose
int rps(int a, int b) {
if(a == b) return 0;
return (a+1) % 3 == b ? -1 : 1;
}
Normal rps (rock, paper, scissors) has 3 nodes in the graph. This can actually easily be generalized to n nodes. The algorithm works like this. Start on node a. If it's the same as b, then it's a draw. Otherwise, check how many steps it is required to to go around the graph to get to b and determine the winner depending on if the number of steps is even or odd.
int rpsn(int a, int b, int n) {
if(a == b) return 0;
int steps = 0;
while((a+steps) % n != b) steps++;
return steps % 2 ? -1 : 1;
}
Read about Rock, Paper, Scissors, Lizard, Spock for a 5 node version.
I'm fairly confident that the loop could be exchanged for a single clever math operation, but I'm having a brain freeze at the moment. I'll update the post if I find it.
EDIT:
I found a way. Here is a very short rps function with no loops for arbitrary n:
// Returns the number of steps required to go from a to b
int steps(int a, int b, int n) {
return (n+b-a) % n;
}
int rpsn(int a, int b, int n) {
if(a == b) return 0;
return steps(a,b,n) % 2 ? -1 : 1;
}
The reason for doing (n+b-a) % n instead of (b-a) % n is that we need the left operand of % to be nonnegative.
First of all, srand should be called just once at the beginning of the program. You call it on every call of Random().
But the bigger issue is that your function Random() does not return anything, it just prints the value. This should have grnerated a warning in your compiler. This probably means that Random always returns 0.
To fix the problem, do return rand() % 3; instead of printing it.

Using arrays to compare char

I'm coding this pattern game, but I am having difficulties in storing the previous input of the users "uno" and "dos" to a array so it can be compared, if same it will ask for another input which has not been picked. Example of This
Round 1:
Player 1 Inputs : -> A
Player 2 Inputs : -> B
Valid
Round 2:
Player 1 Inputs : -> L
Player 2 Inputs : -> V
Valid
Round 3:
Player 1 Inputs : -> A (Invalid Already been used)
enter char again
That above is an example i am trying to achieve. I will post the code below. I would appreciate the help very much.
#include <stdio.h>
#include <string.h>
#define SWITCH(_g0,_g1) \
(_g0 << 8) | (_g1 << 0)
#define CASE(_g0,_g1) \
case SWITCH(_g0,_g1)
intgetval(const char *prompt)
{
char *cp;
char buf[100];
int val;
while (1) {
printf("%s: ",prompt);
fflush(stdout);
cp = fgets(buf,sizeof(buf),stdin);
// handle end of file
if (cp == NULL) {
val = -1;
break;
// get the first char on the line
val = buf[0];
if (val != '\n')
break;
}
return val;
}
int main ()
{
int i = 0;
int roundCount = 1;
int pos = 0;
int over = 0;
int f = 1;
char G[9];
char uno,dos;
printf("Game Start!\n");
do {
printf("Round %d!\n", roundCount++);
printf("Input selection upon prompt.\n");
printf("Player 1: ");
scanf(" %c", &uno );
printf("Player 2: ");
scanf(" %c", &dos);
if()
//printf("DEBUG: %2.2X %2.2X\n",G[0],G[1]);
switch (SWITCH(uno,dos)) {
CASE('L','V'):
CASE('V','S'):
CASE('S','P'):
CASE('P','R'):
CASE('R','L'):
CASE('R','S'):
CASE('P','V'):
CASE('S','L'):
CASE('V','R'):
CASE('L','P'):
f++;
pos--;
printf("Uno Wins! Pos[%d]\n\n", pos);
break;
CASE('R','P'):
CASE('L','R'):
CASE('R','V'):
CASE('P','S'):
CASE('P','L'):
CASE('S','R'):
CASE('S','V'):
CASE('L','S'):
CASE('V','P'):
CASE('V','L'):
f++;
pos++;
printf("Dos Wins Pos[%d]!\n\n", pos);
break;
CASE('R','R'):
CASE('P','P'):
CASE('S','S'):
CASE('L','L'):
CASE('V','V'):
f++;
pos = pos;
break;
}
if (pos == -3 || pos == 3) {
printf("Game over\n");
break;
}
if (f == 5 && pos != -3 && pos != 3) {
switch (SWITCH(uno,dos)) {
CASE('L','V'):
CASE('V','S'):
CASE('S','P'):
CASE('P','R'):
CASE('R','L'):
CASE('R','S'):
CASE('P','V'):
CASE('S','L'):
CASE('V','R'):
CASE('L','P'):
printf("Uno:Wins!\n");
break;
CASE('R','P'):
CASE('L','R'):
CASE('R','V'):
CASE('P','S'):
CASE('P','L'):
CASE('S','R'):
CASE('S','V'):
CASE('L','S'):
CASE('V','P'):
CASE('V','L'):
printf("Dos Win!\n");
break;
}
}
} while (f < 5);
return 0;
}
im trying to implement a for loop for this but it wouldn't work , i am not getting the result that i want, adding this code. I would appreciate it if you would rewrite the code with this loop or if there is any other way please tell me how.
for ( i = 0; i < sizeof(useduno); i++)
{
if (uno == useduno[i]) // where useduno is the array, where uno is to be stored, so it cannot be used again
{
printf("You already used the letter. Use another letter: ");
scanf(" %c", &uno);
}
}

C | Comparison between two groups of arrays

I'm pretty fresh in the computers world and started to work on c.
now i'm building a little project about generating code (shown below):
My main:
#include <stdio.h>
#include "connect.h"
#define EASY 20
#define NORMAL 15
#define HARD 10
#define CRAZY 30
int main ()
{
int choice = 1;
char enter, returnV;
system("cls");
printf("Welcome to ""THE MAGSHIMIM CODE BREAKER""!!!\n");
printf("\n");
printf("A secret password was chosen to protect the credit card of Pancratius,\nthe descendant of Antiochus\n");
printf("Your mission is to stop Pancratius by revealing his secret password.\n");
printf("the rules are the follows:\n");
printf("\n");
printf("1. In each round you try to guess the secret password (4 distinct digits)\n");
printf("2. After every guess you'll receive two hints about the password");
printf("\nHITS the number of digits in your guess witch were exactly right.\n");
printf("MISSES the number of digits in your guess witch belong to the password but weremiss-placed\n");
printf("3 - if you'll fail to guess the password after a certain number of rounds \tPancratius will buy all the gift to Hanukkah!!!\n");
printf("\n");
printf("Press Enter to continue...\n");
enter = getch();
if (enter = '\n'){
do{
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4 ){
switch(choice){
case (1):
system("cls");
returnV = levels(EASY);
break;
case (2):
system("cls");
returnV = levels(NORMAL);
break;
case (3):
system("cls");
returnV = levels(HARD);
break;
case (4):
system("cls");
returnV = levels(CRAZY);
break;
switch(returnV){
case('y'):
break;
case('n'):
return 0;
break;
}
}
}
else if (choice != 1 || choice != 2 || choice != 3 || choice != 4 ){
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
}
} while (returnV != 'n');
}
system("PAUSE");
}
header file to connect:
char levels (int level);
"levels" function:
#include <stdio.h>
#include "connect.h"
#include <time.h>
#include <stdlib.h>
char cases (int myCase, char crazyl);
char levels (int level) {
char crazyl = 'n',playerChoice;
switch (level){
case (20):
playerChoice = cases (level,crazyl);
printf ("\n%c\n",playerChoice);
return playerChoice;
break;
case (15):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (10):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (30):
crazyl = 'x';
level = rand() % (25 - 5 + 1);
playerChoice = cases (level,crazyl);
return playerChoice;
}
}
int ranGen (int code1,int code2, int code3, int code4);
char cases (int level,char crazyl)
{
unsigned int check;
char choise = 't',code1,code2,code3,code4;
if(level > 0){
while (level > 0){
if(crazyl == 'n'){
printf("Write your guess (only 1-6, no ENTER is needed) [%d guess left]\n",level);
}
else if (crazyl == 'x'){
printf("Write your guess (only 1-6, no ENTER is needed) [xxx guess left]\n");
}
code1 = getch();
printf("%c",code1);
code2 = getch();
printf("\t%c",code2);
code3 = getch();
printf("\t%c\t",code3);
code4 = getch();
printf("%c\n",code4);
if(code1 > '0' && code1 < '7' && code2 > '0' && code2 < '7' && code3 > '0' && code3 < '7' && code4 > '0' && code4 < '7'){
check = ranGen(code1,code2,code3,code4);
level--;
} else {
printf("\nnot a good number only numbers between 1-6\n");
level--;
}
if (level == 0) {
printf("FOR GOD SAKE WE LOST!!!\n");
printf("The secret password was:\n");
while (choise != 'y' || choise != 'n') {
if (choise != 'y' || choise != 'n') {
printf("keep playing? (y/n):");
_flushall();
scanf("%1c",&choise);
if (choise == 'y' || choise == 'n' ) {
return choise;
} else {
continue;
}
}
}
}
}
}
}
int ranGen(int code1,int code2, int code3, int code4) {
unsigned int ranCode[3],check,code[3];
code[0] = (int) code1 - 48;
code[1] = (int) code2 - 48;
code[2] = (int) code3 - 48;
code[3] = (int) code4 - 48;
do {
ranCode[0] = rand() % (6 - 1 + 1);
ranCode[1] = rand() % (6 - 1 + 1);
ranCode[2] = rand() % (6 - 1 + 1);
ranCode[3] = rand() % (6 - 1 + 1);
} while (code[0] != ranCode[0] || code[1] != ranCode[1] || code[2] != ranCode[2] || code[3] != ranCode[3]);
}
Now my problem is in ranGen function at "levels" paste.
I need to Generate 4 random numbers between 1-6 that different from each other
(1234 is ok, 1878 not ok, 2234 not ok either) and that the user will guess the digits while if he made a correct digits lets say:
generated code = 2345
guess = 1364
The user will get: 1 HIT and 1 MISS while if user will input 2222 he will get 1 HIT and 3 MISSES.
Now im pretty lost here and any help will be great.
I see the problems in your ranGen() function...
you have...
unsigned int ranCode[3],check,code[3];
ranCode[3] gives you 3 elements in that array. Array elements start counting at zero, so that would give you ranCode[0], ranCode[1] and ranCode[2]. If you want ranCode[3] and code[3], than you need to change the above line to...
unsigned int ranCode[4],check,code[4];
That gives you 4 elements, numbered from 0 to 3 (0, 1, 2 & 3 equals 4 numbers).
I'm also not certain what you are trying to do with...
ranCode[0] = rand() % (6 - 1 + 1);
...in your program, it will evaluate what is inside the brackets first, so 6 - 1 = 5, + 1 = 6. So in essence, that line will also look like ranCode[0] = rand() % 6; to the compiler and will give a number from 0 to 5. If you wish to add one to the result, you can use: ranCode[0] = (rand() % 6) + 1;, that would do the random number first, then add one to it for 1 to 6 (which is what I assume you wanted for a dice roll?).
Anyhow, you're passing code4 to a nonexistent element, out of range and probably corrupting memory somewhere, which would have undefined behaviour, possibly crash the system, or effect another variable's memory etc.

C: How do I break this loop in my code?

I've looked at questions asked on stackoverflow before, but this is my first time asking, so I apologize in advance for any format mistakes. I've been taking a class on C programming for about a month, and I've been given an assignment to use a do/while loop in my main function to loop a displayMenu(), which allows the user to input either 1, 2, or 3 to display a certain block of information.
int main(void)
{
int option = 0;
do
{
option = displayMenu();
}
while (option == displayName() || displayColor() || displayFood());
}
//Display the menu for choosing an option or exiting the program
int displayMenu()
{
int choice = 1;
while (choice == 1 || 2 || 3)
{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name, 2 - My favorite color, 3 - My favorite food\n");
printf("%s", "Or type in any other number to exit the program: ");
scanf("%d", &choice);
puts("");
if (choice == 1)
displayName();
if (choice == 2)
displayColor();
if (choice == 3)
displayFood();
}
return choice;
}
Now, I'm sure the error is somewhere within these two methods, but just in case, I'm posting the display methods.
//Function to display my name
int displayName()
{
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor()
{
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood()
{
int value = 3;
puts("My favorite food is z.\n");
return value;
}
If the user inputs 1, 2, or 3, the program correctly displays the information and loops to prompt the user again about inputting another value. However, if any other number is input, the program prompts the user again to input a value, when instead it should be closing the program.
What am I doing wrong? I tried inserting a
else return choice;
after the first three if statements, because i thought that would be needed to break the loop, but it didn't work. Does it have something to do with my while conditions? I'm unsure if my conditions are right, (about == and || precedence and whatnot), so if someone could clarify that too it'd be nice.
I know there are probably more efficient methods to executing this program, but I'm limited to what I've been taught in the class, which really isn't anything more than what I've coded.
while (choice == 1 || 2 || 3)
is equivalent to
while ((choice == 1) || 2 || 3)
which is equivalent to
while (1)
What you want is:
while (choice == 1 || choice == 2 || choice == 3)
This line is an infite loop:
while (choice == 1 || 2 || 3)
I guess what you want is:
while (choice == 1 || choice == 2 || choice == 3)
Ignoring the many errors in the original code, what you can do to refactor the loop logic is to use an array of function pointers:
int (*functions[])(void) = { displayName, displayColor, displayFood };
int choice = -1;
do {
choice = get_choice(); // assuming get_choice returns an integer between 0 and 2, or -1 on error/eof.
if (choice != -1)
functions[choice]();
} while (choice != -1)
this will make your code more concise, provided all of your functions have the same prototype.
Well because you got your answer I will not try to give you another Answer which will probably be the same.
One thing you should know, what happens if the user type a letter or a number + a letter (1j) ?
You should have control of your programs when you are dealing with text menus.
Here is a better approach of your program:
#include <stdio.h>
#include <string.h>
int checkInput(int min, int max){
int option,check;
char c;
do{
printf("Choose an Option:\t");
if(scanf("%d%c",&option,&c) == 0 || c != '\n'){
while((check = getchar()) != 0 && check != '\n');
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else if(option < min || option > max){
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else{
break;
}
}while(1);
return option;
}
void quit(void){
printf("Goodbye...\n");
}
//Function to display my name
int displayName(void){
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor(void){
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood(void){
int value = 3;
puts("My favorite food is z.\n");
return value;
}
int displayMenu(void);
int main(void){
int option = 0;
do{
option = displayMenu();
}
while (option != 0);
}
//Display the menu for choosing an option or exiting the program
int displayMenu(void){
int choice;
do{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name\n2 - My favorite color\n3 - My favorite food\n\n");
printf("%s", "Or type in any other number to exit the program: ");
choice = checkInput(0,3);
puts("");
if (choice == 1){
displayName();
}else if (choice == 2){
displayColor();
}else if (choice == 3){
displayFood();
}else if( choice == 0){
quit();
}
}while (choice != 0);
return choice;
}
probably a do{}while(); is better then while{}.

Coding Tic Tac Toe in C with only If statements

So the past week I've been attempting to learn some C, I was giving an exercise to code a really simplistic version of tic tac toe.
I have been asked:
Prompt two users to enter a ‘naught’ or a ‘cross’ respectively into one of the nine positions on the tic, tac, toe grid
After all 9 inputs have been made display the grid
To make it simpler: only when all 9 grid positions have been entered figure out if there is a winner (you can do this with a few ‘if’ statements)
.
I'm told this can be done with a few if statements, so far I have only learnt up to if's, including the basic int, char, float, double, ect.
So, what I'm not truly grasping in how to only use if statements to check if:
the position is already taken, if it has prompt the user to try again or place the current persons naught or cross in that position.
keep track of the positions the two users enter, so I know which position each of the two users they have entered to check those positions if its empty or not.
I feel like I am somewhat over thinking this but I am unsure, if anyone has got any help that'd be great.
This is what I've written so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char board[9];
int num;
printf("Today we are playing a game of Tic Tac Toe\n");
printf("To play the game you need to line up 3 of the same type 'x's or o's' in a line to win\n");
printf("Before we start, whoever wants to be 'X' starts first, and whoever wants to be 'O' starts second\n");
printf("The board looks like this\n");
printf("%d%c%d%c%d\n", 1, 124, 2, 124, 3);
printf("%d%c%d%c%d\n", 4, 124, 5, 124, 6);
printf("%d%c%d%c%d\n", 7, 124, 8, 124, 9);
printf("Lets begin");
printf("\n");
printf("\n");
printf("\n");
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
return 0;
}
Note: Could I also ask that all answers be kept to only using if statements as that is as far as I am up too, and it is how the exercise is meant to be completed, although probably this is ten times easier with for/while and arrays.
Thank you!
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROWS 3
#define COLUMNS 3
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'
void board();//calling class required by C
int checkForWinner();//calling class required by C
char tic_tac_toe[ROWS][COLUMNS] =
{
{ '1', '2', '3'},
{ '4', '5', '6'},
{ '7', '8', '9'}
};
int main()
{
int isGameOn=1, currentPlayer=1, pick;
char checked;
do
{
board();
currentPlayer = (currentPlayer % 2) ? 1 : 2;
printf("Player %d, pick a number: ", currentPlayer);
scanf("%d", &pick);
checked = (currentPlayer == 1) ? 'X' : 'O';
isGameOn = checkForWinner();
if(pick == 1 && tic_tac_toe[0][0] == '1'){
tic_tac_toe[0][0] = checked;
if(isGameOn == 1)break;
}else if(pick == 2 && tic_tac_toe[0][1] == '2'){
tic_tac_toe[0][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 3 && tic_tac_toe[0][2] == '3'){
tic_tac_toe[0][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 4 && tic_tac_toe[1][0] == '4'){
tic_tac_toe[1][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 5 && tic_tac_toe[1][1] == '5'){
tic_tac_toe[1][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 6 && tic_tac_toe[1][2] == '6'){
tic_tac_toe[1][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 7 && tic_tac_toe[2][0] == '7'){
tic_tac_toe[2][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 8 && tic_tac_toe[2][1] == '8'){
tic_tac_toe[2][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 9 && tic_tac_toe[2][2] == '9'){
tic_tac_toe[2][2] = checked;
if(isGameOn == 1){break;}
}
else{
printf("Invalid moved");
}
isGameOn = checkForWinner();
if(isGameOn == 1){
printf("***************************************\n");
printf("The winner is player %d\n", currentPlayer);
printf("***************************************");
break;
}
currentPlayer++;
}while(isGameOn == -1);
board();
return(0);
}
/*Functions*/
/*Board display*/
void board()
{
printf("\n");
printf("%c\t %c\t %c\n", tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][2]);
}
/*Checking for winner*/
int checkForWinner()
{
/*checkign vertical line*/
for(int col=0; col<COLUMNS; col++){
int row=0;
if(tic_tac_toe[row][col] == tic_tac_toe[row+1][col] && tic_tac_toe[row+1][col] == tic_tac_toe[row+2][col]){
return 1;
}
}
/*checking horizontal line*/
if(tic_tac_toe[0][0] == tic_tac_toe[0][1] && tic_tac_toe[0][1] == tic_tac_toe[0][2]){
return 1;
}
else if(tic_tac_toe[1][0] == tic_tac_toe [1][1] && tic_tac_toe[1][1] == tic_tac_toe[1][2])
{
return 1;
}
else if(tic_tac_toe[2][0] == tic_tac_toe [2][1] && tic_tac_toe[2][1] == tic_tac_toe[2][2])
{
return 1;
}
else if(tic_tac_toe[0][0] == tic_tac_toe[1][1] && tic_tac_toe[1][1] == tic_tac_toe[2][2])/*diagonal*/
{
return 1;
}
else {
return -1;
}
}

Resources