简体   繁体   English

C Battleship程序malloc内存分配和放置船只

[英]C Battleship program malloc memory allocation and placing ships

I'm having trouble allocating memory for a grid in my Battleship program. 我在战舰计划中无法为网格分配内存。 While I don't have to create the whole game (just the set-up), I'm not exactly familiar with malloc so I've been having difficulty implementing it in my code. 虽然我不必创建整个游戏(只是设置),但我对malloc并不十分熟悉,因此我很难在代码中实现它。 Basically, I have no idea how to do this. 基本上,我不知道该怎么做。 Any suggestions? 有什么建议么?

The other problem is that I need a function to randomly generate locations for the two pieces, a carrier (5 units long) and a battleship (4 units long) without letting them overlap. 另一个问题是我需要一个函数来随机生成两个零件的位置,即一艘航母(长5个单位)和一艘战舰(长4个单位),并且不要让它们重叠。 I'm not exactly sure how to go about calling the array or displaying the pieces. 我不确定如何调用数组或显示片段。

The output should look something like this: 输出应如下所示:

2艘战舰网格

Here's my code so far: 到目前为止,这是我的代码:

/*
HEADER:
Author: Laura Kent
Date: 11/23/2014
Purpose: In this code, the user plays a simple game of battle ship on a 10x10 board, in which both hidden pieces must be sunk within a certain number of moves.
     It is the coder's job to make sure the locations of each piece are random and do not over-lap.
     The game must be explained beforehand and set to one of the three difficulties that the user selected.
     After each update, the board display must be updated. */


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

#define SIZE 10;

void menu(void);
void dispBoard(int board[][SIZE]);

int main()
{
    headerinfo();
    menu();

    char lvl[50];

    int board[SIZE][SIZE];
    int line, column, count=0, attempt;

/*Another void function is used to print out the main menu which then loops back in the main function so the user can choose other options.*/

    while(1)
    {
        printf("\tSelect your difficulty( easy, normal, hard):");
        gets(lvl);

        if(strncmp(lvl,"easy",4)==0)
        {
            attempt = 30;
        }

        else if (strncmp(lvl,"normal",6)==0)
        {
            attempt = 25;
        }
        else if (strncmp(lvl,"hard",4)==0)
        {
            attempt = 20;
        }
        else
        {
            printf("Invalid input!/n");
        }

        *board = (int *)malloc(SIZE * SIZE * sizeof(int));

        for (line=0 ; line < SIZE ; line++ )
        {
            for(column=0 ; column < SIZE ; column++ )
            {
                *(board + line*SIZE + column) = ++count;
            }
        }
        dispBoard(board);
    }
    return 0;
}

/*This function justs prints out the coder's header info through a void function.*/

void headerinfo (void)
{
    printf ("********************************\nc\nAuthor: Laura Kent lek0073\nCSCE 1030\n********************************\n\n");
}

/*This function prints out the main menu for the game, which is a intro message and the instructions for the player. The difficulty attempts are also mentioned.*/

void menu(void)
{

    printf("\t\t\t\t\t\t\tWellcome to battleship!\n\tThe objective of this game if for you, the player to sink both of the hidden vessels by guessing their locations on a 10x10 board.\n\tThe two ships are an aircraft carrier (A) that is 5 spaces long and a battleship (B) that is 4 spaces long.\n\tThe location of theses vessels are random so either can be found in a row or column. It is up to the player to guess a square where they might be.\n");
    printf("\tIf the player's guess is a miss, that spot will be marked with an '0' but if it is a hit then a '1' will appear, otherwise all squares will be blank.\n");
    printf("\tLastly, each difficulty has a certain amount of attempts: easy (30 attempts), normal (25 attempts), hard (20 attemps).\n\n");

}

void dispBoard(int board[][SIZE])
{
    int line, column;

    printf("\t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8 \t9 \t10");
    printf("\n");

    for (line='A'; line <= 'J'; line++ ){
         printf("%c",line);
         for(column=0; column < SIZE; column++ ){

            if(board[line][column]==-1){
                printf("\t!");

            }else if(board[line][column]==0){
                printf("\t*");
            }else if(board[line][column]==1){
                printf("\tX");
            }
        }
        printf("\n");
    }
}

You are doing it wrong. 你做错了。

int board[SIZE][SIZE];

Here you already have your grid, statically allocated. 在这里,您已经有了静态分配的网格。

*board = (int *)malloc(SIZE * SIZE * sizeof(int));

This is not what you want to do, unless you want to create a 3D battleship map : *board would be a 2D array so board would be 3D. 这不是您要执行的操作,除非您要创建3D战舰地图: *board将是2D数组,因此board将是3D。 Anyway this is a bad mixture between static and dynamic allocation : you don't need malloc . 无论如何,这是静态分配与动态分配之间的不良结合:您不需要malloc

About generating random location, here is a proposal: 关于生成随机位置,这是一个建议:

  • Each "cell" of your grid should have a status (eg FREE/OCCUPIED) 网格的每个“单元”都应有一个状态(例如,“免费” /“已占用”)
  • Generate 2 random indexes i and j , both < SIZE 生成2个随机索引ij ,均< SIZE
  • Ensure cell[i][j] is FREE then randomly generate a direction and ensure the consecutive cells are FREE 确保cell[i][j]空闲,然后随机生成方向并确保连续的cell空闲
  • On success, tag the cells as OCCUPIED, otherwise repeat process (in an other direction or from an other cell) 成功后,将单元格标记为“已占用”,否则重复此过程(从另一个方向或从另一个单元格进行)

Also, about the code: 另外,关于代码:

  • void dispBoard(int board[][SIZE]) should be void dispBoard(int board[SIZE][SIZE]) for consistency void dispBoard(int board[][SIZE])应该为void dispBoard(int board[SIZE][SIZE])以保持一致性
  • line is declared as int but you are using it as a char line被声明为int但您将其用作char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM