#include <stdio.h>
#include <time.h>
#define ROWS 20
#define COLS 20
int main(void)
{
srand((unsigned)time(NULL));
char dot[ROWS][COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
dot[i][j] = 0;
}
}
while (1)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
if (dot[i][j] == 1)
printf("* ");
else if (i == 9 && j == 9)
printf("* ");
else
printf(". ");
if (j == 19)
printf("\n");
}
}
getch();
static int m = 9;
static int n = 9;
int move = rand() % 8;
if (move == 0)
m--;
else if (move == 1)
{
m--;
n++;
}
else if (move == 2)
{
n++;
}
else if (move == 3)
{
m++;
n++;
}
else if (move == 4)
{
m++;
}
else if (move == 5)
{
m++;
n--;
}
else if (move == 6)
{
n--;
}
else if (move == 7)
{
m--;
n--;
}
dot[m][n] = '1';
}
return 0;
}
It's a program I wrote about this problem Problem is
c array random
It is not written whether it is a problem to tile or to erase and blink the screen, but in general, you can erase the screen with window: system('cls') and UNIX: system('clear')
I think you can erase the screen and display it again, but if you don't like it because it's not natural and blinking, you can use the curses library.
When moving coordinates, the beetle does not move when entering the dot[m][n] = '1';
string 1
compared to (dot[i][j] == 1)
integer 1
.
Below is the content that reflects the above based on the code you posted.
// gcc -o ran ran.c -l curses
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <curses.h>
#define ROWS 20
#define COLS 20
int main(void)
{
srand((unsigned)time(NULL));
char dot[ROWS][COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
dot[i][j] = '0';
}
}
int m = 9;
int n = 9;
int move , c = 0;
dot[m][n] = '1';
initscr();
while (1)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
if (dot[i][j] == '1') {
printw(" * ");
}
else
printw(" . ");
}
printw("\n");
}
printw("\n");
getch();
clear();
int q = m;
int w = n;
while(dot[q][w] == '1' ) {
q = m;
w = n;
move = rand() % 8;
if (move == 0 && m - 1 >= 0)
{
q = m - 1;
}
else if (move == 1 && m - 1 >= 0 && n+ 1 < ROWS)
{
q = m - 1;
w = n + 1;
}
else if (move == 2 && n + 1 < ROWS)
{
w = n + 1;
}
else if (move == 3 && m + 1 < COLS && n + 1 < ROWS)
{
q = m + 1;
w = n + 1;
}
else if (move == 4 && m + 1 < COLS)
{
q = m + 1;
}
else if (move == 5 && m + 1 < COLS && n - 1 >= 0)
{
q = m + 1;
w = n - 1;
}
else if (move == 6 && n - 1 >= 0)
{
w = n - 1;
}
else if (move == 7 && m - 1 >= 0 && n - 1>= 0)
{
q = m - 1;
w = n - 1;
}
}
m = q;
n = w;
dot[q][w] = '1';
}
endwin();
return 0;
}
© 2024 OneMinuteCode. All rights reserved.