获取您的
自己的
网站
×
更改方向
更改主题,深色/浅色
转到 Spaces
#include <iostream> using namespace std; int main() { // We put "1" to indicate there is a ship. bool ships[4][4] = { { 0, 1, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }; // Keep track of how many hits the player has and how many turns they have played in these variables int hits = 0; int numberOfTurns = 0; // Allow the player to keep going until they have hit all four ships while (hits < 4) { int row, column; cout << "Selecting coordinates\n"; // Ask the player for a row cout << "Choose a row number between 0 and 3: "; cin >> row; // Ask the player for a column cout << "Choose a column number between 0 and 3: "; cin >> column; // Check if a ship exists in those coordinates if (ships[row][column]) { // If the player hit a ship, remove it by setting the value to zero. ships[row][column] = 0; // Increase the hit counter hits++; // Tell the player that they have hit a ship and how many ships are left cout << "Hit! " << (4-hits) << " left.\n\n"; } else { // Tell the player that they missed cout << "Miss\n\n"; } // Count how many turns the player has taken numberOfTurns++; } cout << "Victory!\n"; cout << "You won in " << numberOfTurns << " turns"; return 0; }
选择坐标
选择 0 到 3 之间的行号:2
选择 0 到 3 之间的列号:1
错过
选择坐标
选择 0 到 3 之间的行号:2
选择 0 到 3 之间的列号:2
命中! 剩余 3 个。
选择坐标
选择 0 到 3 之间的行号:2
选择 0 到 3 之间的列号:2
错过
选择坐标
选择 0 到 3 之间的行号:3
选择 0 到 3 之间的列号:2
命中! 剩余 2 个。
选择坐标
选择 0 到 3 之间的行号:0
选择 0 到 3 之间的列号:2
命中! 剩余 1 个。
选择坐标
选择 0 到 3 之间的行号:0
选择 0 到 3 之间的列号:0
错过
选择坐标
选择 0 到 3 之间的行号:0
选择 0 到 3 之间的列号:1
命中! 剩余 0 个。
胜利!
您在 7 轮内获胜
进程返回值为 0 (0x0) 执行时间:24.994 秒