简体   繁体   English

在 C 中存储网格坐标的最佳方法是什么?

[英]What is the best way to store grid coordinates in C?

I am currently writing a game of battleship as a project for a class.我目前正在编写战舰游戏作为 class 的项目。 What is the best way to store coordinates for ship locations?存储船舶位置坐标的最佳方式是什么? The ocean is a 10x10 grid square with letters going horizontally and numbers vertically.海洋是一个 10x10 的方格,字母水平方向,数字垂直方向。 I need to store the coordinates of each ship.我需要存储每艘船的坐标。 For example, the carrier has 5 spaces so A1, B1, C1, D1, and E1.例如,载体有 5 个空格,即 A1、B1、C1、D1 和 E1。 If I do this in an array, I would somehow have to break up the A1 into a char and an int.如果我在数组中执行此操作,我将不得不以某种方式将 A1 分解为一个 char 和一个 int。 Correct?正确的? Is there a better way to do this?有一个更好的方法吗? Thanks in advance.提前致谢。

you can use a structure:你可以使用一个结构:

struct point{
    int m_vertical;
    char m_horizon;
}

any way you need to do some effort before you ask a question.在您提出问题之前,您需要做一些努力。 Please do some effort and try to search and dig in the webs before asking.请做一些努力,并在询问之前尝试在网上搜索和挖掘。 good luck祝你好运

What you have to do here is translate those letters and numbers into array positions.您在这里要做的就是将这些字母和数字转换为数组位置。

Take the example of E2 .E2为例。 E is the 5th letter of the alphabet, so it could represent the 5th row of your ocean. E 是字母表中的第 5 个字母,因此它可以代表海洋的第 5 行。 The same goes for the numbers, although you don't need any translation there, so 2 is the 2nd column.数字也是如此,虽然你不需要任何翻译,所以 2 是第二列。 Now, if you remember that array indexes start at 0, the 5th row is actually at the 4th index, and the 2nd column is at the 1st index.现在,如果您还记得数组索引从 0 开始,那么第 5 行实际上在第 4 个索引处,而第 2 列在第 1 个索引处。 So, E2 represents ocean[4][1] (or ocean[1][4] , depending on your representation);因此, E2代表ocean[4][1] (或ocean[1][4] ,取决于您的表示);

With that being said, to turn something like E2 into coordinates you can do something like this:话虽如此,要将E2之类的东西转换为坐标,您可以执行以下操作:

char pos[2] = {'E', '2'};
int col = pos[0] - 'A';
int row = pos[1] - '0';

// now you can access your ocean with something like ocean[col][row]

What I'm doing here is taking the ASCII code of the letter E and subtracting the ACSII code of the letter A from it.我在这里所做的是获取字母 E 的 ASCII 代码并从中减去字母 A 的 ACSII 代码。 The same for '2' and '0'. '2' 和 '0' 相同。 This works because ASCII codes from 'A' to 'Z' go from 65 to 90, in order, and ASCII codes for '0' to '9' go from 48 to 57.这是因为 ASCII 码从 'A' 到 'Z' go 依次从 65 到 90,而 ASCII 码从 '0' 到 '9' go 从 48 到 57。

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

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