简体   繁体   中英

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. 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. 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. Anyway this is a bad mixture between static and dynamic allocation : you don't need 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
  • Ensure cell[i][j] is FREE then randomly generate a direction and ensure the consecutive cells are FREE
  • 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
  • line is declared as int but you are using it as a char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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