So i built this really simple game in c language, where you are a ship and need to avoid a bullet rising up the screen. Once I run it in terminal, every time I want to move the ship I enter a (left) s(straight) or d(right). I was wondering if there was a way to not be forced use the enter key after every move and rather have the bullet gradually rise up like one space a second or something automatically.
The code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#define height 20
#define width 15
int main (int argc, char *argv[]) {
printf("Beginning Game\n");
printf("Press 's' to start\n");
char move = 0;
int count = 6;
int turn = 0;
int row = 0;
int col = 0;
int left = 0;
int right = 14;
srand(time(NULL));
int shootcol = rand() % (width - 3) + 2 ;
int shootrow = height + 1;
int shoot2col = rand() % (width - 3) + 2 ;
int shoot2row = height + 15;
while (move != 'e') {
printf("\n");
scanf(" %c", &move);
if (move == 's') {
turn++;
}
else if (move == 'a') {
count--;
turn++;
} else if (move == 'd') {
count++;
turn++;
}
row = 0;
col = 0;
printf("TURN: %d\n", turn);
while (row < height) {
while (col < width) {
//printf("%d", col );
if (((row == shootrow) && (col == shootcol)) || ((row == shoot2row) && (col == shoot2col))) {
printf(":");
} else if (col == left) {
printf("|");
} else if (col == right) {
printf("|");
} else if (row < 5) {
printf(" ");
} else if (row == 5) {
if (col < count) {
printf(" ");
} else if (col == count) {
printf("|");
} else if (col == count + 1) {
printf("-");
} else if (col == count + 2) {
printf("|");
} else if (col >= count + 3) {
printf(" ");
}
} else if (row == 6) {
if (col < count) {
printf(" ");
} else if (col == count) {
printf("\\");
} else if (col == count + 1) {
printf(" ");
} else if (col == count + 2) {
printf("/");
} else if (col >= count + 3) {
printf(" ");
}
} else {
printf(" ");
}
col++;
}
col = 0;
printf("\n");
row++;
}
shootrow--;
shoot2row--;
if ((count == left) || (count == right - 2)) {
printf("YOU LOSE!!\n");
move = 'e';
} else if ((shootrow == 5) || (shootrow == 4)) {
if ((count == shootcol) || (count == shootcol - 2 ) || (count == shootcol - 1)) {
printf("YOU LOSE!!\n");
move = 'e';
} if ((count == shoot2col) || (count == shoot2col - 2 ) || (count == shoot2col - 1)) {
printf("YOU LOSE!!\n");
move = 'e';
}
} if (shootrow <= 0) {
shootrow = height - 1;
shootcol = rand() % (width - 3) + 2 ;
} if (shoot2row <= 0) {
shoot2row = height - 1;
shoot2col = rand() % (width - 3) + 2;
}
}
return 0;
}
The simplest way is using the conio library
#include <conio.h>
#define DELAY 300 // define here the amount of milliseconds to sleep
If you are using linux or mac
#include <unistd.h>
If you are using Windows
#include <windows.h>
and this is how the beginning of your loop would look like
while (move != 's')
scanf(" %c", &move);
move = ' ';
while (move != 'e') {
printf("\n");
//Sleep(DELAY); // windows only sleep 's' lowercase for linux
usleep(DELAY); // for mac
if (_kbhit())
{
move = _getch();
}
if (move == 's') {
turn++;
}
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.
I'm learning C at school, and as homework I have to write the tictactoe game. No problem with the "algorithm", but I do not understand why if I change the order of the variables declaration, the program output drastically changes or even the programme stops working. For example, if I swap line 12 with line 13, the element of the array coord change values at random points of the programme. Can someone explain me why this happen?
#include <stdio.h>
#define DIM 3
#define MAX 11
int main(void) {
char c;
int state = 0; //Variable for the switch case
int nC, nR; //Variables used to count how many X or O there are in the rows and columns of the grid
int i, j;
int coord[2] = {0, 0}; //Array for the coordinates
char grid[DIM][DIM]; //Grid 3x3
char player1[MAX] = "", player2[MAX] = ""; //Name of the players
printf("Player 1, insert your name (max 10 characters): ");
gets(player1);
fflush(stdin);
printf("Player 2, insert your name (max 10 characters): ");
gets(player2);
for (i = 0; i < DIM; i++) { //Inizialize the grid with '.'
for (j = 0; j < DIM; j++) {
grid[i][j] = '.';
printf("%3c", grid[i][j]);
if (j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
do{
switch (state) {
case 0: //State 0: Player 1 is asked for the coordinates corresponding to the position where you want to insert the X symbol
printf("\n%s your turn: ", player1);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'O') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'X';
c = 'X';
state = 2;
}
else{
state = 0;
printf("Invalid coordinates!\n");
}
break;
case 1: //State 1: Player 2 is asked for the coordinates corresponding to the position where you want to insert the O symbol
printf("\n%s your turn: ", player2);
scanf("%d %d", &coord[1], &coord[2]);
if (grid[coord[1] - 1][coord[2] - 1] == '.' && grid[coord[1] - 1][coord[2] - 1] != 'X') { //Check that the selected coordinates are free. Otherwise it prints an error message
grid[coord[1] - 1][coord[2] - 1] = 'O';
c = 'O';
state = 2;
}
else{
printf("Invalid coordinates!\n");
state = 1;
}
break;
case 2: //State 2: Check if there a right combination of X or O
printf("\n");
for (i = 0; i < DIM; i++) {
for (j = 0; j < DIM; j++) {
printf("%3c", grid[i][j]);
if(j == 0 || j == 1) printf(" |");
}
if (i == 0 || i == 1) printf("\n- - - - - - - -\n");
}
nC = 0;
nR = 0;
i = coord[1] - 1;
for (j = 0; j < DIM; j++) {
if(grid[i][j] != c){
break;
}
else{
nR++;
}
}
j = coord[2] - 1;
for (i = 0; i < DIM; i++) {
if (grid[i][j] != c) {
break;
}
else{
nC++;
}
}
if (nC == 3 || nR == 3) state = 3;
else if (c == 'X') state = 1;
else state = 0;
break;
case 3:
if (c == 'X') printf("\n%s IS THE WINNER!\n", player1);
else printf("\n%s IS THE WINNER!\n", player2);
return 0;
break;
}
} while (1);
}
In C, array indices for an array with n elements run from 0 to n−1.
int coord[2] = {0, 0}; defines coord to have two elements, so their indices are 0 and 1.
Throughout the code, coord[1] and coord[2] are used. coord[2] is outside the defined array, so the behavior of the program is not defined by the C standard.
I tried writing code for cs50 pset1's problem: credit.c(more comfortable) after week2. My code is given below. The problem is that 'sumx' and 'sumy' are just 0 and hence 'sum' is always equal to 0. So whenever I give a correct credit card number, it is just going to new line and program ends. How can I solve this problem and why are 'sumx' and 'sumy' not adding up to their respective sums as they should according to the algorithm?
My code is:
#include <cs50.h>
#include <stdio.h>
int main(void){
long long i;
do{
printf("Your credit card number:\n");
i = get_long_long();
}
while(i < 4e12 || i > 5.5e15);
int count = 0;
int n;
long long c = i;
while(i != 0){
n = i%10;
i = i/10;
count++;
}
int x[count];
for(int j = 0; j < count; j++){
x[j] = c%10;
i = c/10;
}
int sumx = 0;
for(int j = 0; j < count - 1; j += 2){
x[j] = x[j] * 2;
sumx = sumx + x[j];
printf("%i", sumx);
}
int sumy = 0;
for(int j = 0; j < count; j += 2){
sumy = sumy + x[j];
}
int sum;
sum = sumx + sumy;
if(sum%10 == 0){
if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
printf("AmEx\n");
}
else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
printf("MASTERCARD\n");
}
else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
printf("VISA\n");
}
}
else{
printf("Invalid Number\n");
}
return 0;
}
//#include <cs50.h>
#include <stdio.h>
int main(void){
long long i=4111111111111111;
//Master: 5105105105105100;//16
//visa: 4111111111111111
printf("%lld\n",i);
//~ do{
//~ printf("Your credit card number:\n");
//~ i = get_long_long();
//~ }
//~ while(i < 4e12 || i > 5.5e15);
int count = 0;
long long c = i;
int k=0;
int x[100];//
while(c != 0){
x[k] = c%10;
c = c/10;
printf("%lld\n",c);
count++;
k++;
}
//k==count
printf("count:%d\n",count);
printf("k:%d\n",k);
// x[i] contains all the digits of credit card
printf("print x[i]\n");
for (int i=0;i<count;i++){
printf("%d ",x[i]);
}
printf("\n");
int addsum=0,x2prod=0;
for (int j=0; j<k; j+=2 ){
addsum += x[j];
}
printf("addsum:%d\n",addsum);
for (int j=1; j<k; j+=2 ){
if ( (2 * x[j]) > 9 ){ //have 2 digit
x2prod += (2 * x[j]) / 10;
x2prod += (2 * x[j]) % 10;
}
else // have one digit
x2prod += 2 * x[j];
}
printf("x2prod:%d\n",x2prod);
int sum;
sum = addsum + x2prod;
printf("\nsum: %d\n",sum);
if(sum%10 == 0){
if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
printf("AmEx\n");
}
else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
printf("MASTERCARD\n");
}
else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
printf("VISA\n");
}
}
else{
printf("Invalid Number\n");
}
return 0;
}
I apply some correction on your code, store all credit card digits on x[]array in first while().
I checked code output with only three samples and by the way this is not a reliable version, try to catch any error.
As you read on my comment i don't any idea about that, but by perform simple search this link
show me what to do and decode it to your way.
We're supposed to create a number board whereby a user is allowed to select a number for instance, number 5 and one of the number 5's in the board will be clearly indicated as selected with a hyphen above and below it.
Problem now is: No matter what I try the hyphens refuse to move to the right spot.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define HEIGHT 9
#define WIDTH 8
void board(char array[HEIGHT][WIDTH])
{
int x,y,i,j,score,steps = 0;
/****BORDER CREATION*/
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
for(y=0;y<WIDTH+1;y++)
{
printf("\n");
printf("# ");
for(x=0;x<HEIGHT+1;x++)
{
printf("%c ",array[y][x]);
}
printf("# ");
printf("\n\n");
}
for (i = 0; i < WIDTH+4; i ++)
printf("# ");
printf("\n");
/****BORDER CREATION*/
}
void instruc(char *name, int *steps, int *selected)
{
/*User record & score header*/
printf("\n-----Hello %s! Let's see what you can do------\n",name);
printf("----------WELCOME TO NUMBER CONNECT----------\n");
printf("----------PREVIOUS PLAYERS' RECORDS----------\n");
printf("----------Name: %s Score(Steps): %i--\n\n",name,*steps);
printf("\nYour score: %i",*steps);
printf("\nNumber %i is currently selected",*selected);
printf("\n\nAction Keys: ");
printf("\nPush 'U' to move UP");
printf("\nPush 'D' to move DOWN");
printf("\nPush 'L' to move LEFT");
printf("\nPush 'R' to move RIGHT");
printf("\nPush 'X' to REMOVE path\n");
printf("\nTo select a new number, press digits from 1 to 7\n");
printf("\nPush 'q' or 'Q' to QUIT\n\n");
}
void select(int *selected,char array[HEIGHT][WIDTH])
{
int i,j,x;
printf("\nPlease select a number (1-8): ");
fflush(stdin);
scanf("%i",selected);
/*POINTER TYPE CONVERTION FAIL
selected = (char)*selected;*/
/*ASCII CHARACTER ATTEMPT FAIL
if (*selected == 1){
*selected = 1;
}
else if (*selected == 2){
*selected = 2;}
else if (*selected == 3){
*selected = 3;}
else if (*selected == 52){
*selected = 4;}
else if (*selected == 53){
*selected = 5;}
else if (*selected == 54){
*selected = 6;}
else if (*selected == 55){
*selected = 7;}
else if (*selected == 56){
*selected = 8;}
else{
printf("Non-Numeric Input not allowed");}*/
printf("\nNumber Selected: %i",*selected);
/*To indicate selected number with hyphens (denoted by 45)*/
for (i = 0; i < WIDTH+1;i++)
{
for (j =0; j < HEIGHT+1; j++){
if (array[i][j] == *selected){
array[i-1][j] = 45;
array[i+1][j] = 45;
}
}
}
printf("\nPosition of i: %i ",i);
printf("Position of j: %i\n\n",j);
}
void assign(char array[HEIGHT][WIDTH], int *selected)
{
int i,j;
/*int rr,rrr;
int x = 0;
srand((unsigned) time(NULL));
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT; j++){
x = (rand()%8+1)+48;
array[i][j] = x;
}
}
for (i = 0; i < WIDTH+3;i++)
{
for (j = 0; j < HEIGHT+3; j++){
rr = rand()%WIDTH;
rrr = rand()%HEIGHT;
x= 32;
array[rr][rrr] = x;
}
}
printf("\n");*/
/*To blank our everything that is not a symbol*/
array[0][1] = 49;
array[0][7] = 49;
array[5][9] = 50;
array[6][1] = 50;
array[1][4] = 51;
array[5][7] = 51;
array[7][2] = 52;
array[5][5] = 52;
array[3][3] = 53;
array[1][1] = 53;
array[7][3] = 54;
array[6][2] = 54;
array[3][7] = 55;
array[7][6] = 55;
array[2][4] = 56;
array[4][4] = 56;
for (i = 0; i < WIDTH+4;i++)
{
for (j = 0; j < HEIGHT+4; j++){
if ((array[i][j] != 49) && (array[i][j] != 50) && (array[i][j] != 51) &&
(array[i][j] != 52) && (array[i][j] != 53) && (array[i][j] != 54) && (array[i][j] != 55) &&
(array[i][j] != 56)){
array[i][j] = 32;
}
}
}
}
int main(void)
{
int i,j,x,y,score = 0,steps = 0,result = 0,selected=0;
char array[HEIGHT][WIDTH],name[20];
printf("Please Input Name: ");
scanf("%s",&name);
instruc(name,&steps,&selected);
assign(array,&selected);
board(array);
select(&selected,array);
board(array);
return 0;
}
I wrote a TicTacToe program in C that reads 68.3 KB on my hard disk, and I was wondering if there are any sort of optimization techniques I could use to decrease the amount of bytes in my .exe file.
For instance, is there anything in my code that I could change to make the resulting executable "smaller"?
Code:
#include <stdio.h>
#include <stdbool.h>
void drawBoard(int [3][3]);
bool boardFull(int [3][3]);
bool checkWin(int [3][3], int);
int main()
{
int board[3][3];
int marker, turn, row, column, i, j;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
board[i][j] = -1;
}
printf("Player One is X\n");
printf("Player Two is O\n");
drawBoard(board);
while(!boardFull(board))
{
if((turn % 2) == 0)
{
printf("Player One's turn.\n");
marker = 1;
}
else
{
printf("Player Two's turn.\n");
marker = 0;
}
printf("Which row? ");
scanf("%i", &row);
printf("Which column? ");
scanf("%i", &column);
if(board[row - 1][column - 1] != -1)
{
while(board[row - 1][column - 1] != -1)
{
printf("Space already taken. Try again.\n");
printf("Which row? ");
scanf("%i", &row);
printf("Which column? ");
scanf("%i", &column);
printf("\n");
}
}
board[row - 1][column - 1] = marker;
drawBoard(board);
if(checkWin(board, marker))
{
if(marker == 1)
printf("Player One wins!!");
else
printf("Player Two wins!!");
return 0;
}
turn++;
}
printf("Cat's game!\n");
return 0;
}
void drawBoard(int board[3][3])
{
int i, j;
printf("\n");
for(i = 0; i < 3; i++)
{
printf(" ");
for(j = 0; j < 3; j++)
{
if(board[i][j] == 0)
printf("O");
else if(board[i][j] == 1)
printf("X");
else
printf(" ");
if(j == 2)
continue;
else
printf(" | ");
}
if(i == 2)
printf("\n\n");
else
printf("\n -----------\n");
}
}
bool boardFull(int board[3][3])
{
int i, j;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
if(board[i][j] == -1)
return false;
}
}
return true;
}
bool checkWin(int board[3][3], int w)
{
return
board[0][0] == w && board[1][1] == w && board[2][2] == w
|| board[0][2] == w && board[1][1] == w && board[2][1] == w
|| board[0][0] == w && board[1][0] == w && board[2][0] == w
|| board[0][1] == w && board[1][1] == w && board[2][1] == w
|| board[0][2] == w && board[1][2] == w && board[2][2] == w
|| board[0][0] == w && board[0][1] == w && board[2][2] == w
|| board[1][0] == w && board[1][1] == w && board[2][2] == w
|| board[2][0] == w && board[2][1] == w && board[2][2] == w;
}