-
Notifications
You must be signed in to change notification settings - Fork 5
/
car-racing.c
60 lines (55 loc) · 1.43 KB
/
car-racing.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRACK_LENGTH 20
void print_track(int player_position, int opponent_position);
int get_move();
int main() {
srand(time(NULL));
int player_position = 0;
int opponent_position = 0;
printf("Welcome to the Text-based Car Racing Game!\n");
printf("Your car: [P]\nOpponent car: [O]\n");
while (1) {
print_track(player_position, opponent_position);
int move = get_move();
player_position += move;
opponent_position += rand() % 3 + 1; // opponent moves randomly
if (player_position >= TRACK_LENGTH) {
printf("You win!\n");
break;
}
else if (opponent_position >= TRACK_LENGTH) {
printf("You lose!\n");
break;
}
}
return 0;
}
void print_track(int player_position, int opponent_position) {
printf("\n");
for (int i = 0; i < TRACK_LENGTH; i++) {
if (i == player_position) {
printf("[P]");
}
else if (i == opponent_position) {
printf("[O]");
}
else {
printf("[ ]");
}
}
printf("\n");
}
int get_move() {
int move;
while (1) {
printf("Enter a move (1-3): ");
scanf("%d", &move);
if (move >= 1 && move <= 3) {
break;
}
printf("Invalid move. Please enter a move between 1 and 3.\n");
}
return move;
}