From 975055e40938730cb09d151ba17bf8defd3b4adf Mon Sep 17 00:00:00 2001 From: Steph Enders Date: Sun, 26 Feb 2023 10:43:21 -0500 Subject: Code quality and improvements I genuinely cannot remember what I was doing here, as I never committed it. But basically - it looks like I used my IDE and fixed warnings and improved some code blocks / references --- .clang-format | 178 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/helper.cpp | 107 +++++++++----------------------- src/helper.hpp | 35 ++++------- src/log.hpp | 49 +++++++++++++++ src/random.cpp | 4 +- src/random.hpp | 4 +- src/timedLatch.hpp | 7 ++- src/ur.cpp | 12 ++-- 8 files changed, 279 insertions(+), 117 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..c0d69d8 --- /dev/null +++ b/.clang-format @@ -0,0 +1,178 @@ +--- +Language: Cpp +# BasedOnStyle: Mozilla +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveMacros: None +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: TopLevel +AlwaysBreakAfterReturnType: TopLevel +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Never + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: false + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Mozilla +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeComma +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 2 +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: true +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: false +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Left +PPIndentWidth: -1 +ReferenceAlignment: Pointer +ReflowComments: true +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... + diff --git a/src/helper.cpp b/src/helper.cpp index 3d44bc6..7ced30c 100644 --- a/src/helper.cpp +++ b/src/helper.cpp @@ -37,7 +37,7 @@ next(int* p, int max) } std::shared_ptr> -createBoard(std::shared_ptr> textures) +createBoard(const std::shared_ptr>& textures) { auto board = std::make_shared>(); sf::Texture& star_texture = (*textures)[STAR_TILE]; @@ -146,17 +146,6 @@ createBoard(std::shared_ptr> textures) return board; } -sf::Font -loadFont() -{ - sf::Font font; - if (!font.loadFromFile("./res/DejaVuSansMono.ttf")) { - std::cerr << "Unable to load font" << std::endl; - throw std::runtime_error("Unable to load font"); - } - return font; -} - std::shared_ptr createPiece(int id, sf::Texture& texture) { @@ -171,10 +160,9 @@ createPiece(int id, sf::Texture& texture) } std::shared_ptr -createPlayer(const int pid, sf::Texture& texture) +createPlayer(int pid, sf::Texture& texture) { std::shared_ptr player = std::make_shared(); - player->pid = pid; player->score = 0; player->pieces = std::make_shared>(); for (int i = 0; i < NUM_PIECES; i++) { @@ -229,19 +217,19 @@ createRollSprites(sf::Texture& t1, sf::Texture& t2) } std::shared_ptr> -createPassSprites(std::shared_ptr> textures) +createPassSprites(const std::shared_ptr>& textures) { auto sprites = std::make_shared>(); - for (int i = 0; i < 3; i++) { - sprites->push_back(sf::Sprite((*textures)[PASS_TILES[i]])); + for (int i : PASS_TILES) { + sprites->push_back(sf::Sprite((*textures)[i])); } return sprites; } std::shared_ptr> createWinSprites(int player_id, - std::shared_ptr> textures) + const std::shared_ptr>& textures) { auto sprites = std::make_shared>(); auto tile_ids = player_id == P1_ID ? P1_WIN_TILES : P2_WIN_TILES; @@ -256,12 +244,12 @@ createWinSprites(int player_id, } std::shared_ptr> -createStartSprites(std::shared_ptr> textures) +createStartSprites(const std::shared_ptr>& textures) { auto sprites = std::make_shared>(); - for (int i = 0; i < 3; i++) { - sprites->push_back(sf::Sprite((*textures)[START_TILES[i]])); + for (int i : START_TILES) { + sprites->push_back(sf::Sprite((*textures)[i])); } return sprites; } @@ -269,51 +257,12 @@ createStartSprites(std::shared_ptr> textures) void makeNum(sf::Sprite* sprite_ptr, int num, - std::shared_ptr> textures) + const std::shared_ptr>& textures) { sf::Texture& t = (*textures)[NUMS_TILES[num]]; sprite_ptr->setTexture(t); }; -bool -clickedPiece(sf::Vector2i mousePosition, struct piece_t* piece) -{ - return piece->sprite.getGlobalBounds().contains(mousePosition.x, - mousePosition.y); -} - -bool -canMovePiece(struct piece_t* piece, - int roll, - std::shared_ptr> myPieces, - std::shared_ptr> enemyPieces) -{ - int next = piece->position + roll; - - // rolled passed the exit - if (next > EXIT_SPACE) { - return false; - } - - // colliding with another piece - for (struct piece_t& p : (*myPieces)) { - // cannot move onto your own piece - if (p.id != piece->id && p.position == next) { - return false; - } - } - - // can't attack in safe square - for (struct piece_t& p : (*enemyPieces)) { - // cannot move onto a protected enemy piece - if (next == SAFE_SPACE && p.position == SAFE_SPACE) { - return false; - } - } - - return true; -} - // This function takes in an row and col we want to put the sprite in // and translate it to a real position in the view // This is because we've ZOOMed in an that adjusts the entire view. @@ -326,9 +275,9 @@ pos(float c, float r) bool canPlace(struct piece_t* piece, int turn_pid, - struct board_t board_tile, - std::shared_ptr> myPieces, - std::shared_ptr> opponentPieces, + const struct board_t& board_tile, + const std::shared_ptr>& myPieces, + const std::shared_ptr>& opponentPieces, int& takenPieceId) { if (board_tile.pid != turn_pid && board_tile.pid != SHARED_ID) @@ -366,39 +315,39 @@ canPlace(struct piece_t* piece, * this is for the purpose of passing if no legal move available */ bool -hasMoves(std::shared_ptr activePlayer, - std::shared_ptr opponent, +hasMoves(const std::shared_ptr& activePlayer, + const std::shared_ptr& opponent, int roll) { int occupied_spaces[14] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + // Populate player pieces for (auto& p : (*activePlayer->pieces)) { if (p.position < 0) continue; // not on board int target = p.position + roll; - if (target == EXIT_SPACE) + if (target == EXIT_SPACE) { return true; // can always land in the exit skip rest of the function + } occupied_spaces[p.position]++; } + // Only populate safe space for (auto& op : (*opponent->pieces)) { if (op.position == SAFE_SPACE) { occupied_spaces[SAFE_SPACE]++; - break; + break; // only 1 piece can be in the safe space } } - for (auto& p : (*activePlayer->pieces)) { - int target = p.position + roll; - if (target > EXIT_SPACE) { - continue; // off the board - } else if (target == EXIT_SPACE) { - return true; // can always land in the exit - } else if (occupied_spaces[target] == 0) { - return true; // has a free space - } - } - return false; + // find if any moves available + return std::ranges::any_of(activePlayer->pieces->begin(), + activePlayer->pieces->end(), + [&occupied_spaces, &roll](const piece_t& p) { + int target = p.position + roll; + return target == EXIT_SPACE || + occupied_spaces[target] == 0; + }); } void diff --git a/src/helper.hpp b/src/helper.hpp index e13ee5e..6fef4b6 100644 --- a/src/helper.hpp +++ b/src/helper.hpp @@ -66,7 +66,6 @@ struct board_t struct player_t { - int pid; int score; std::shared_ptr> pieces; }; @@ -82,13 +81,10 @@ std::shared_ptr> loadTextures(const char* path); std::shared_ptr> -createBoard(std::shared_ptr> textures); - -sf::Font -loadFont(); +createBoard(const std::shared_ptr>& textures); std::shared_ptr -createPlayer(const int pid, sf::Texture& pieceTexture); +createPlayer(int pid, sf::Texture& pieceTexture); std::shared_ptr createPiece(int id, sf::Texture& texture); @@ -100,32 +96,23 @@ std::shared_ptr> createRollSprites(sf::Texture& t1, sf::Texture& t2); std::shared_ptr> -createPassSprites(std::shared_ptr> textures); +createPassSprites(const std::shared_ptr>& textures); std::shared_ptr> createWinSprites(int player_id, - std::shared_ptr> textures); + const std::shared_ptr>& textures); std::shared_ptr> -createStartSprites(std::shared_ptr> textures); +createStartSprites(const std::shared_ptr>& textures); void makeNum(sf::Sprite* sprite_ptr, int num, - std::shared_ptr> textures); - -bool -clickedPiece(sf::Vector2i mousePosition, std::shared_ptr piece); - -bool -canMovePiece(std::shared_ptr piece, - int roll, - std::shared_ptr> myPieces, - std::shared_ptr> enemyPieces); + const std::shared_ptr>& textures); bool -hasMoves(std::shared_ptr activePlayer, - std::shared_ptr opponent, +hasMoves(const std::shared_ptr& activePlayer, + const std::shared_ptr& opponent, int roll); sf::Vector2f @@ -134,9 +121,9 @@ pos(float c, float r); bool canPlace(struct piece_t* piece, int turn_pid, - struct board_t board_tile, - std::shared_ptr> myPieces, - std::shared_ptr> opponentPieces, + const struct board_t& board_tile, + const std::shared_ptr>& myPieces, + const std::shared_ptr>& opponentPieces, int& takenPieceId); void diff --git a/src/log.hpp b/src/log.hpp index 5927682..73c9c10 100644 --- a/src/log.hpp +++ b/src/log.hpp @@ -44,47 +44,56 @@ str(GameState gs) return "Unknown state: " + std::to_string(gs); } } + // END UR SPECIFIC CODE std::string str(int i) { return std::to_string(i); } + std::string str(long i) { return std::to_string(i); } + std::string str(long long i) { return std::to_string(i); } + std::string str(unsigned i) { return std::to_string(i); } + std::string str(unsigned long i) { return std::to_string(i); } + std::string str(unsigned long long i) { return std::to_string(i); } + std::string str(float i) { return std::to_string(i); } + std::string str(double i) { return std::to_string(i); } + std::string str(long double i) { @@ -127,51 +136,61 @@ debug() { log_d(""); } + void debug(int msg) { log_d(str(msg)); } + void debug(long msg) { log_d(str(msg)); } + void debug(long long msg) { log_d(str(msg)); } + void debug(unsigned msg) { log_d(str(msg)); } + void debug(unsigned long msg) { log_d(str(msg)); } + void debug(unsigned long long msg) { log_d(str(msg)); } + void debug(float msg) { log_d(str(msg)); } + void debug(double msg) { log_d(str(msg)); } + void debug(long double msg) { log_d(str(msg)); } + void debug(std::string msg) { @@ -184,51 +203,61 @@ info() { log("", L_INFO); } + void info(int msg) { log(str(msg), L_INFO); } + void info(long msg) { log(str(msg), L_INFO); } + void info(long long msg) { log(str(msg), L_INFO); } + void info(unsigned msg) { log(str(msg), L_INFO); } + void info(unsigned long msg) { log(str(msg), L_INFO); } + void info(unsigned long long msg) { log(str(msg), L_INFO); } + void info(float msg) { log(str(msg), L_INFO); } + void info(double msg) { log(str(msg), L_INFO); } + void info(long double msg) { log(str(msg), L_INFO); } + void info(std::string msg) { @@ -241,51 +270,61 @@ warn() { log("", L_WARN); } + void warn(int msg) { log(str(msg), L_WARN); } + void warn(long msg) { log(str(msg), L_WARN); } + void warn(long long msg) { log(str(msg), L_WARN); } + void warn(unsigned msg) { log(str(msg), L_WARN); } + void warn(unsigned long msg) { log(str(msg), L_WARN); } + void warn(unsigned long long msg) { log(str(msg), L_WARN); } + void warn(float msg) { log(str(msg), L_WARN); } + void warn(double msg) { log(str(msg), L_WARN); } + void warn(long double msg) { log(str(msg), L_WARN); } + void warn(std::string msg) { @@ -298,51 +337,61 @@ error() { log("", L_ERROR); } + void error(int msg) { log(str(msg), L_ERROR); } + void error(long msg) { log(str(msg), L_ERROR); } + void error(long long msg) { log(str(msg), L_ERROR); } + void error(unsigned msg) { log(str(msg), L_ERROR); } + void error(unsigned long msg) { log(str(msg), L_ERROR); } + void error(unsigned long long msg) { log(str(msg), L_ERROR); } + void error(float msg) { log(str(msg), L_ERROR); } + void error(double msg) { log(str(msg), L_ERROR); } + void error(long double msg) { log(str(msg), L_ERROR); } + void error(std::string msg) { diff --git a/src/random.cpp b/src/random.cpp index e94b191..73b226a 100644 --- a/src/random.cpp +++ b/src/random.cpp @@ -6,14 +6,12 @@ namespace ur { Random::Random(int min, int max) { - this->min = min; - this->max = max; // setup the random stuff unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); this->engine = std::default_random_engine(seed); // setup distribution - float range = float(max - min); + auto range = float(max - min); this->distribution = std::normal_distribution(range / 2.f, range / 4.f); } diff --git a/src/random.hpp b/src/random.hpp index e74267a..18beef4 100644 --- a/src/random.hpp +++ b/src/random.hpp @@ -2,16 +2,16 @@ #define UR_RANDOM_H #include + namespace ur { class Random { public: Random(int min, int max); + int next(); private: - int min; - int max; std::default_random_engine engine; std::normal_distribution distribution; }; diff --git a/src/timedLatch.hpp b/src/timedLatch.hpp index 77c7d49..30e3f43 100644 --- a/src/timedLatch.hpp +++ b/src/timedLatch.hpp @@ -1,15 +1,20 @@ #ifndef UR_TIMEDLATCH_H #define UR_TIMEDLATCH_H + #include namespace ur { class TimedLatch { public: - TimedLatch(sf::Time duration); + explicit TimedLatch(sf::Time duration); + void start(); + void reset(); + bool is_running(); + bool is_completed(); private: diff --git a/src/ur.cpp b/src/ur.cpp index b3ea5f7..3bbc670 100644 --- a/src/ur.cpp +++ b/src/ur.cpp @@ -5,13 +5,10 @@ #include "timedLatch.hpp" #include #include -#include #include const char* TEXTURE_PATH = "./res/ur.png"; -const float PAD = 32.f; -const float PIECE_PAD = 8.f; -const float TEXT_OFFSET = 8.f; + const sf::Color BG_COLOR = sf::Color(66, 47, 81, 255); const sf::Color SEMI_TRANSPARENT = sf::Color(255, 255, 255, 128); @@ -26,7 +23,6 @@ bool mouse_left_locked = false; // tracks the turn pids int turn_pid = P1_ID; -int rolling_frame = 0; // which player won P1_ID or P2_ID int winner = -1; @@ -97,9 +93,9 @@ inline void render_dice(sf::RenderWindow* window, std::shared_ptr active_player, std::shared_ptr opponent, - std::shared_ptr> dice, - std::shared_ptr> roll_sprites, - std::shared_ptr> pass_sprites, + const std::shared_ptr>& dice, + const std::shared_ptr>& roll_sprites, + const std::shared_ptr>& pass_sprites, std::shared_ptr> textures, sf::Sprite* roll_result, ur::TimedLatch* animation_timer, -- cgit v1.2.3-54-g00ecf