Fruit disappears sometimes Snake in C - c

Im making a snake game in c, most things seem to be working right but I found a bug that I can't seem to fix. The fruit in my game sometimes just disappears for no reason. First, I thought that the problem was that I was generating it outside of the play-area but I put a restriction on that and the problem still exists.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <math.h>
#include <time.h>
int gameOver = 0, width = 20, height = 20, x, y, fruitX, fruitY, score;
int s;
int totalTail;
int tailX[100], tailY[100];
void Setup() {
srand((unsigned int)time(NULL));
x = height / 2;
y = width / 2;
score = 0;
do {
fruitX = rand() % height;
fruitY = rand() % width;
} while (fruitX <= 0 || fruitY <= 0 || fruitX == x || fruitY == y || fruitX > height || fruitY > width);
}
void Draw() {
system("cls");
for (int i = 0; i < height;i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || j == 0 || i == width - 1 || j == height - 1) {
printf("#");
}
else if (i == x && j == y) { //generates head
printf("O");
}
else if (fruitX == i && fruitY == j) { //generates fruit
printf("F");
}
else {
int print = 0; //generates tail
for (int k = 0; k < totalTail; k++) {
if (tailX[k] == i && tailY[k] == j) {
printf("o");
print = 1;
}
}
if (print == 0) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d", score); //displays score
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'w':
s = 1;
break;
case 's':
s = 2;
break;
case 'a':
s = 3;
break;
case 'd':
s = 4;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < totalTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (s) {
case 1:
x--;
break;
case 2:
x++;
break;
case 3:
y--;
break;
case 4:
y++;
break;
default:
break;
}
for (int i = 0; i < totalTail; i++) { //checks if the head and tail have collided
if (tailX[i] == x && tailY[i] == y) {
gameOver = 1;
}
}
if (x > 18 || y > 18 || x <= 0 || y <= 0) { //checks if player is out of the area
gameOver = 1;
}
if (x == fruitX && y == fruitY) { // adds point to score and regenerates fruit, I think the problem is here, not sure though
score += 1;
totalTail++;
do {
fruitX = rand() % height;
fruitY = rand() % width;
} while (fruitX <= 0 || fruitY <= 0 || fruitX == x || fruitY == y || fruitX > height || fruitY > width);
}
}
int main()
{
Setup();
while (gameOver != 1) {
Input();
Logic();
Draw();
Sleep(10);
}
return 0;
}

Related

How do I add power ups to my space invader game in C language like, double shooting, adding firing speed?

I'm having trouble with adding power ups. I don't know where to put it. I'm a first year college; can somebody help?
This is what I did. I want to add power ups in this game where whenever I destroy enemy, it drops power ups like firing speed and double shooting.
I don't know what to put inside to have the enemy drop some power up.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
int main()
{
int sizey = 23;
int sizex = 40;
int x, y, yi;
char world[sizey][sizex];
char player = 'A';
char playerLaser = '^';
char enemy = 'M';
char enemyShielded = 'O';
char enemyLaser = 'U';
char explosion = 'X';
int score = 0;
int victory = 1;
int laserReady = 1;
int enemyReady = 0;
srand(time(NULL));
/*welcome screen*/
printf("\n \n Welcome soldier! \n \n \n \n");
Sleep(1000);
printf(" Brave the COMMAND PROMPT INVADERS and come back a hero. \n \n \n \n");
Sleep(2500);
printf(" Your operating system is depending upon you. \n \n \n \n");
Sleep(2500);
printf(" Good luck.");
Sleep(1000);
printf("\n \n \n \n Press any key to start.");
getch();
/*initialise world*/
int totalEnemies = 0;
for (x = 0; x < sizex; x ++) {
for (y = 0; y < sizey; y ++) {
if ((y+1) % 2 == 0 && y < 7 && x > 4
&& x < sizex - 5 && x % 2 ==0) {
world[y][x] = enemy;
totalEnemies ++;
}
else if ((y+1) % 2 == 0 && y >= 7 && y < 9 && x > 4
&& x < sizex - 5 && x % 2 ==0){
world[y][x] = enemyShielded;
totalEnemies = totalEnemies + 2;
}
else {
world[y][x] = ' ';
}
}
}
world[sizey - 1][sizex / 2] = player;
int i = 1;
char direction = 'l';
char keyPress;
int currentEnemies = totalEnemies;
while(currentEnemies > 0 && victory) {
int drop = 0;
int enemySpeed = 1 + 10 * currentEnemies / totalEnemies;
laserReady ++;
/*display world*/
system("cls");
printf(" SCORE: %d", score);
printf("\n");
for (y = 0; y < sizey; y ++) {
printf("|");
for (x = 0; x < sizex; x ++) {
printf("%c",world[y][x]);
}
printf("|");
printf("\n");
}
/*laser time*/
for (x = 0; x < sizex; x ++) {
for (y = sizey-1; y >= 0; y --) {
if (i%2 == 0 && world[y][x] == enemyLaser
&& (world[y+1][x] != enemy & world[y+1][x] != enemyShielded)){
world[y+1][x] = enemyLaser;
world[y][x] = ' ';
}
else if (i%2 == 0 && world[y][x] == enemyLaser
&& (world[y+1][x] == enemy | world[y+1][x] == enemyShielded)){
world[y][x] = ' ';
}
}
}
for (x = 0; x < sizex; x ++) {
for (y = 0; y < sizey; y ++) {
if ((i % 5) == 0 && (world[y][x] == enemyShielded
| world[y][x] == enemy) && (rand() % 15) > 13
&& world[y+1][x] != playerLaser) {
for (yi = y+1; yi < sizey; yi ++) {
if (world[yi][x] == enemy
| world[yi][x] == enemyShielded) {
enemyReady = 0;
break;
}
enemyReady = 1;
}
if (enemyReady) {
world[y+1][x] = enemyLaser;
}
}
if (world[y][x] == playerLaser && world[y-1][x] == enemy) {
world[y][x] = ' ';
world[y-1][x] = explosion;
currentEnemies --;
score = score + 50;
}
else if (world[y][x] == playerLaser
&& world[y-1][x] == enemyShielded) {
world[y][x] = ' ';
world[y-1][x] = enemy;
currentEnemies --;
score = score + 50;
}
else if (world[y][x] == playerLaser
&& world[y-1][x] == enemyLaser) {
world[y][x] = ' ';
}
else if (world[y][x] == explosion) {
world[y][x] = ' ';
}
else if ((i+1) % 2 == 0 && world[y][x] == enemyLaser
&& world[y+1][x] == player) {
world[y+1][x] = explosion;
world[y][x] = ' ';
victory = 0;
}
else if (world[y][x] == playerLaser
&& world[y-1][x] != enemyLaser) {
world[y][x] = ' ';
world[y-1][x] = playerLaser;
}
}
}
/*update enemy direction*/
for (y = 0; y < sizey; y ++) {
if (world[y][0] == enemy) {
direction = 'r';
drop = 1;
break;
}
if (world[y][sizex-1] == enemy){
direction = 'l';
drop = 1;
break;
}
}
/*update board*/
if (i % enemySpeed == 0) {
if (direction == 'l') {
for (x = 0; x < sizex - 1; x ++) {
for (y = 0; y < sizey; y ++) {
if (drop && (world[y-1][x+1] == enemy
|| world[y-1][x+1] == enemyShielded)){
world[y][x] = world[y-1][x+1];
world[y-1][x+1] = ' ';
}
else if (!drop && (world[y][x+1] == enemy
|| world[y][x+1] == enemyShielded)) {
world[y][x] = world[y][x+1];
world[y][x+1] = ' ';
}
}
}
}
else {
for (x = sizex; x > 0; x --) {
for (y = 0; y < sizey; y ++) {
if (drop && (world[y-1][x-1] == enemy
|| world[y-1][x-1] == enemyShielded)) {
world[y][x] = world[y-1][x-1];
world[y-1][x-1] = ' ';
}
else if (!drop && (world[y][x-1] == enemy
|| world[y][x-1] == enemyShielded)) {
world[y][x] = world[y][x-1];
world[y][x-1] = ' ';
}
}
}
}
for (x = 0; x < sizex; x ++) {
if (world[sizey - 1][x] == enemy) {
victory = 0;
}
}
}
/*control player*/
if(kbhit()){
keyPress = getch();
}
else {
keyPress = ' ';
}
if (keyPress == 'a') {
for (x = 0; x < sizex; x = x+1) {
if ( world[sizey-1][x+1] == player) {
world[sizey-1][x] = player;
world[sizey-1][x+1] = ' ';
}
}
}
if (keyPress == 'd') {
for (x = sizex - 1; x > 0; x = x-1) {
if ( world[sizey-1][x-1] == player) {
world[sizey-1][x] = player;
world[sizey-1][x-1] = ' ';
}
}
}
if (keyPress == 'm' && laserReady > 2) {
for (x = 0; x < sizex; x = x+1) {
if ( world[sizey-1][x] == player) {
world[sizey - 2][x] = playerLaser;
laserReady = 0;
}
}
}
i ++;
Sleep(50);
}
system("cls");
printf(" SCORE: %d", score);
printf("\n");
for (y = 0; y < sizey; y ++) {
printf("|");
for (x = 0; x < sizex; x ++) {
printf("%c",world[y][x]);
}
printf("|");
printf("\n");
}
Sleep(1000);
system("cls");
if (victory != 0) {
printf("\n \n \n \n \n \n CONGRATULATIONS! \n \n \n \n \n");
Sleep(1000);
printf("\n \n Score: %d", score);
Sleep(1000);
int bonus = totalEnemies*20 - i;
printf("\n \n Bonus: %d", bonus);
Sleep(1000);
printf("\n \n Total Score: %d", score + bonus);
printf("\n \n \n \n Well done");
Sleep(1000);
printf(", Hero.");
Sleep(1000);
getch();
}
else {
printf("\n \n \n \n \n \n You have failed.");
Sleep(1000);
printf("\n \n \n \n \n \n Windows is doomed.");
Sleep(1000);
printf("\n \n Final Score: %d", score);
getch();
}
}

How to get rid of error C1083: Cannot open include file: 'unistd.h'?

I'm trying to run this code on Visual Studio 2022, but it gives an error:
C1083: Cannot open include file: 'unistd.h': No such file or directory.
As I understood that the code was written for the UNIX system, but I would like to run it on Windows.
Snake game
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include<time.h>
#include<ctype.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <unistd.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int length;
int bend_no;
int len;
char key;
void record();
void load();
int life;
void Delay(long double);
void Move();
void Food();
int Score();
void Print();
void gotoxy(int x, int y);
void GotoXY(int x, int y);
void Bend();
void Boarder();
void Down();
void Left();
void Up();
void Right();
void ExitGame();
int Scoreonly();
struct coordinate {
int x;
int y;
int direction;
};
typedef struct coordinate coordinate;
coordinate head, bend[500], food, body[30];
int main()
{
char key;
Print();
system("cls");
load();
length = 5;
head.x = 25;
head.y = 20;
head.direction = RIGHT;
Boarder();
Food(); //to generate food coordinates initially
life = 3; //number of extra lives
bend[0] = head;
Move(); //initialing initial bend coordinate
return 0;
}
void Move()
{
int a, i;
do {
Food();
fflush(stdin);
len = 0;
for (i = 0; i < 30; i++)
{
body[i].x = 0;
body[i].y = 0;
if (i == length)
break;
}
Delay(length);
Boarder();
if (head.direction == RIGHT)
Right();
else if (head.direction == LEFT)
Left();
else if (head.direction == DOWN)
Down();
else if (head.direction == UP)
Up();
ExitGame();
} while (!kbhit());
a = getch();
if (a == 27)
{
system("cls");
exit(0);
}
key = getch();
if ((key == RIGHT && head.direction != LEFT && head.direction != RIGHT) || (key == LEFT && head.direction != RIGHT && head.direction != LEFT) || (key == UP && head.direction != DOWN && head.direction != UP) || (key == DOWN && head.direction != UP && head.direction != DOWN))
{
bend_no++;
bend[bend_no] = head;
head.direction = key;
if (key == UP)
head.y--;
if (key == DOWN)
head.y++;
if (key == RIGHT)
head.x++;
if (key == LEFT)
head.x--;
Move();
}
else if (key == 27)
{
system("cls");
exit(0);
}
else
{
printf("\a");
Move();
}
}
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void GotoXY(int x, int y)
{
HANDLE a;
COORD b;
fflush(stdout);
b.X = x;
b.Y = y;
a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(a, b);
}
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
void load() {
int row, col, r, c, q;
gotoxy(36, 14);
printf("loading...");
gotoxy(30, 15);
for (r = 1; r <= 20; r++) {
sleep(200);//to display the character slowly
printf("%c", 177);
}
getch();
}
void Down()
{
int i;
for (i = 0; i <= (head.y - bend[bend_no].y) && len < length; i++)
{
GotoXY(head.x, head.y - i);
{
if (len == 0)
printf("v");
else
printf("*");
}
body[len].x = head.x;
body[len].y = head.y - i;
len++;
}
Bend();
if (!kbhit())
head.y++;
}
void Delay(long double k)
{
Score();
long double i;
for (i = 0; i <= (10000000); i++);
}
void ExitGame()
{
int i, check = 0;
for (i = 4; i < length; i++) //starts with 4 because it needs minimum 4 element to touch its own body
{
if (body[0].x == body[i].x && body[0].y == body[i].y)
{
check++; //check's value increases as the coordinates of head is equal to any other body coordinate
}
if (i == length || check != 0)
break;
}
if (head.x <= 10 || head.x >= 70 || head.y <= 10 || head.y >= 30 || check != 0)
{
life--;
if (life >= 0)
{
head.x = 25;
head.y = 20;
bend_no = 0;
head.direction = RIGHT;
Move();
}
else
{
system("cls");
printf("All lives completed\nBetter Luck Next Time!!!\nPress any key to quit the game\n");
record();
exit(0);
}
}
}
void Food()
{
if (head.x == food.x && head.y == food.y)
{
length++;
time_t a;
a = time(0);
srand(a);
food.x = rand() % 70;
if (food.x <= 10)
food.x += 11;
food.y = rand() % 30;
if (food.y <= 10)
food.y += 11;
}
else if (food.x == 0)/*to create food for the first time coz global variable are initialized with 0*/
{
food.x = rand() % 70;
if (food.x <= 10)
food.x += 11;
food.y = rand() % 30;
if (food.y <= 10)
food.y += 11;
}
}
void Left()
{
int i;
for (i = 0; i <= (bend[bend_no].x - head.x) && len < length; i++)
{
GotoXY((head.x + i), head.y);
{
if (len == 0)
printf("<");
else
printf("*");
}
body[len].x = head.x + i;
body[len].y = head.y;
len++;
}
Bend();
if (!kbhit())
head.x--;
}
void Right()
{
int i;
for (i = 0; i <= (head.x - bend[bend_no].x) && len < length; i++)
{
//GotoXY((head.x-i),head.y);
body[len].x = head.x - i;
body[len].y = head.y;
GotoXY(body[len].x, body[len].y);
{
if (len == 0)
printf(">");
else
printf("*");
}
/*body[len].x=head.x-i;
body[len].y=head.y;*/
len++;
}
Bend();
if (!kbhit())
head.x++;
}
void Bend()
{
int i, j, diff;
for (i = bend_no; i >= 0 && len < length; i--)
{
if (bend[i].x == bend[i - 1].x)
{
diff = bend[i].y - bend[i - 1].y;
if (diff < 0)
for (j = 1; j <= (-diff); j++)
{
body[len].x = bend[i].x;
body[len].y = bend[i].y + j;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
else if (diff > 0)
for (j = 1; j <= diff; j++)
{
/*GotoXY(bend[i].x,(bend[i].y-j));
printf("*");*/
body[len].x = bend[i].x;
body[len].y = bend[i].y - j;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
}
else if (bend[i].y == bend[i - 1].y)
{
diff = bend[i].x - bend[i - 1].x;
if (diff < 0)
for (j = 1; j <= (-diff) && len < length; j++)
{
/*GotoXY((bend[i].x+j),bend[i].y);
printf("*");*/
body[len].x = bend[i].x + j;
body[len].y = bend[i].y;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
else if (diff > 0)
for (j = 1; j <= diff && len < length; j++)
{
/*GotoXY((bend[i].x-j),bend[i].y);
printf("*");*/
body[len].x = bend[i].x - j;
body[len].y = bend[i].y;
GotoXY(body[len].x, body[len].y);
printf("*");
len++;
if (len == length)
break;
}
}
}
}
void Boarder()
{
system("cls");
int i;
GotoXY(food.x, food.y); /*displaying food*/
printf("F");
for (i = 10; i < 71; i++)
{
GotoXY(i, 10);
printf("!");
GotoXY(i, 30);
printf("!");
}
for (i = 10; i < 31; i++)
{
GotoXY(10, i);
printf("!");
GotoXY(70, i);
printf("!");
}
}
void Print()
{
//GotoXY(10,12);
printf("\tWelcome to the mini Snake game.(press any key to continue)\n");
getch();
system("cls");
printf("\tGame instructions:\n");
printf("\n-> Use arrow keys to move the snake.\n\n-> You will be provided foods at the several coordinates of the screen which you have to eat. Everytime you eat a food the length of the snake will be increased by 1 element and thus the score.\n\n-> Here you are provided with three lives. Your life will decrease as you hit the wall or snake's body.\n\n-> YOu can pause the game in its middle by pressing any key. To continue the paused game press any other key once again\n\n-> If you want to exit press esc. \n");
printf("\n\nPress any key to play game...");
if (getch() == 27)
exit(0);
}
void record() {
char plname[20], nplname[20], cha, c;
int i, j, px;
FILE* info;
info = fopen("record.txt", "a+");
getch();
system("cls");
printf("Enter your name\n");
scanf("%[^\n]", plname);
//************************
for (j = 0; plname[j] != '\0'; j++) { //to convert the first letter after space to capital
nplname[0] = toupper(plname[0]);
if (plname[j - 1] == ' ') {
nplname[j] = toupper(plname[j]);
nplname[j - 1] = plname[j - 1];
}
else nplname[j] = plname[j];
}
nplname[j] = '\0';
//*****************************
//sdfprintf(info,"\t\t\tPlayers List\n");
fprintf(info, "Player Name :%s\n", nplname);
//for date and time
time_t mytime;
mytime = time(NULL);
fprintf(info, "Played Date:%s", ctime(&mytime));
//**************************
fprintf(info, "Score:%d\n", px = Scoreonly());//call score to display score
//fprintf(info,"\nLevel:%d\n",10);//call level to display level
for (i = 0; i <= 50; i++)
fprintf(info, "%c", '_');
fprintf(info, "\n");
fclose(info);
printf("wanna see past records press 'y'\n");
cha = getch();
system("cls");
if (cha == 'y') {
info = fopen("record.txt", "r");
do {
putchar(c = getc(info));
} while (c != EOF);
}
fclose(info);
}
int Score()
{
int score;
GotoXY(20, 8);
score = length - 5;
printf("SCORE : %d", (length - 5));
score = length - 5;
GotoXY(50, 8);
printf("Life : %d", life);
return score;
}
int Scoreonly()
{
int score = Score();
system("cls");
return score;
}
void Up()
{
int i;
for (i = 0; i <= (bend[bend_no].y - head.y) && len < length; i++)
{
GotoXY(head.x, head.y + i);
{
if (len == 0)
printf("^");
else
printf("*");
}
body[len].x = head.x;
body[len].y = head.y + i;
len++;
}
Bend();
if (!kbhit())
head.y--;
}
I tried to find information on how to fix the code, but I did not succeed.

Movement for game character doesn't work at all

Here is the .c code from start to finish. I suspect it's an order of operations issue or something else.
The code is supposed to have a title screen where you can exit or play. If you hit play it renders a new char array in which you can move either left, right, or down (a/d/s). You get points for going down a row each time as well as going over 'P' spots on the array.
Once you hit y-coordinate 202 on the array as well as have positive points, you win and it renders a congrats char array. If you go negative in points (by hitting the '#' paces or the 'L' wall that goes down a row every 1/2 second) then you will lose and be told you lost in a new char array as well as be asked if you want to exit or play again.
And as mentioned before, the movement for the 'L's and the play character 'O' simply doesn't move.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
char quickchar(float delay);
void render();
void titleRender();
void renderLoss();
void renderWin();
int score();
char titlescreen[20][59] = { };
char diffdiff[20][46] = {
(Grid removed due to char limit)
};
char gameover[20][50] = {
(Grid removed due to char limit)
};
char gameboard[203][26] = {
(Grid removed due to char limit)
};
int playerx;
int playery;
int pts;
void entryRender();
void gameRender();
int main() {
int input;
char replay;
int lx;
int ly;
char walkin;
int gaming;
char titlechoice;
int diff;
int running;
lx = 0;
ly = 0;
running = 1;
playerx = 13;
playery = 5;
pts = 25;
gaming = 0;
while (gaming == 0) {
titleRender();
printf("\033[1;32m");
printf("\nPress 'p' to play or 'x' to exit!");
printf("\033[0m");
scanf(" %c", &titlechoice);
if (titlechoice == 'p') {
gaming += 4;
}
if (titlechoice == 'x') {
return 0;
}
}
while (gaming == 4) {
system("stty -echo raw");
render();
printf("\033[1;35m");
printf("Choose a direction: s/Down, a/Left, d/Right.\n\r");
printf("\033[0m");
walkin = quickchar(0.5);
scanf("%c", &walkin);
//obj behaviour
if (walkin == 's' &&
gameboard[playery +1][playerx] != '#' &&
gameboard[playery + 1][playerx] != '+' &&
gameboard[playery + 1][playerx] != '|' &&
gameboard[playery + 1][playerx] != '-') {
playery++;
pts += 5;
if (gameboard[playery + 1][playerx] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery + 1][playerx] = '_';
}
}
else if (walkin == 'a' &&
gameboard[playery][playerx - 1] != '#' &&
gameboard[playery][playerx - 1] != '+' &&
gameboard[playery][playerx - 1] != '|' &&
gameboard[playery][playerx - 1] != '-') {
playerx--;
if (gameboard[playery][playerx - 1] == '#') {
pts -= 25;
}
if (gameboard[playery][playerx - 1] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx - 1] = '_';
}
}
else if (walkin == 'd' &&
gameboard[playery][playerx + 1] != '#' &&
gameboard[playery][playerx + 1] != '+' &&
gameboard[playery][playerx + 1] != '|' &&
gameboard[playery][playerx + 1] != '-') {
playerx++;
if (gameboard[playery][playerx + 1] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P) {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx + 1] = '_';
}
}
if (walkin == 'a' || walkin == 's' || walkin == 'd' ||
walkin != 'a' || walkin != ' ' || walkin != 'd' ) {
for (ly = 0; ly = 202; ly++) {
for (lx = 1; lx = 25; lx++) {
gameboard[ly][lx] = 'L';
}
}
}
if (pts <= 0) {
system("clear");
renderLoss();
scanf("%c", replay);
if (replay == 'Y') {
gaming = 3;
}
if (replay == 'N') {
gaming = 5;
}
}
if (playery == 202) {
renderWin();
printf("");
printf("Congrats! You got a score of %d !", pts);
printf("");
scanf("%c", &replay);
if (replay == 'Y') {
gaming = 4;
}
if (replay == 'N') {
gaming = 5;
}
}
//player postion == 203y, then congrta screen
//ask player to set gaming to 4(replay) or none (exit program)
}
system("stty echo -raw");
return 0;
}
void render() {
int y,x,k;
system("clear");
printf("\033[01;33m");
printf("||POINTS: %d||\r\n", pts);
printf("\033[0m");
for (y = 0; y < 203; y++) {
for (x = 0; x < 26; x++) {
if (y == playery && x == playerx) {
printf("\033[0;32m");
printf("O");
printf("\033[0m");
}
else {
printf("\033[1;36m");
printf("%c", gameboard[y][x]);
printf("\033[0m");
}
}
printf("\r\n");
}
}
void titleRender() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 59; x++) {
printf("\033[0;32m");
printf(" %c", titlescreen[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderLoss() {
int y, x;
system("clear");
for (y = 0; y < 26; y++) {
for (x = 0; x < 50; x++) {
printf("\033[0;31m");
printf(" %c", gameover[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderWin() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 46; x++) {
printf("\033[0;33m");
printf(" %c", diffdiff);
printf("\033[0m");
}
printf("\r\n");
}
}
char quickchar(float delay) {
int flags;
char c;
usleep((int)(delay*1000000));
flags = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
c = getchar();
fcntl(0, F_SETFL, flags ^ O_NONBLOCK);
return c;
}

VM Placement with FF, BF and WF Algorithms

Please I am working on VM Placement using First-fit (FF), Best-fit (BF) and Worst-fit (WF) algorithms. The FF and WF seem to work pretty good but there's is a little bit of issue with the BF. The VM sequence are generated randomly for the placement.
The problem is that, sometimes when it sorts out the PMs and picks the one with the least capacity of resources and when it gets to checking if it has enough resource for hosting that particular VM it says "WAIT" instead of placing it on the next available PM with enough resources. It works well from the start but as the process continues it tends to get such error in the placements.
For example, a VM sequence of X, S, M, L, S, L, X, L, M, M the placement is supposed to be:
X 2
S 2
M 2
L 1
S 1
L 1
X 1
L 1
M WAIT
M WAIT
instead it displays:
X 2
S 2
M 2
L 1
S 1
L 1
X WAIT
L WAIT
M WAIT
M WAIT
I really don't know which part of the code is making such an error occur. I would be glad if assistance can be provided. Below is the code - thank you.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <time.h>
#define max 250
#define min 10
int main()
{
int i, k,g, c[max] = {0}, r[max] = {0}, d[max] = {0}, cv[max] = {0},
rv[max] = {0}, dv[max] = {0}, rw[max] = {0}; //declaration of variables
int nf=10; char ch;
float avgpwr=0; //, nb = 3
int m=2;
int b = 1; int ff[10] = {0};
int cm[max] = {0}, rm[max] = {0}, dm[max] = {0};
int a;
for (a=1; a<=b; a++)
{
printf("\n\tVirtual Machine Placement");
printf("\n\t**************************************"); printf("\n");
int flag, j, count=0;
char vm_type[] = {'S', 'M', 'L', 'X'};
printf("\n");
//loop throug array and print values
for (i=1; i<=nf; i++)
{
//generate random index number
int index = my_rand ();
printf("VM %d:",i); printf("%-5c", vm_type[index]);
switch(vm_type[index]) {
case 'S':
cv[i]= 2; rv[i]= 4; dv[i]= 50; rw[i] = 69;
break;
case 'M':
cv[i]= 3; rv[i]= 8; dv[i]= 100; rw[i] = 139;
break;
case 'L':
cv[i]= 5; rv[i]= 12; dv[i]= 150; rw[i] = 207;
break;
case 'X':
cv[i]= 6; rv[i]= 18; dv[i]= 200; rw[i] = 345;
break;
default:
printf("That was not a valid option :(");
}
printf("\n");
}
printf("\n1.First fit 2.Best fit 3.Worst fit\n");
do
{
int nc[10]={0}; int dc[10]={0};
int mc[10]={0}; int rd[10]={0};
int host[10] = {0};
for (i=1; i<=m; i++)
{
if (i==1){
c[i] = 64; r[i] = 64; d[i] = 700; ff[i] = i;
}
if (i==2){
c[i] = 32; r[i] = 32; d[i] = 500; ff[i] = i;
}
}
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nFirst Fit\n");
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(j=1; j<=m; j++)
{
if(cv[i] <= c[j] && rv[i]<= r[j] && dv[i] <= d[j]){
printf("%-15d\t%-15d\t%\n",i,ff[j]); //printf("\n");
count++;
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 || ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
nc[j] = nc[j] + cv[i];
mc[j] = mc[j] + rv[i];
dc[j]= dc[j] + dv[i];
rd[j]= rd[j] + rw[i];
host[j] = host[j]+ 1;
}
break;
}
else
{
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT..\n");
// rejectvm++;
}
}
printf("\n");
//printf("%d , %d , %d , %d \n", nc[i], rd[i], mc[i], dc[i]);
break;
case 2: printf("\nBest Fit\n");
int y1, z1, temp1,temp_r1, temp_d1;
//placing the vms
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(y1=1;y1<=m;y1++)
{
for(z1=y1;z1<=m;z1++)
{
if (c[y1] !=0 && r[y1] !=0 || d[y1] !=0)
{
if(c[y1] > c[z1] && r[y1] > r[z1] && d[y1] > d[z1])
{
temp1 = c[y1]; temp_r1 = r[y1]; temp_d1 = d[y1];
c[y1]= c[z1]; r[y1]= r[z1]; d[y1]= d[z1];
c[z1]=temp1; d[z1]=temp_r1; d[z1]=temp_d1;
temp1=ff[y1];
ff[y1]=ff[z1];
ff[z1]=temp1;
}
}
}
}
for(j=1; j<=m; j++)
{
if( c[j] >= cv[i] && r[j] >= rv[i] && d[j] >= dv[i]){
printf("%-15d\t%-15d\t%\n",i,ff[j]);
count++;
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 ||
ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
//ctr[i] = ctr[i] + 1;
nc[j] = nc[j] + cv[i];
mc[j] = mc[j] + rv[i];
dc[j]= dc[j] + dv[i];
rd[j]= rd[j] + rw[i];
host[j] = host[j]+ 1;
}
break;
}
else {
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT...\n");
}
}
printf("\n");
break;
case 3: printf("\nWorst Fit\n");
int y, z, temp,temp_r, temp_d;
//placing the vms
printf("\n\nVirtualM_No\tPhyMac_No\n");
for(i=1; i<=nf; i++)
{
flag = 1;
for(j=1; j<=m; j++)
{
for(y=1;y<=m;y++)
{
for(z=y;z<=m;z++)
{
if(c[y] < c[z] && r[y] < r[z] && d[y] < d[z])
{
temp = c[y]; temp_r = r[y]; temp_d = d[y];
c[y]= c[z]; r[y]= r[z]; d[y]= d[z];
c[z]=temp; r[z]=temp_r; d[z]=temp_d;
temp1=ff[y];
ff[y]=ff[z];
ff[z]=temp1;
}
}
}
if( c[j] >= cv[i] && r[j] >= rv[i] && d[j] >= dv[i]){
printf("%-15d\t%-15d\t%d\n",i,ff[j],j);
count++; g = ff[j];
if(ff[j]==1 || ff[j]==2 || ff[j]==3 || ff[j]==4 || ff[j]==5 || ff[j]==6 || ff[j]==7 || ff[j]== 8|| ff[j]==9 || ff[j]==10)
{
c[j] = c[j] - cv[i];
r[j] = r[j] - rv[i];
d[j] = d[j] - dv[i];
// ctr[i] = ctr[i] + 1;
nc[g] = nc[g] + cv[i];
mc[g] = mc[g] + rv[i];
dc[g]= dc[g] + dv[i];
rd[g]= rd[g] + rw[i];
host[g] = host[g]+ 1;
}
break;
}
else
{
flag++;
}
}
if(flag > m) {
printf("%-15d\t%-15s\n",i,"WAIT...\n");
}
}
printf("\n");
break;
default:
printf("That was not a valid option :(");
break;
}
}
while(ch<=3);
}
}
int my_rand ()
{
static int first = 0;
if (first == 0)
{
srand (time (NULL));
first = 1;
}
return (rand ()% 4);
}

Missing output from C Blackjack game's int array

So I am trying to write a Blackjack game in C just for the fun of it (something I have never tried before). I have gotten past the first few steps such as how to set up the deck and how to give the cards to the dealer and player. However, the displayed output is not showing what I want it too (showing the dealer only has 1 card when it should be showing 2). Here is a screenshot:
I did run this on my phone (easier to get a screenshot), but I am having the same results on my computer using Code::Blocks. Anyways, I have two functions to handle setting up the deck and to display the current cards. The dealing of the cards I am handling in the main() function using loops. I know that the makeDeck() function is working correctly, so I am assuming that my error is somewhere else. Have a look at my code and let me know what's going on (also, any suggestions for improvement would be appreciated):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Function Prototypes*/
int* makeDeck();
/*Usage - returns an int* to be used for the deck */
void showHands(int[], int[]);
/*Usage - pass dealerHand[], then playerHand[] */
int main() {
srand(time(0)); //Make a new rand() seed value
int x, count = 0, choice = 1;
int* cards = makeDeck();
int dealerCards[12]; //cards in hand will never exceed 11
int playerCards[12]; //4 A's, 4 2's, 3 3's
/*Loop to run the game. One iteration per hand */
while(choice != 0) {
for(x = 0; x < 12; x++) {
dealerCards[x] = 0;
playerCards[x] = 0;
}
//Deal 2 cards to dealer and player
for(x = 0; x < 2; x++) {
dealerCards[x] = cards[count];
count++;
}
for(x = 0; x < 2; x++) {
playerCards[x] = cards[count];
count++;
}
showHands(dealerCards, playerCards);
/*DEBUGGING */
printf("\nEnter 0 to exit loop: ");
scanf("%i", &choice);
}
return 0;
}
//Declare placeholder variable "bunchOfCards" globally
int bunchOfCards[52];
int* makeDeck(){
int* deck = bunchOfCards;
int x = 0,
y = 0,
card = 0;
for(x = 0; x < 52; x++) { //set all cards to 0
deck[x] = 0;
}
for(x = 0; x < 4; x++) { //set up deck
for(y = 1; y < 14; y++) {
card = (rand() % 52);
//check if deck position is already used
while(deck[card] != 0) {
card = (rand() % 52);
}
deck[card] = y;
}
}
/* DEBUGGING
for(x = 0; x < 52; x++) {
printf("%i\t", deck[x]);
} */
return deck;
}
void showHands(int* dealer, int* player) {
int x; char card[3] = { '\0', '\0', '\0' };
puts("The hands are: \n\nDealer:");
//Display dealer cards
for(x = 0; x < 12; x++) {
if(dealer[x] != 0) {
if((dealer[x] < 10) && (dealer[x] != 1)) {
card[0] = (char)(((int)'0') + dealer[x]);
card[1] = '\0';
} else if(dealer[x] == 1) {
card[0] = 'A';
card[1] = '\0';
} else if(dealer[x] == 10) {
card[0] = '1';
card[1] = '0';
} else if(dealer[x] == 11) {
card[0] = 'J';
card[1] = '\0';
} else if(dealer[x] == 12) {
card[0] = 'Q';
card[1] = '\0';
} else if(dealer[x] == 13) {
card[0] = 'K';
card[1] = '\0';
}
printf("\t%s", card);
}
//Display player cards
puts("\nPlayer: ");
for(x = 0; x < 12; x++) {
if(player[x] != 0) {
if((player[x] < 10) && (player[x] != 1)) {
card[0] = (char)(((int)'0') + player[x]);
card[1] = '\0';
} else if(player[x] == 1) {
card[0] = 'A';
card[1] = '\0';
} else if(player[x] == 10) {
card[0] = '1';
card[1] = '0';
} else if(player[x] == 11) {
card[0] = 'J';
card[1] = '\0';
} else if(player[x] == 12) {
card[0] = 'Q';
card[1] = '\0';
} else if(player[x] == 13) {
card[0] = 'K';
card[1] = '\0';
}
printf("\t%s", card);
}
}
}
}
Your for-loops appear to include each other.
for(x = 0; x < 12; x++) {
if(dealer[x] != 0) {
...
}
puts("\nPlayer: ");
for(x = 0; x < 12; x++) {
...
}
}
The first for-loop starts with x = 0, the second for loop goes up to x = 12, then the first for-loop stops before executing a second time because it reached the terminating condition.

Resources