gpt4 book ai didi

c - C语言战舰游戏

转载 作者:行者123 更新时间:2023-11-30 21:27:53 24 4
gpt4 key购买 nike

我一直在用 C 语言编写战舰游戏,但遇到了一些问题。首先,我想要一个用于“击中和击沉”船只的计数器(它是编码的,但它似乎不起作用,击中船只后,它总是打印 1),因此,这不会当所有船只都沉没时,不要结束计划。这是我的主要功能和“拍摄”功能的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define rows 5
#define columns 5

int mainint main(){
srand(time(NULL));
int grid[rows][columns], attemps=0, ships;
int sunk;

printf("Let's play the battleship game!\n");
printf("You have 20 tries.\n");

printf("Enter the number of ships: ");
scanf("%d",&ships);

prepare_grid(grid); //Prepare grid with items of value -1
gen_ships(grid,ships); //Generate random ships surrounded by water (value 1)
print_grid(grid); //Print grid without showing the generated ships (all items will be "~" meaning "undiscovered water).

sunk=0;

for (int a=0;a<20;a++){
shoot(grid,sunk,ships);
attemps++;
print_grid(grid);

printf("\nAttemps: %d\n",attemps);
}

print_secret_grid(grid); //Print final grid, showing all sunk ships and positions shot

return 0;
}

void shoot(int grid[rows][columns], int sunk, int ships) {

int x, y;

printf("\nLine --> ");
scanf("%d", &x);
printf("Column --> ");
scanf("%d", &y);

do {
if (grid[x-1][y-1] == 1) {
grid[x-1][y-1] = 2; //We assign value 2 because we want to print only the ones the user hits, it will print X which means "hit and sunk".
sunk++;
printf("\nHit and sunk\n");
printf("Sunk ships:%d \n\n", sunk);
} else if (grid[x - 1][y - 1] == -1) { //It will print "*" which means "discovered water".
grid[x - 1][y - 1] = 0;
printf("\nMiss\n\n");
}
}while (sunk=!ships);
}

最佳答案

在 C 中使用函数调用时,值通过复制传递。这意味着

int value = 0;
function(value);
printf("%d\n", value);

将始终打印值0,即使函数读起来像这样

void function(int value) {
value++;
}

因为在函数 function 中,int 值 的副本正在递增。

要解决此问题,请传递 value 内存位置的副本,然后递增存储在该位置的数字。

int value = 0;
function(&value);

void function(int* value) {
(*value)++;
}

关于c - C语言战舰游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47526597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com