1. C++ / Говнокод #20073

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    //Collisions
    static float collisionradius;
    if(numplayers>1)
    	for(k=0;k<numplayers;k++){
    	for(i=k;i<numplayers;i++){
    	if(i==k)i++;
       			if(i<numplayers)
       					if((animation[player[i].targetanimation].attack!=reversed&&animation[player[i].targetanimation].attack!=reversal&&animation[player[k].targetanimation].attack!=reversed&&animation[player[k].targetanimation].attack!=reversal)||(i!=0&&k!=0))
       						if((animation[player[i].currentanimation].attack!=reversed&&animation[player[i].currentanimation].attack!=reversal&&animation[player[k].currentanimation].attack!=reversed&&animation[player[k].currentanimation].attack!=reversal)||(i!=0&&k!=0))
       							if(player[i].howactive<=typesleeping&&player[k].howactive<=typesleeping)
       								if(player[i].howactive!=typesittingwall&&player[k].howactive!=typesittingwall)
       									if(i!=k&&player[i].whichpatchx==player[k].whichpatchx&&player[i].whichpatchz==player[k].whichpatchz&&player[k].skeleton.oldfree==player[k].skeleton.free&&player[i].skeleton.oldfree==player[i].skeleton.free&&player[i].targetanimation!=climbanim&&player[i].targetanimation!=hanganim&&player[k].targetanimation!=climbanim&&player[k].targetanimation!=hanganim)
       										if(player[i].coords.y>player[k].coords.y-3)
       											if(player[i].coords.y<player[k].coords.y+3)
       												if(player[i].coords.x>player[k].coords.x-3)
       													if(player[i].coords.x<player[k].coords.x+3)
       														if(player[i].coords.z>player[k].coords.z-3)
       															if(player[i].coords.z<player[k].coords.z+3){
       																if(findDistancefast(&player[i].coords,&player[k].coords)<3*((player[i].scale+player[k].scale)*2.5)*((player[i].scale+player[k].scale)*2.5)){
      																	if(player[i].onfire||player[k].onfire){
      																		if(!player[i].onfire)player[i].CatchFire();
       																		if(!player[k].onfire)player[k].CatchFire();
       																	}
       																}
       																...

    http://hg.icculus.org/icculus/lugaru/file/97b303e79826/Source/GameTick.cpp#l7276

    gammaker, 25 Мая 2016

    Комментарии (3)
  2. C++ / Говнокод #20072

    +9

    1. 1
    2. 2
    3. 3
    #define GetLastError rand /* optimize API work */ 
    #define struct union /* saves memory */ 
    #define while if /* saves cpu time */

    dm_fomenok, 25 Мая 2016

    Комментарии (15)
  3. C++ / Говнокод #20056

    +4

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    string TRASETXT::trace(string &a // получаемая строка ) 
    { 
        string b; // возвращаемая строка 
        stringstream s; // строковый поток 
        // переводит в втооом словосочетании все большие буквы в маленькие 
        for (unsigned int i = 0; i < a.size(); i++) // а - получаемая строка 
        { 
            int key = a[i]; 
            if ((key <= -33) && (key >= -64)) // от А до Я 
                key += 32; 
            if (key == -88) // только буква Ё 
                key = -72; 
            if ((key >= 65) && (key <= 90)) // от A до Z 
                key += 32; 
            s << (char)key; 
        } 
        getline(s, b); // получаем строку только из маленьких букв во временную переменную 
        s.clear(); // очищаем поток 
        return b; 
    }

    Увидел в курсаче у чувака, лучший метод преобразования строки в lowercase, везде буду использовать теперь и вам рекомендую

    semoro, 23 Мая 2016

    Комментарии (49)
  4. C++ / Говнокод #20053

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    u_long thisIp = htonl(this->sockaddr.sin_addr.S_un.S_addr);
        u_long otherIp = htonl(other.sockaddr.sin_addr.S_un.S_addr);
        u_short thisPort = htons(this->sockaddr.sin_port);
        u_short otherPort = htons(other.sockaddr.sin_port);
    
        // ip1 + port1 < ip2 + port2
        if (thisIp < otherIp)
        {
            if (thisPort <= otherPort)
            {
                return true;
            }
            else
            {
                return ((unsigned)(thisPort - otherPort) < (unsigned)(otherIp - thisIp));
            }
        }
        else
        {
            if (thisPort >= otherPort)
            {
                return false;
            }
            else
            {
                return ((unsigned)(thisIp - otherIp) < (unsigned)(otherPort - thisPort));
            }
        }

    Сравнить IPv4 адрес + порт. Т.е., по сути, (thisIP + thisPort) < (otherIP + otherPort).
    unsigned long long, приди!

    gost, 21 Мая 2016

    Комментарии (23)
  5. C++ / Говнокод #20047

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    bool  Object::DeleteDouble(void* data)
        {
            Element* rc = Head;
            BANKCLIENT* asd = (BANKCLIENT*)rc->Data;
            int dbl;
            Element* rc1 = Head;
            BANKCLIENT* asd1 = (BANKCLIENT*)rc1->Data;
            while ((rc != NULL) && (rc->Data != data))
            {
                asd = (BANKCLIENT*)rc->Data;
                dbl = asd->NumScore;
                while ((rc1 != NULL) && (rc1->Data != data))
                {
                    asd1 = (BANKCLIENT*)rc1->Data;
                    if (dbl == asd1->NumScore)
                    {
                        std::cout << "Дублирующийся элемент удалён" << std::endl;
                        Delete(rc1);
                        goto flag;
                    }
                }
            }
        flag:
            system("pause");
            return rc;
        }

    Некая svetlana.kotik раскрывает секреты односвязных списков.

    Fluttie, 20 Мая 2016

    Комментарии (71)
  6. C++ / Говнокод #20009

    −2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    #include <iostream>
    #include <cstdlib>
    #include <windows.h>
    #include <string>
    using namespace std;
    int main()
    {
        SetConsoleCP(1251);
        SetConsoleOutputCP(1251);
        cout << "Привет, я твой личный собеседник на ближайшие 40 секунд. Мое имя Компьютер" << endl;
        string *greeting = new string;
        cin >> greeting;
        if (greeting == "Привет" || greeting == "Здравствуйте" || greeting == "Приветствую" || greeting == "привет" || greeting == "да" || greeting == "Да" || greeting == "здравствуйте" || greeting == "приветствую")
            cout << "Как Вас зовут?" << endl;
        else
            while (greeting == "Привет" || greeting == "Здравствуйте" || greeting == "Приветствую" || greeting == "привет" || greeting == "да" || greeting == "Да" || greeting == "здравствуйте" || greeting == "приветствую");
            {
                cout << "Давайте начнем с приветствия" << endl;
                cin >> greeting;
            }
    }

    Nobody can help me now

    0x00000, 15 Мая 2016

    Комментарии (4)
  7. C++ / Говнокод #19994

    −3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    template<unsigned int I, unsigned int F>
    struct Lua_dispatch_ {
        template<typename R, typename... Args>
        inline static R Lua_dispatch(lua_State*&& lua, Args&&... args) noexcept {
            constexpr ScriptFunctionData const& F_ = ScriptFunctions::functions[F];
            auto arg = luabridge::Stack<typename CharType<F_.func.types[I - 1]>::type>::get(lua, -1);
            return Lua_dispatch_<I - 1, F>::template Lua_dispatch<R>(
                    forward<lua_State*>(lua),
                    arg,
                    forward<Args>(args)...);
        }
    };
    
    template<unsigned int F>
    struct Lua_dispatch_<0, F> {
        template<typename R, typename... Args>
        inline static R Lua_dispatch(lua_State*&&, Args&&... args) noexcept {
            constexpr ScriptFunctionData const& F_ = ScriptFunctions::functions[F];
            return reinterpret_cast<FunctionEllipsis<R>>(F_.func.addr)(forward<Args>(args)...);
        }
    };
    
    template<unsigned int I>
    static typename enable_if<ScriptFunctions::functions[I].func.ret == 'v', int>::type wrapper(lua_State* lua) noexcept {
        Lua_dispatch_<ScriptFunctions::functions[I].func.numargs, I>::template Lua_dispatch<void>(forward<lua_State*>(lua));
        return 0;
    }
    
    template<unsigned int I>
    static typename enable_if<ScriptFunctions::functions[I].func.ret != 'v', int>::type wrapper(lua_State* lua) noexcept {
        auto ret = Lua_dispatch_<ScriptFunctions::functions[I].func.numargs, I>::template Lua_dispatch<typename CharType<ScriptFunctions::functions[I].func.ret>::type>(forward<lua_State*>(lua));
        luabridge::Stack <typename CharType<ScriptFunctions::functions[I].func.ret>::type>::push (lua, ret);
        return 1;
    }
    
    template<unsigned int I>
    struct F_
    {
        static constexpr LuaFuctionData F{ScriptFunctions::functions[I].name, wrapper<I>};
    };
    
    template<> struct F_<0> { static constexpr LuaFuctionData F{"CreateTimer", LangLua::CreateTimer}; };
    template<> struct F_<1> { static constexpr LuaFuctionData F{"CreateTimerEx", LangLua::CreateTimerEx}; };
    
    template<size_t... Indices>
    inline LuaFuctionData *LangLua::functions(indices<Indices...>)
    {
    
        static LuaFuctionData functions_[sizeof...(Indices)]{
                F_<Indices>::F...
        };
    
        static_assert(
                sizeof(functions_) / sizeof(functions_[0]) ==
                sizeof(ScriptFunctions::functions) / sizeof(ScriptFunctions::functions[0]),
                "Not all functions have been mapped to Lua");
    
        return functions_;
    }
    
    void LangLua::LoadProgram(const char *filename)
    {
        int err = 0;
    
        if ((err = terra_loadfile(lua, filename)) != 0)
            throw runtime_error("Lua script " + string(filename) + " error (" + to_string(err) + "): \"" +
                                string(lua_tostring(lua, -1)) + "\"");
    
        constexpr auto functions_n = sizeof(ScriptFunctions::functions) / sizeof(ScriptFunctions::functions[0]);
    
        LuaFuctionData *functions_ = functions(IndicesFor<functions_n>{});
    
        luabridge::Namespace tes3mp = luabridge::getGlobalNamespace(lua).beginNamespace("tes3mp");
    
        for(int i = 0; i < functions_n; i++)
            tes3mp.addCFunction(functions_[i].name, functions_[i].func);
    
        tes3mp.endNamespace();
    
        if ((err = lua_pcall(lua, 0, 0, 0)) != 0) // Run once script for load in memory.
            throw runtime_error("Lua script " + string(filename) + " error (" + to_string(err) + "): \"" +
                                string(lua_tostring(lua, -1)) + "\"");
    }

    Это часть модуля скриптинга на Lua для моего проекта. Так же поддерживаются нативные языки и Pawn.

    Koncord, 13 Мая 2016

    Комментарии (0)
  8. C++ / Говнокод #19993

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    #include <iostream>
    
    namespace __hidden__ {
      struct print {
        bool space;
        print() : space(false) {}
        ~print() { std::cout << std::endl; }
    
        template <typename T>
        print &operator , (const T &t) {
          if (space) std::cout << ' ';
          else space = true;
          std::cout << t;
          return *this;
        }
      };
    }
    
    #define print __hidden__::print(),
    
    int main() {
      int a = 1, b = 2;
      print "this is a test";
      print "the sum of", a, "and", b, "is", a + b;
      return 0;
    }

    Отсюда: [color=violet]http://madebyevan.com/obscure-cpp-features/[/color]

    myaut, 13 Мая 2016

    Комментарии (12)
  9. C++ / Говнокод #19989

    −1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    typedef std::vector<LogicalTypeNamedItem_t> LogicalTypeNamedItems_t;
    
    class LogicalTypesContainer
    {
    ...
    ...
    ...
    public:
        bool Find(QString Name, QString Type);
        LogicalTypeItems_t m_Result;
    };
    
    
    bool LogicalTypesContainer::Find(QString Name, QString Type)
    {
        for(LogicalTypeNamedItems_t::iterator it = m_LogicalTypeNamedItems.begin();
            it < m_LogicalTypeNamedItems.end(); ++it)
        {
            LogicalTypeNamedItem_t LogicalTypeNamedItem = *it;
            if(QString::compare(LogicalTypeNamedItem.GetName(), Name, Qt::CaseInsensitive) == 0)
            {
                LogicalTypeTypedItems_t LogicalTypeTypedItems = LogicalTypeNamedItem.GetLogicalTypeTypedItems();
                for(LogicalTypeTypedItems_t::iterator devIt = LogicalTypeTypedItems.begin();
                    devIt < LogicalTypeTypedItems.end(); ++devIt)
                {
                    LogicalTypeTypedItem_t LogicalTypeTypedItem = *devIt;
                    if(QString::compare(LogicalTypeTypedItem.GetType(), Type, Qt::CaseInsensitive) == 0)
                    {
                        m_Result = LogicalTypeTypedItem.GetLogicalTypes();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    Есть некий контейнер LogicalTypesContainer, хранящий данные, необходимые во множестве мест. В главном окне приложения создается экземпляр LogicalTypesContainer. У главного окна реализуется интерфейс, возвращающий указатель на данный объект. Далее во все мыслимые и немыслимые места передается указатель на форму главного окна. Суть приведенного фрагмента кода в том, что требуется по некоторому ключу найти в map'е вектор и далее в этом векторе найти некий объект. Делается это во множестве мест. Идиотизм в том, что метод find не просто ищет по ключу, а создает копию вектора, в котором потом самостоятельно надо искать требуемый элемент.

    AlexRider, 12 Мая 2016

    Комментарии (0)
  10. C++ / Говнокод #19988

    +3

    1. 1
    https://github.com/3dfxdev/hyper3DGE/commit/bdc2d2309a24f5f729c07cdf386ecaa75403c980

    Куча километров кода сокращена в пару строчек. Нафиг тогда было писать ту кучу километров?

    UsernameAK, 12 Мая 2016

    Комментарии (45)