在战舰游戏c++中返回一个私有函数指针
Returning a private function pointer in Battleship game c++
周六快乐!
我正在尝试自学c++,所以我正在做一个战舰程序。
这个版本是相当标准的。玩家输入一个单元格的坐标,试图击中一艘船。如果船被击中,程序就会显示。如果一艘船所占用的所有单元格都被击中,程序就打印一条消息,说明该船已沉没。每次尝试后,程序通过显示电路板的当前状态,所有成功的尝试分别标记为"*"
或"x"
。
我有一个像这样的战列舰板
a b c d e f g h i j
+-------------------+
0| |
1| |
2| |
3| |
4| |
5| |
6| |
7| |
8| |
9| |
+-------------------+
这是我的头文件用于上下文:
#ifndef BOARD_H
#define BOARD_H
#include "Ship.h"
#include <vector>
class Board
{
public:
Board(void);
void addShip(char type, int x1, int y1, int x2, int y2);
void print(void);
void hit(char c, int i);
int level(void);
private:
std::vector<Ship *> shipList;
char score[10][10];
Ship *shipAt(int x, int y);
};
#endif
这是我迄今为止为我的CPP所做的(对不起,代码很长,但有必要为这个问题提供上下文):
#include "Board.h"
#include <iostream>
using namespace std;
#include <vector>
#include <string.h>
#include <stdexcept>
//member function definitions
Board::Board()
{
//char score[10][10] = " ";
char score[10][10] = {' '};
}
void Board::addShip(char type, int x1, int y1, int x2, int y2)
{
if(shipList.size()<=9)
{
shipList.push_back(Ship::makeShip((char) type, (int) x1, (int) y1, (int) x2, (int) y2));
}
}
void Board::print(void){
cout<< " a b c d e f g h i j"<< endl;
cout <<" +-------------------+"<< endl;
for (int i = 0; i < 10; i++) {
cout<<" "<< i <<"|" ;
for (int j = 0; j < 10; j++) {
cout << score[i][j];
}
if(i == 0){
cout << " |";
}
else{
cout << " |";
}
cout<< endl;
}
cout <<" +-------------------+"<< endl;
}
void Board::hit(char c, int i){
if (c<'a' || c>'j' || i > 9 || i<0){
throw invalid_argument("Error: invalid input");
}
if (c == 'a'){
int a = 0;
}
if (c == 'b'){
int b = 1;
}
if (c == 'c'){
int c = 2;
}
if (c == 'd'){
int d = 3;
}
if (c == 'e'){
int e = 4;
}
if (c == 'f'){
int f = 5;
}
if (c == 'g'){
int g = 6;
}
if (c == 'h'){
int h = 7;
}
if (c == 'i'){
int i = 8;
}
if (c == 'j'){
int j = 9;
}
}
Ship *shipAt(int x, int y)
如果一艘船占用单元格(x,y),这个函数返回一个指向该船的指针。否则它返回一个空指针。vector<Ship *> shipList
是包含基指针的vector,用于存储指向船只的指针
对于void hit(char c, int i)
当玩家试图击中由char c和int i定义的单元格时,这个函数被调用。该函数必须确定船只是否被击中,并相应地更新船只的等级和棋盘状态。它使用私有函数shipAt.
本质上,我不知道如何用私有成员函数Ship *shipAt(int x, int y)
实现void hit(char c, int i)
并满足这些要求。
您可以减去既小写又大写的ASCII字母(它甚至可以在不使用ASCII的编译器上工作)。所以我认为你只需要:
void Board::hit(char c, int i){
if (c<'a' || c>'j' || i > 9 || i<0){
throw invalid_argument("Error: invalid input");
}
Ship* ship = shipAt(i, c-'a');
if (ship) {
// ...
}
// ...
}
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 更改一个指针后更改乘法对象
- 从另一个指针指向函数的指针
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- C++ typedef 函数指针,并在一个语句中声明一个指针
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 如何获得GUID编码器,如果我在IMFTransform上有一个指针?
- 我不明白我的错误需要返回一个指针数组
- 使用 SFINAE 测试是否可以将一个指针类型static_cast到另一个指针类型
- 将指针分配给另一个指针时会发生什么情况?
- 如何保存指针地址,以便另一个指针可以继续处理它
- 为什么 std::span 是一个指针 + 大小而不是两个迭代器
- 类的成员应该是一个指针
- 隐式指针变量,在自动定义中具有另一个指针变量
- 利用双重链接列表中的下一个指针
- 你能把一个指针投射到数组中吗?