I've been turning around and around trying to figure out how to give my players turns. The questions is for there to be two players playing tic tac toe but I can't figure how to do that. Here's my code:
#include <stdio.h>
#include <stdlib.h>
void displayBoard(char [3][3]);enter code here
int playerType (int player, char boardArray[3][3]);
int selectLocation(char [3][3], int , int );
char setTurn(char [3][3], int , int , char );
int main()
{
int player,location;
char position;
char boardArray[3][3]={{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
player= playerType (player, boardArray);
int i;
for(i=0;i<9;i++)
{
if (player==3)
break;
else{
location=selectLocation(boardArray, player, location);
position=setTurn(boardArray, location, player, position);
}
}
return 0;
}
void displayBoard(char boardArray [3][3]) //This displays the tic tac toe board
{
printf("\t%c|%c|%c\n", boardArray[0][0], boardArray[0][1], boardArray[0][2]);
printf("\t%c|%c|%c\n", boardArray[1][0], boardArray[1][1], boardArray[1][2]);
printf("\t%c|%c|%c\n", boardArray[2][0], boardArray[2][1], boardArray[2][2]);
}
int playerType (int player, char boardArray [3][3]) //This decides who plays first
{
player=0;
printf("Enter 1 for Player X.\n");
printf("Enter 2 for Player O.\n");
printf("Enter 3 to Quit. \n");
scanf("%d", &player);
if (player == 1)
{
printf("You're player X.\n");
displayBoard(boardArray);
}
else if (player == 2)
{
printf("You're player O.\n");
displayBoard(boardArray);
}
else if(player == 3)
printf("You Quit.\n");
else
printf("Invalid Entry.\n");
return player;
}
int selectLocation(char boardArray[3][3], int player, int location) //This takes in the location
{
printf("Pick a location from 1-9.\n");
scanf("%d", &location);
return location;
}
char setTurn(char boardArray[3][3], int location, int player, char position) //This outputs the location
{
if (player == 1)
{
switch(location)
{
case 1:
{
boardArray[0][0]='x';
break;
}
case 2:
{
boardArray[0][1]='x';
break;
}
case 3:
{
boardArray[0][2]='x';
break;
}
case 4:
{
boardArray[1][0]='x';
break;
}
case 5:
{
boardArray[1][1]='x';
break;
}
case 6:
{
boardArray[1][2]='x';
break;
}
case 7:
{
boardArray[2][0]='x';
break;
}
case 8:
{
boardArray[2][1]='x';
break;
}
case 9:
{
boardArray[2][2]='x';
break;
}
default:
printf("invalid");
}
}
else if (player == 2)
{
switch(location)
{
case 1:
{
boardArray[0][0]='O';
break;
}
case 2:
{
boardArray[0][1]='O';
break;
}
case 3:
{
boardArray[0][2]='O';
break;
}
case 4:
{
boardArray[1][0]='O';
break;
}
case 5:
{
boardArray[1][1]='O';
break;
}
case 6:
{
boardArray[1][2]='O';
break;
}
case 7:
{
boardArray[2][0]='O';
break;
}
case 8:
{
boardArray[2][1]='O';
break;
}
case 9:
{
boardArray[2][2]='O';
break;
}
default:
printf("Invalid");
}
}
printf("\t%c|%c|%c\n", boardArray[0][0], boardArray[0][1], boardArray[0][2]);
printf("\t%c|%c|%c\n", boardArray[1][0], boardArray[1][1], boardArray[1][2]);
printf("\t%c|%c|%c\n", boardArray[2][0], boardArray[2][1], boardArray[2][2]);
return position;
}
Change player selection part player= playerType (player, boardArray); inside for loop like this -
int player,location;
char position;
char boardArray[3][3]={{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
int i;
for(i=0;i<9;i++)
{
player= playerType (player, boardArray);
if (player==3)
break;
else
{
location=selectLocation(boardArray, player, location);
position=setTurn(boardArray, location, player, position);
}
}
Related
I am writing code for snake game using C programming language. In my code, when I am trying to take bigger length and height value for game border then output is somehow got distorted. Please let me know how can I make border which could cover whole console window and what is the issue with existing code.
My code:-
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define MAXTL 100
int len=20,wid=20;
int headX,headY,fruitX,fruitY,gameOver,level,flag=0,score=0;
int tailX[MAXTL];int tailY[MAXTL];
int countTail=0;
void draw();
void defaultsetting();
void userinput();
void my_sleep(int level);
//void delay();
void draw(){
system("cls");
for(int i=0;i<len;i++)
{
for(int j=0;j<wid;j++){
if(i==0 || i==len-1){
printf("=");
}
else if(j==0 || j==wid-1){
printf("#");
}
else{
if(i==headX && j==headY){
printf("O");
}
else if(i==fruitX && j==fruitY){
printf("*");
}
else{
int tail=0;
for(int k=0;k<countTail;k++){
if(i==tailX[k]&& j==tailY[k]){
printf("-");
tail=1;
}
}
if(tail==0){
printf(" ");
}
}
}
}
printf("\n");
}
}
void defaultsetting(){
gameOver=0;
srand(time(0));
headX=len/2;
headY=wid/2;
do{
fruitX=rand()%20;
fruitY=rand()%20;
}while(fruitX==0||fruitY==0);
}
void userinput(){
if(kbhit()){
switch(getch()){
case 72://up
flag=1;
break;
case 75://left
flag=2;
break;
case 77://right
flag=3;
break;
case 80://down
flag=4;
break;
case 'q':
gameOver=1;
break;
}
}
}
void logic(){
srand(time(0));
int i,prev2X,prev2Y;
int prevX=tailX[0];
int prevY=tailY[0];
tailX[0]=headX;
tailY[0]=headY;
for(i=1;i<countTail;i++){
prev2X=tailX[i];
prev2Y=tailY[i];
tailX[i]=prevX;
tailY[i]=prevY;
prevX=prev2X;
prevY=prev2Y;
}
switch(flag){
case 1:
headX--;
break;
case 2:
headY--;
break;
case 3:
headY++;
break;
case 4:
headX++;
break;
default:
//printf("Inside default");
break;
}
if(headX <0|| headX>len||headY<0||headY>wid){
gameOver=1;
}
for(i=0;i<countTail;i++){
if(i==tailX[i]&& i==tailY[i]){
gameOver=1;
}
}
if(headX==fruitX&& headY==fruitY)
{
do{
fruitX=rand()%20;
fruitY=rand()%20;
}while(fruitX==0 ||fruitY==0);
score+=10;
countTail++;
}
}
int main(){
int m,n;
char c;
defaultsetting();
printf("Enter level of game\n");
scanf("%d",&level);
while(!gameOver)
{
draw();
userinput();
logic();
my_sleep(level);
}
printf("Your Score =%d",score);
return 0;
}
void my_sleep(int level){
if(level==1){
sleep(1);
}
else if(level==2){
sleep(0.4);
}
else if(level==3){
sleep(0.02);
}
}
Does anyone know why when I run this code it goes for P2_TURN and how to make this enum active that when P2 move then P1 goes and whoever win the correct statement will be given from print_status()… also is there an easier/cleaner way to assign the winner. At the void process_move(struct game* p_game_info) is there a way to replace digits 0-8 with user input without switch case….Sorry for being a bit chaotic with this query but it’s almost 4 in the morning so hope you’ll forgive me….
game.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "game.h"
void play_game()
{
struct game *p_game_info = 0;
p_game_info = malloc(sizeof(struct game));
initialise_game (p_game_info, "John", "Annie");
draw_banner();
display_board(p_game_info->board);
system("cls");
display_board_positions ();
draw_banner();
process_move( p_game_info);
display_board(p_game_info->board);
print_status ( p_game_info );
}
void initialise_game(struct game* p_game_info, char* name1, char* name2)
{
for (int r=0; r<3; r++)
for(int c=0; c<3; c++)
p_game_info->board[r][c] = SPACE;
display_board_positions ();
p_game_info->status=P1_TURN;
// p_game_info->finished = False;
strncpy(p_game_info->playerNames[0], name1,MAX_NAME_LEN);
strncpy(p_game_info->playerNames[1], name2,MAX_NAME_LEN);
}
void draw_banner(){
printf("---------------\n");
printf(" GAME STATUS \n");
printf("---------------\n");
}
void display_board( char board[3][3]){
printf("---------------\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %c ", board[i][j]);
if (j != 2)
printf("|");
}
if (i != 2)
printf("\n-----------");
printf("\n");
}
printf("---------------\n");
}
void print_status (struct game*p_game_info ){
if ((p_game_info->finished=False)&&
(p_game_info->status=P1_TURN))
{
printf("John's Turn\n");
}
else if ((p_game_info->finished=False)&&
(p_game_info->status=P2_TURN))
{
printf("Annie's Turn\n");
}
else if
(p_game_info->status==P1_WON)
{
printf( "Well done John, you have won\n");
}
else if
(p_game_info->status==P2_WON)
{
printf("Well done Annie, you have won\n");
}
else if
(p_game_info->status==DRAW)
{
printf("Game Over It is a draw\n");
}
}
void display_board_positions (){
int count = 0;
printf("---------------\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %d ", count);
count++;
if (j != 2)
printf("|");
}
if (i != 2)
printf("\n-----------");
printf("\n");
}
printf("---------------\n");
}
void process_move(struct game* p_game_info){
if (p_game_info->status==P1_TURN){
printf("enter number for 'X' from 0-8\n");
char ckey = (char) getchar();
switch (ckey){
case '0':
if(p_game_info->board[0][0]==SPACE){
p_game_info->board[0][0]=X_SYMBOL;
}
break;
case '1':
if(p_game_info->board[0][1]==SPACE){
p_game_info->board[0][1]=X_SYMBOL;
}
break;
case '2':
if(p_game_info->board[0][2]==SPACE){
p_game_info->board[0][2]=X_SYMBOL;
}
break;
case '3':
if(p_game_info->board[1][0]==SPACE){
p_game_info->board[1][0]=X_SYMBOL;
}
break;
case '4':
if(p_game_info->board[1][1]==SPACE){
p_game_info->board[1][1]=X_SYMBOL;
}
break;
case '5':
if(p_game_info->board[1][2]==SPACE){
p_game_info->board[1][2]=X_SYMBOL;
}
break;
case '6':
if(p_game_info->board[2][0]==SPACE){
p_game_info->board[2][0]=X_SYMBOL;
}
break;
case '7':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=X_SYMBOL;
}
break;
case '8':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=X_SYMBOL;
}
break;
default:
;
}p_game_info->status=P2_TURN
}
else if (p_game_info->status=P2_TURN){
printf("enter number for 'O' from 0-8\n");
char ckey = (char) getchar();
switch (ckey){
case '0':
if(p_game_info->board[0][0]==SPACE){
p_game_info->board[0][0]=O_SYMBOL;
}
break;
case '1':
if(p_game_info->board[0][1]==SPACE){
p_game_info->board[0][1]=O_SYMBOL;
}
break;
case '2':
if(p_game_info->board[0][2]==SPACE){
p_game_info->board[0][2]=O_SYMBOL;
}
break;
case '3':
if(p_game_info->board[1][0]==SPACE){
p_game_info->board[1][0]=O_SYMBOL;
}
break;
case '4':
if(p_game_info->board[1][1]==SPACE){
p_game_info->board[1][1]=O_SYMBOL;
}
break;
case '5':
if(p_game_info->board[1][2]==SPACE){
p_game_info->board[1][2]=O_SYMBOL;
}
break;
case '6':
if(p_game_info->board[2][0]==SPACE){
p_game_info->board[2][0]=O_SYMBOL;
}
break;
case '7':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=O_SYMBOL;
}
break;
case '8':
if(p_game_info->board[2][1]==SPACE){
p_game_info->board[2][1]=O_SYMBOL;
}
break;
default:
;
}}
}
void finished_game(struct game* p_game_info){
if((p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[0] [1]==O_SYMBOL)&&(p_game_info->board[0][2]==O_SYMBOL)||
(p_game_info->board[1][0]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&& (p_game_info->board[1][2]==O_SYMBOL)||
(p_game_info->board[2][0]==O_SYMBOL)&&(p_game_info->board[2][1]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[1][0]==O_SYMBOL)&&(p_game_info->board[2][0]==O_SYMBOL)||
(p_game_info->board[0][1]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][1]==O_SYMBOL)||
(p_game_info->board[0][2]==O_SYMBOL)&&(p_game_info->board[1][2]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][0]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][2]==O_SYMBOL)||
(p_game_info->board[0][2]==O_SYMBOL)&&(p_game_info->board[1][1]==O_SYMBOL)&&(p_game_info->board[2][0]==O_SYMBOL))
{
p_game_info->status=P2_WON;
return;
}
else if((p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[0][1]==X_SYMBOL)&&(p_game_info->board[0][2]==X_SYMBOL)||
(p_game_info->board[1][0]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[1][2]==X_SYMBOL)||
(p_game_info->board[2][0]==X_SYMBOL)&&(p_game_info->board[2][1]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[1][0]==X_SYMBOL)&&(p_game_info->board[2][0]==X_SYMBOL)||
(p_game_info->board[0][1]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][1]==X_SYMBOL)||
(p_game_info->board[0][2]==X_SYMBOL)&&(p_game_info->board[1][2]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][0]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][2]==X_SYMBOL)||
(p_game_info->board[0][2]==X_SYMBOL)&&(p_game_info->board[1][1]==X_SYMBOL)&&(p_game_info->board[2][0]==X_SYMBOL))
{
p_game_info->status=P1_WON;
return;
}
else
{
p_game_info->status=DRAW;
return;
}
}
game.h
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#define MAX_NAME_LEN 50
enum Bool { False, True };
enum status { P1_TURN, P2_TURN, P1_WON, P2_WON, DRAW };
typedef enum Bool boolean;
static const char SPACE= '-';
static const char X_SYMBOL = 'X';
static const char O_SYMBOL = 'O';
struct game {
char board[3][3];
char playerNames[2][MAX_NAME_LEN];
int status;
boolean finished;
};
void play_game();
void initialise_game(struct game* p_game_info, char* name1, char* name2);
void draw_banner();
void display_board( char board[3][3]);
void print_status (struct game*p_game_info );
void display_board_positions ();
void process_move(struct game* p_game_info);
void finished_game(struct game* p_game_info);
#endif // game
Current output
---------------
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
GAME STATUS
enter number for 'O' from 0-8
2
- | - | O
- | - | -
- | - | -
Process returned 0 (0x0) execution time : 7.731 s
Press any key to continue.
Your question is indeed chaotic. I'm not sure what you really want to know, but notice that 'else if (p_game_info->status=P2_TURN){' is wrong. You need a double equal sign there.
I am developing a simple hotel reservation management system, but I've encountered a little problem. The system("cls"); in mainMenu() function doesn't work, only if the mainMenu() function is called by the bookRoom() function. I tried works just fine with other function, I have no idea why this happens.
Where is my mistake?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
char exitOpt[1],cfm[1];;
int mainMenu_Opt;
int chk = 0;
int advance[4] = {750, 500, 250, 125};
int roomFee[4] = {1500, 1000, 500 ,250};
int rT[4] = {1,2,3,4};
int roomAvail[4] = {1,2,2,5};
struct guest{
char id[5];
char name[30];
int age;
int r_type;
int chk_in_date;
int chk_out_date;
int per;
int totPay;
int paid;
int balance;
};
struct guest grec;
FILE *fguest,*ftemp;
void main();
void mainMenu();
void checkRoom();
void putRAV();
int bookRoom();
void vldRT();
void readData();
void exitProgram ();
void mainMenu()
{
system("cls");
for(;;)
{
fguest = fopen("guest_list.dat","rb");
while(fread(&grec,sizeof(grec),1,fguest)==1 )
{
if (grec.r_type == chk)
roomAvail[chk-1]--;
}
chk = 0;
fclose(fguest);
printf("\n Welcome to HRMS \n\n");
printf("\tMain Menu\n\n");
printf("1. Check Room's Availability\n\n");
printf("2. Book A Room\n\n");
printf("3. Check Out a Room Guest\n\n");
printf("4. Edit Reservation\n\n");
printf("5. Search\n\n");
printf("6. Exit\n\n");
printf("Please, enter your choice (1-6): ");
scanf("%d",&mainMenu_Opt);
fflush(stdin);
switch(mainMenu_Opt)
{
case 1: { putRAV();
break; }
case 2: {
bookRoom();
break; }
// case 3: { chkoRoom();
// break; }
//
// case 4: { editRes();
// break; }
//
case 5: { readData();
break; }
case 6: { exitProgram();
break; }
default: printf("\nInvalid Input. Please try again with valid input (whole number between 1 - 6).\n ");
}
}
}
void checkRoom()
{
system("cls");
fguest = fopen("guest_list.dat","rb");
while(fread(&grec,sizeof(grec),1,fguest)==1 )
{
switch (grec.r_type)
{
case 1: {
roomAvail[0]--;
break; }
case 2: {
roomAvail[1]--;
break; }
case 3: {
roomAvail[2]--;
break; }
case 4: {
roomAvail[3]--;
break; }
}
}
fclose(fguest);
}
void putRAV()
{
system("cls");
int j;
for (j = 0; j < 4; j++)
{
printf("%d\n", roomAvail[j]);
}
printf("Back to main (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ printf("Returning to main menu...\n");
Sleep(1000);
mainMenu(); }
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ putRAV(); }
else
{ printf("\nInvalid Input. Returning to ReadData\n");
putRAV(); }
}
int bookRoom()
{
system("cls");
fflush(stdin);
grec.totPay = 0;
fguest = fopen("guest_list.dat","ab+");
printf("\n\tBook A Room");
printf("\n\nGuest\'s ID\t\t: "); scanf("%s",grec.id); fflush(stdin);
printf("Guest\'s Name\t\t: "); scanf("%30s",grec.name); fflush(stdin);
printf("Guest\'s Age\t\t: "); scanf("%d",&grec.age); fflush(stdin);
printf("Room\'s Type\t\t: "); scanf("%d",&grec.r_type); fflush(stdin);
vldRT();
printf("Check-in Date\t\t: "); scanf("%d",&grec.chk_in_date); fflush(stdin);
printf("Check-out Date\t\t: "); scanf("%d",&grec.chk_out_date); fflush(stdin);
printf("Staying Period\t\t: "); scanf("%d",&grec.per); fflush(stdin);
grec.totPay = (roomFee[grec.r_type - 1] * grec.per) - advance[grec.r_type-1];
printf("Total Payment\t\t: %d\n", grec.totPay);
printf("Total Paid\t\t: "); scanf("%d",&grec.paid); fflush(stdin);
grec.balance = grec.totPay - grec.paid;
printf("Balance\t\t\t: %d \n\n",grec.balance);
printf("\t\t Confirm Booking (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ fwrite(&grec,sizeof(grec),1,fguest);
fclose(fguest);
chk = grec.r_type;
printf("Room successfully booked...\n");
printf("Returning to main menu...\n");
Sleep(1000);
return chk;
}
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ bookRoom(); }
else
{ printf("\nInvalid Input. Returning to Book A Room\n");
bookRoom(); }
mainMenu();
}
void vldRT()
{
if (grec.r_type <= 0 || grec.r_type >4)
{
printf("Invalid input!! Input must be between 1 - 4\n");
printf("Please try again:\n");
printf("Room\'s Type\t\t: "); scanf("%d",&grec.r_type); fflush(stdin); }
}
void exitProgram ()
{
printf("\nExit program (Y/N)? "); gets(exitOpt); fflush(stdin);
if ((strcmp(exitOpt,"Y")==0) || (strcmp(exitOpt,"y")==0))
exit(0);
else if ((strcmp(exitOpt,"N")==0) || (strcmp(exitOpt,"n")==0))
mainMenu();
else
printf("\nInvalid Input. Please try again with valid input (Y/N). \n");
exitProgram();
}
void readData()
{
system("cls");
fguest = fopen("guest_list.dat","rb");
rewind(fguest);
while(fread(&grec,sizeof(grec),1,fguest)==1) //continue reading until there's no more struct data
{
printf("\n\nGuest\'s ID\t\t: %s", grec.id);
printf("\nGuest\'s Name\t\t: %s",grec.name);
printf("\nGuest\'s Age\t\t: %d",grec.age);
printf("\nRoom\'s Type\t\t: %d",grec.r_type);
printf("\nCheck-in Date\t\t: %d",grec.chk_in_date);
printf("\nCheck-out Date\t\t: %d",grec.chk_out_date);
printf("\nStaying Period\t\t: %d",grec.per);
printf("\nTotal Payment\t\t: %d", grec.totPay);
printf("\nTotal Paid\t\t: %d",grec.paid);
printf("\nBalance\t\t\t: %d \n\n",grec.balance);
}
fclose(fguest);
printf("Back to main (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ printf("Returning to main menu...\n");
Sleep(1000);
mainMenu(); }
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ readData(); }
else
{ printf("\nInvalid Input. Returning to ReadData\n");
readData(); }
}
void main()
{
checkRoom();
mainMenu();
}
Why not make your own cls function that is portable?
void my_cls(void) {
int i = 5000;
while (i-->0)
printf("\n");
}
so i'm trying to do a badminton scorekeeper.
and having a problem.
#include<stdio.h>
int scorekeeper();
char home[21]="HOME",away[21]="AWAY",choice3;
void scoreboard();
int score1=0,score2=0,set1=0,set2=0,m=1;
int main()
{
int choice1,choice2,setnum;
char buf[50];
printf("\t\t\t/////////////////////////////////\n\t\t\t/ BADMINTON SCOREKEEPER\t/\n\t\t\t/////////////////////////////////\n\n");
do {
printf("Do you want to enter players' or teams' names?\n1-Yes\n2-No\n:>>");
scanf("%d",&choice1);
switch(choice1) {
case 1: {
do {
printf("\nPlease enter HOME player's or team's name(max 20 characters including space)\n:>>");
fgets(buf, sizeof buf, stdin);
scanf(" %20[^\n]",&home);
printf("\nPlease enter AWAY player's or team's name(max 20 characters including space)\n:>>");
fgets(buf, sizeof buf, stdin);
scanf(" %20[^\n]",&away);
do {
printf("\n\n%.20s VS %.20s\n\n1.Confirm\n2.Edit\n:>>",home,away);
fgets(buf, sizeof buf, stdin);
scanf(" %d",&choice2);
if(choice2!=1&&choice2!=2)
printf("\n***ERROR. INVALID INPUT***\n\n");
} while(choice2!=1&&choice2!=2);
} while(choice2==2);
break;
}
case 2: {
printf("\nSet up to default:\n%s VS %s\n\n",home,away);
break;
}
default: {
printf("\n***ERROR. INVALID SELECTION***\n\n");
break;
}
}
} while(choice1!=1&&choice1!=2);
do {
printf("\n\nHow many sets you want to play?\n(enter 1,3 or 5)\n:>>");
scanf("%d",&setnum);
if(setnum!=1&&setnum!=3&&setnum!=5)
printf("\n\n***INVALID INPUT. PLEASE RE-ENTER***\n\n");
} while(setnum!=1&&setnum!=3&&setnum!=5);
printf("\n\nSTART THE MATCH\n===============\n\n");
while(setnum>0) {
--setnum;
score1=0;
score2=0;
while(score1<21&&score2<21) {
scoreboard();
scorekeeper();
}
if (score1==21&&score2==20||score1==20&&score2==21)
while(score1!=score2+2&&score2!=score1+2) {
scoreboard();
scorekeeper();
if(score1==29&&score2==29)
break;
}
if(score1==29&&score2==29) {
scoreboard();
scorekeeper();
}
if(score1>score2)
++set1;
else
++set2;
scoreboard();
++m;
printf("\n\nEND OF SET\n\n");
if(set1==set2+2||set2==set1+2)
break;
}
return 0;
}
void scoreboard()
{
int a,b,c,d,e,f,g,h,i,j;//here comes the problem
if(m==1) {
a=score1;
b=score2;
printf("\n\n\t\t S\n----------------------------\n|%-20s|%2d|%2d|\n----------------------------\n|%-20s|%2d|%2d|\n----------------------------\n\n",home,set1,a,away,set2,b);
} else if(m==2) {
c=score1;
d=score2;
printf("\n\n\t\t S\n-------------------------------\n|%-20s|%2d|%2d|%2d|\n-------------------------------\n|%-20s|%2d|%2d|%2d|\n-------------------------------\n\n",home,set1,a,c,away,set2,b,d);
} else if(m==3) {
e=score1;
f=score2;
printf("\n\n\t\t S\n-------------------------------\n|%-20s|%2d|%2d|%2d|\n-------------------------------\n|%-20s|%2d|%2d|%2d|\n-------------------------------\n\n",home,set1,a,c,e,away,set2,b,d,f);
}
return;
}
int scorekeeper()
{
printf("\n\nHOT KEYS LIST:\nA-%s SCORES\nL-%s SCORES\n\n",home,away);
scanf(" %c",&choice3);
switch(choice3) {
case 'A':
case 'a': {
++score1;
break;
}
case 'L':
case 'l': {
++score2;
break;
}
default: {
printf("\n\n***ERROR. INVALID INPUT***\n\n");
break;
}
}
return score1,score2;
}
what i am trying to do is when in set 1, the program will assign value of score1 & score2 to a&b respectively. then going to next set, it'll overwrite value of score1& score2 back to 0 before assigning them to c&d. how am i suppose to do this without affecting value stored in a&b?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Please feel free to copy paste and try it out, it stops working halfway through function handget when individual hand is assigned a space in memory
/*
* A program that is meant to classify five-card poker hands.
*Is still in progress
*/
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#define SEED 7
#define SIZE 5
/*
*
*/
typedef enum suits {
clubs,
diamonds,
hearts,
spades
} suits;
typedef enum values {
zero,
one, // not used, but ensures numerical values correspond
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
jack,
queen,
king,
ace
} values;
typedef struct cards {
suits suit;
values value;
} cards;
int islegal(cards *hand, int nr_of_cards);
/* Given any number of cards, determines whether any duplicates
* or false cards are present or not. If so, returns 0, otherwise 1.
*/
int flop(cards **handPtr);
/* Asks the user to input a hand of cards;
* returns the number of cards being input
*/
int *rawtoflop (cards *handPtr, int nr_of_cards);
int hander(cards **handPtr,int counter);
int handget(cards **playerhands,cards *thishands, int handsize);
void printsuit(suits thissuit);
/* Prints the enum-type suits
*/
void printvalue(values thisvalue);
/* Prints the enum-type values
*/
void printhand(cards *hand, int nr_of_cards);
/* Prints a hand of cards without further processing
*/
int main(void) {
cards *thishand, *playerhands;
flop(&thishand);
printhand(thishand,6);
handget(&playerhands,thishand,6);
return 0;
}
int islegal(cards *hand, int nr_of_cards) {
int i, fulldeck[4][13]={0};
int current_value, current_suit;
cards *current_card = hand;
int legal = 1;
for (i=0; i<nr_of_cards; i++) {
current_value = (int) (*current_card).value;
current_suit = (*current_card).suit;
// if the current card has value zero, it is not a valid hand
if (current_value==0) {
legal = 0;
break;
}
//check if the current card already appears, if yes invalid hand, if no,
//change the flag for that card in the full deck.
//Since (two) will correspond to fulldeck[.][0] there is a -2 offset.
if ( (fulldeck[current_suit][current_value - 2]) > 0 ) {
legal = 0;
break;
} else {
fulldeck[current_suit][current_value - 2]++;
}
current_card++;
}
return legal;
}
int flop(cards **handPtr) {
int i,*q=NULL,n=NULL;
int j[5]={0,0,0,0,0};
int k[5]={1,1,1,1,1},nr_of_cards = 5;//for more/less cards CHANGE HERE!
char rawsuit, rawcard[4];
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
n=memcmp(j,k,sizeof(j));
while(n!=0) {
printf("Please input the five cards on the table: ");
q=rawtoflop(*handPtr,nr_of_cards);
for (i=0;i<nr_of_cards;i++) {
j[i]=*(q+i);
}
n=memcmp(j,k,sizeof(j));
}
free(&handPtr);
return nr_of_cards;
}
int *rawtoflop (cards *handPtr, int nr_of_cards){
int i,m[5],*mPtr;
char rawsuit, rawcard[4];
mPtr=m;
// ask for the cards
for (i=0; i<nr_of_cards; i++)/* do */{
scanf("%3s", &rawcard);
rawsuit = rawcard[0];
if (rawcard[1]=='1') {
if (rawcard[2]=='0') {
(handPtr)[i].value = ten;
} else {
(handPtr)[i].value = zero;
}
} else if (rawcard[1]=='2') {
(handPtr)[i].value = two;
} else if (rawcard[1]=='3') {
(handPtr)[i].value = three;
} else if (rawcard[1]=='4') {
(handPtr)[i].value = four;
} else if (rawcard[1]=='5') {
(handPtr)[i].value = five;
} else if (rawcard[1]=='6') {
(handPtr)[i].value = six;
} else if (rawcard[1]=='7') {
(handPtr)[i].value = seven;
} else if (rawcard[1]=='8') {
(handPtr)[i].value = eight;
} else if (rawcard[1]=='9') {
(handPtr)[i].value = nine;
} else if (rawcard[1]=='J') {
(handPtr)[i].value = jack;
} else if (rawcard[1]=='Q') {
(handPtr)[i].value = queen;
} else if (rawcard[1]=='K') {
(handPtr)[i].value = king;
} else if (rawcard[1]=='A') {
(handPtr)[i].value = ace;
} else {
(handPtr)[i].value = zero;
}
switch (rawsuit) {
case 'h':
(handPtr)[i].suit = hearts;
break;
case 'd':
(handPtr)[i].suit = diamonds;
break;
case 'c':
(handPtr)[i].suit = clubs;
break;
case 's':
(handPtr)[i].suit = spades;
break;
default:
(handPtr)[i].value = zero;
}
m[i]=(islegal(handPtr,i+1));
}
return mPtr;
}
int hander(cards **handPtr,int counter) {
int i, nr_of_cards = 2;
char rawsuit, rawcard[4];
if(counter==0){
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
}
// ask for the cards
for (i=0; i<nr_of_cards; i++) do {
scanf("%3s", &rawcard);
rawsuit = rawcard[0];
if (rawcard[1]=='1') {
if (rawcard[2]=='0') {
(*handPtr)[i].value = ten;
} else {
(*handPtr)[i].value = zero;
}
} else if (rawcard[1]=='2') {
(*handPtr)[i].value = two;
} else if (rawcard[1]=='3') {
(*handPtr)[i].value = three;
} else if (rawcard[1]=='4') {
(*handPtr)[i].value = four;
} else if (rawcard[1]=='5') {
(*handPtr)[i].value = five;
} else if (rawcard[1]=='6') {
(*handPtr)[i].value = six;
} else if (rawcard[1]=='7') {
(*handPtr)[i].value = seven;
} else if (rawcard[1]=='8') {
(*handPtr)[i].value = eight;
} else if (rawcard[1]=='9') {
(*handPtr)[i].value = nine;
} else if (rawcard[1]=='J') {
(*handPtr)[i].value = jack;
} else if (rawcard[1]=='Q') {
(*handPtr)[i].value = queen;
} else if (rawcard[1]=='K') {
(*handPtr)[i].value = king;
} else if (rawcard[1]=='A') {
(*handPtr)[i].value = ace;
} else {
(*handPtr)[i].value = zero;
}
switch (rawsuit) {
case 'h':
(*handPtr)[i].suit = hearts;
break;
case 'd':
(*handPtr)[i].suit = diamonds;
break;
case 'c':
(*handPtr)[i].suit = clubs;
break;
case 's':
(*handPtr)[i].suit = spades;
break;
default:
(*handPtr)[i].value = zero;
}
} while (!islegal(*handPtr, i+1));
return nr_of_cards;
}
int handget(cards **playerhand,cards *thishands, int handsize) {
cards *player=NULL,*individualhand=NULL;
int nr_players=1;
(*playerhand) = (cards *) malloc(7*sizeof(cards));
memcpy(*playerhand,thishands,handsize*sizeof(cards));
printf("Please enter the cards for player 1: ");
hander(&player,0);
memcpy(*playerhand+5,player,7*sizeof(cards));
printf("1 we made it this far chaps!!!\n");
individualhand =(cards *) malloc(7*sizeof(cards));//THIS IS WHERE IT ALL GOES WRONG!!
printf("2 we made it this far chaps!!\n");
return nr_players;
}
void printsuit(suits thissuit) {
switch (thissuit) {
case diamonds:
printf("d");
break;
case clubs:
printf("c");
break;
case hearts:
printf("h");
break;
case spades:
printf("s");
break;
}
return;
}
void printvalue(values thisvalue) {
switch (thisvalue) {
case two:
printf("2");
break;
case three:
printf("3");
break;
case four:
printf("4");
break;
case five:
printf("5");
break;
case six:
printf("6");
break;
case seven:
printf("7");
break;
case eight:
printf("8");
break;
case nine:
printf("9");
break;
case ten:
printf("10");
break;
case jack:
printf("J");
break;
case queen:
printf("Q");
break;
case king:
printf("K");
break;
case ace:
printf("A");
break;
}
return;
}
void printhand(cards *hand, int nr_of_cards) {
int i;
for (i=0; i<nr_of_cards; i++) {
printsuit((hand[i]).suit);
printvalue((hand[i]).value);
printf(" ");
}
printf("\n");
return;
}
You allocate enough space for 7 cards:
(*playerhand) = (cards *) malloc(7*sizeof(cards));
Then you copy seven cards into *playerhand+5:
memcpy(*playerhand+5,player,7*sizeof(cards));
So you get a buffer overflow. *playerhand+5 is the same as &(*playerhand)[5]. So you're copying 7 cards into the fifth place in an array with enough capacity for 7 cards.
That's one problem of using magic number. I can't guess what this "5" means if you don't give it a name (nor why 7 cards).
Actually the problem is not that you're copying TO thishands but that you are copying FROM thishands. You allocated 5*sizeof(cards) to thishands,but when calling handget, you're calling it with handget(&playerhands,thishand,6);. The last argument is 6, and therein lies your problem.
Get rid of all these magic numbers. Instead make them (and this is strictly because you seem to be using C not C++) #defines. That way you have a consistent number to work with.