- 1
А куда пропал инканус?
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
А куда пропал инканус?
+1
%% This function is needed as a hack to guide dialyzer into inferring
%% the correct types.
-spec id(A) -> A.
id(A) ->
A.
%% Где-то в header'е....
-define(deftarget(RECIPE), {RECIPE, fun my_module:id/1}).
%% A horrible, horrible hack to make Dialyzer infer right type of the promise return value
-define(want(TARGET),
(fun() ->
case TARGET of
{_, ___IAmSorryYouHaveToSeeThisWorkaroundForDialyzer} ->
___IAmSorryYouHaveToSeeThisWorkaroundForDialyzer(my_module:want(TARGET))
end
end)()).
Пути статический типизации в Erlang неисповедимы.
+1
// Update is called once per frame
void Update () {
if (!isWin && !isFail && !isPaused)
{
if (timeForUnhit > 0) //Для состояния восстановления игрока
{
timeForUnhit -= Time.deltaTime;
//LevelGenerate.Instance.player.GetComponent<SpriteRenderer>().sprite = hitPlayer;
}
else if (timeForInvc > 0)
//Для состояния непобедимости игрока
{
timeForInvc -= Time.deltaTime;
//LevelGenerate.Instance.player.GetComponent<SpriteRenderer>().sprite = invcPlayer;
}
else
{
//LevelGenerate.Instance.player.GetComponent<SpriteRenderer>().sprite = player;
LevelGenerate.Instance.player.GetComponent<Animator>().CrossFade(animNames[0], 0);
if (invc)
{
MusicManager.Instance.gameObject.GetComponent<AudioSource>().clip = MusicManager.Instance.music[1];
MusicManager.Instance.gameObject.GetComponent<AudioSource>().Play();
}
invc = false;
}
}
i = LevelGenerate.Instance.playerY;
j = LevelGenerate.Instance.playerX;
if (!isWin && !isFail) //Если уровень не завершен
{
collideEnemy(); //Обнаружение столкновения с врагом
collectItem(); //Обнаружения столкновения с собираемым предметом
genNthOrdColls(2); //Генерация предметов n-ого порядка после сбора предметов (n-1)-ого
genNthOrdColls(3);
genNthOrdColls(4);
if (colls[0] == 0 && colls[1] == 0 && colls[2] == 0 && colls[3] == 0 && LevelGenerate.Instance.resLoaded) isWin = true; //Если все предметы собраны, то уровень завершен с прохождением
}
if (isWin && animationSet == 0) //Меняем спрайт игрока при завершении уровня
{
//LevelGenerate.Instance.player.GetComponent<SpriteRenderer>().sprite = winPlayer;
LevelGenerate.Instance.player.GetComponent<Animator>().CrossFade(animNames[1], 0);
animationSet++;
delayTime = 1.5f;
MusicManager.Instance.gameObject.GetComponent<AudioSource>().mute = true;
SoundManager.Instance.gameObject.GetComponent<AudioSource>().clip = SoundManager.Instance.sounds[0];
SoundManager.Instance.gameObject.GetComponent<AudioSource>().Play();
}
if (isWin && delayTime <= 0)
{
//path = Application.dataPath + "\\Levels\\SaveData1";
/*if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath;
path = Path.Combine(path, "Levels");
}
else if (Application.platform == RuntimePlatform.Android)
path = Application.persistentDataPath;
path = Path.Combine(path, "SaveData1");
fs = new FileStream(path, FileMode.Open);
bw = new BinaryWriter(fs);*/
levelNum = (byte)(Convert.ToByte(LevelGenerate.Instance.levelFile.Substring(5)) - 1);
levelNum++;
if (PlayerPrefs.GetInt("maxLevel") == levelNum)
{
PlayerPrefs.SetInt("maxLevel", (int)levelNum);
PlayerPrefs.Save();
}
PlayerPrefs.SetInt("level", (int)levelNum);
/*bw.Write(levelNum);
bw.Write("Level" + (levelNum+1).ToString());
bw.Close();
fs.Close();*/
SceneManager.LoadScene("Win");
} else if (delayTime > 0)
{
delayTime -= Time.deltaTime;
}
if (isFail && delayTime <= 0)
{
//path = Application.dataPath + "\\Levels\\SaveData1";
/*if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath;
path = Path.Combine(path, "Levels");
```
}
else if (Application.platform == RuntimePlatform.Android)
path = Application.persistentDataPath;
path = Path.Combine(path, "SaveData1");
fs = new FileStream(path, FileMode.Open);
bw = new BinaryWriter(fs);
fs.Seek(1, SeekOrigin.Begin);
bw.Write(LevelGenerate.Instance.levelFil e);
bw.Close();
fs.Close();*/
PlayerPrefs.SetString("levelFile", LevelGenerate.Instance.levelFile);
PlayerPrefs.Save();
SceneManager.LoadScene("Fail");
} else if (delayTime > 0)
{
delayTime -= Time.deltaTime;
}
}
```
Самый страшный метод из EventManager-а (модуль который отвечал за все события в игре - коллизию с врагом, таймаут непобедимости и пр.).
+1
//Генерация уровня из файла
void mapGenerate()
{
float x = 0.72f, y = -0.72f; //Координаты игрового объекта
byte i = 0, j = 0; //Цифровые координаты игрвоого объекта
while (y >= -5.76f)
{
while (x <= 5.76f)
{
if (map[i, j] % 8 == 1) //Если игровой объект - точка спавна игрока
{
player.transform.position = new Vector3(x, y, 0);
playerX = j;
playerY = i;
}
else if (map[i, j] % 8 == 5) //Если игровой объект - точка спавна врага
{
enemy.transform.position = new Vector3(x, y, 0);
enemyX = j;
enemyY = i;
//print("Enemy: " + enemyX + " " + enemyY);
} else if(map[i, j] % 8 == 6) //Если игровой объект - собираемый предмет
{
EventManager.Instance.colls[0]++; //Увеличивается количество собираемых монет на уровне
mapObj[i, j] = Instantiate(entities[map[i, j] % 8], new Vector3(x, y, 0), Quaternion.identity);
}
else if (map[i,j] % 8 != 0) { //Для остальных игровых объектов
mapObj[i,j] = Instantiate(entities[map[i, j] % 8], new Vector3(x, y, 0), Quaternion.identity);
}
x += 0.72f;
j++;
}
y -= 0.72f;
x = 0.72f;
j = 0;
i++;
}
}
//Считывание данных об уровне
void readLevelFile()
{
string path = "";
FileStream fs = null;
BinaryReader br = null;
if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath;
path = Path.Combine(path, "Levels");
path = Path.Combine(path, levelFile);
fs = new FileStream(path, FileMode.Open);
br = new BinaryReader(fs);
head = br.ReadBytes(8); //Чтение заголовка файла
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
map[i, j] = br.ReadByte(); //Чтение кода игрового объекта
}
}
br.Close();
fs.Close();
} else if (Application.platform == RuntimePlatform.Android)
{
byte[] file = null;
path = "jar:file://"+ Application.dataPath + "!/assets/Levels/"+levelFile;
www = new WWW(path);
while (!www.isDone) { }
if (!string.IsNullOrEmpty(www.error))
{
Debug.LogError("Can't read");
}
file = www.bytes;
for (int i = 0; i < 8; i++)
{
head[i] = file[i];
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
map[i, j] = file[j + i * 8 + 8]; //Чтение кода игрового объекта
}
}
www.Dispose();
}
Из кода собственной аркады на Unity 2017-ого года. Неоправданные байто*бские оптимизации, взаимодействие между модулями через десяток глобалов, магические константы не зафиксированные в именах кода, куча хардкода. И ето из модуля для генерации уровня. В модуле для управления событиями код страшнее.
0
Пиздец-оффтоп #18
#1: https://govnokod.ru/26503 https://govnokod.xyz/_26503
#2: https://govnokod.ru/26541 https://govnokod.xyz/_26541
#3: https://govnokod.ru/26583 https://govnokod.xyz/_26583
#4: https://govnokod.ru/26689 https://govnokod.xyz/_26689
#5: https://govnokod.ru/26784 https://govnokod.xyz/_26784
#5: https://govnokod.ru/26839 https://govnokod.xyz/_26839
#6: https://govnokod.ru/26986 https://govnokod.xyz/_26986
#7: https://govnokod.ru/27007 https://govnokod.xyz/_27007
#8: https://govnokod.ru/27023 https://govnokod.xyz/_27023
#9: https://govnokod.ru/27098 https://govnokod.xyz/_27098
#10: https://govnokod.ru/27125 https://govnokod.xyz/_27125
#11: https://govnokod.ru/27129 https://govnokod.xyz/_27129
#12: https://govnokod.ru/27184 https://govnokod.xyz/_27184
#13: https://govnokod.ru/27286 https://govnokod.xyz/_27286
#14: https://govnokod.ru/27298 https://govnokod.xyz/_27298
#15: https://govnokod.ru/27322 https://govnokod.xyz/_27322
#16: https://govnokod.ru/27328 https://govnokod.xyz/_27328
#17: https://govnokod.ru/27346 https://govnokod.xyz/_27346
0
def generate_words(sample, phonemes, num=10):
global words, yd
gen = True
parens = 0
r = random.random()
word = ""
i = 0
while i < int(num):
for j in range(0, len(sample)):
if sample[j] == '(':
if gen:
gen = (random.randint(0,1) == 0)
if not gen:
parens += 1
elif sample[j] == ')':
if not gen:
parens -= 1
if parens == 0:
gen = True
elif sample[j] in phonemes.keys():
for n, phtype in enumerate(phonemes.keys()):
if gen and phtype == sample[j]:
#k = random.choice(phonemes[phtype])
n = yd.randomGen(phonemeRanks[phtype])
k = phonemes[phtype][n]
word += k
elif gen:
word += sample[j]
if (not word in words) and (not isExceptional(word)):
words.append(word)
i += 1
word = ""
# ...
"""parsing sound changes rule with the notation X>Y/Z, where X is a set of source phonemes
Y - a set of resulting phonemes, Z - a positional condition (optional)"""
def parsePhNotation(inline):
rule = inline.split('>')
if (not len(rule) == 2):
return []
source = rule[0].split(',')
final = rule[1].split('/')
result = final[0].split(',')
posCond = []
rule = []
if (len(final) > 2):
return False
elif (len(final) == 2):
posCond = final[1].split('_')
if (not len(posCond) == 2):
return []
posCond[0] = posCond[0].split('#')
posCond[1] = posCond[1].split('#')
if (len(posCond[0]) == 2) and len(posCond[0][0]) > 0:
return []
elif len(posCond[0]) == 2:
rule.append(" "+posCond[0][1])
else:
rule.append(posCond[0][0])
if (len(posCond[1]) == 2) and len(posCond[1][1]) > 0:
return []
rule.append(posCond[1][0])
if len(posCond[1]) == 2:
rule[1] += " "
rule[0] = rule[0].split(",")
rule[1] = rule[1].split(",")
final = []
if len(source) > len(result):
for i in range(len(result)-1, len(source)-1):
result.append("")
elif len(source) < len(result):
for i in range(len(source)-1, len(result)-1):
source.append("")
final.append(source)
final.append(result)
if (len(rule)>0):
final.append(rule)
return final
Рекурсивный спуск, автомат с магазинной памятью, top-down parsing, bottom-up parsing? Не, не слышал. В свое время время делал вот такие самопальные алгоритмы для рандомной генерации слов по фонетическим шаблонам (типа "CV(C)", "VC" и т.д.) и фонетического преобразования слов и при попытке починить чета наступал на новые баги, т.к. не до конца понимал как вообще парсятся компьютерные языки.
0
-export([parse_transform/2, abstract/2]).
parse_transform(Forms, _Options) ->
normal(Forms).
normal({call, _Line, {atom, _, '$$'}, [Outer]}) ->
case Outer of
{'fun', _, {clauses, Quoted}} ->
%% Remove outer `fun' and only leave its clauses:
ok;
Quoted ->
%% A plain term has been quoted, leave it as is:
ok
end,
Result = abstract(Quoted),
%% io:format("Quoted block ~p~n", [Result]),
Result;
normal(L) when is_list(L) ->
lists:map(fun normal/1, L);
normal(T) when is_tuple(T) ->
list_to_tuple(lists:map(fun normal/1, tuple_to_list(T)));
normal(T) ->
T.
-define(line, 0).
%% @doc Create AST of the AST
abstract({call, _Line, {atom, _, '$'}, [Splice]}) ->
normal(Splice);
abstract(Orig = {var, Line, VarName}) ->
case lists:suffix("__AST", atom_to_list(VarName)) of
true ->
Orig;
false ->
{tuple, ?line, [ {atom, ?line, var}
, {integer, ?line, Line}
, {atom, ?line, VarName}
]}
end;
abstract(T) when is_tuple(T) ->
{tuple, ?line, lists:map(fun abstract/1, tuple_to_list(T))};
abstract([]) ->
{nil, ?line};
abstract([Hd|Tail]) ->
{cons, ?line, abstract(Hd), abstract(Tail)};
abstract(A) when is_atom(A) ->
{atom, ?line, A};
abstract(I) when is_integer(I) ->
{integer, ?line, I}.
Мета-метушня, убогое подобие лисповского квотирования.
0
#include <iostream>
#include <fstream>
using namespace std;
//ifstream in("C://Users//Илья//Desktop//calc.exe", ios::binary);
ifstream in("C://Users//Илья//Desktop//kernel32.dll", ios::binary );
ofstream out("D:\\hello.txt");
void printhex(int position, int size)
{
int *A = new int[size];
int n = 0;
in.seekg(position);
for (int i = 0; i < size; i++)
{
n = in.get();
A[i] = n;
}
for (int i = (size-1); i >= 0; i--)
{
printf("%02X", A[i]);
}
cout << endl;
}
int printdec(int position, int size)
{
int* A = new int[size];
int n = 0;
int result = 0;
in.seekg(position);
for (int i = 0; i < size; i++)
{
n = in.get();
A[i] = n;
}
for (int i = (size-1); i >= 0; i--)
{
result = result * 16 * 16 + A[i];
}
return result;
}
int main()
{
char c;
int n;
unsigned int n1 = 0;
in.seekg(60); //положение байта, содержащего значение смещения;
n1 = in.get();
printf("%02X", n1); //вывод смещения;
cout << endl;
in.seekg(n1); //положение подписи (PE);
for (int i = 0; i < 4; i++)
{
c = in.get();
cout << c; //вывод подписи (PE)
}
cout << endl;
int numb_of_sect = printdec(n1 + 6, 2);
cout << numb_of_sect << endl;
printhex(n1 + 24, 2);
printhex(n1 + 24 + 28, 4);
printhex(n1 + 24 + 28 + 68, 4);
int adr = printdec(n1 + 24 + 28 + 68, 4);
cout << "-----------------" << endl;
if(adr==0) //проверка наличия таблицы экспортов;
{
cout << "The export table is missing." << endl;
}
}
0
#define l '!'
main(int I){int _[]={[0]=01740,[10]=010[_
]>>4,[010]=0xf00,[0x10]=0,[011]=_[7]/0x10
,[013]=_[0011]/16,[13]=7,[014]=016,[14]=_
[7]>>12,[15]=001,[01]=0x03fFC,[2]=0x781F,
[3]=0x6E003,[4]=49152,[5]=_[04],['\a']=_[
6]>>1,['\''-l]=074000,};for(I=0;I<l*17-l/
2;++I,putchar((I%l<l/2)&&(_[I/(l)]&1<<15-
(I%l))?0x23:(I%l>(l/2))&&((I/(l))[_]&1<<(
15-((l-1)-(I%l))))?l|2:I*2==(((l/2)*_[13]
+3)*4)>>!!1?(((!l)["Fuck you!"])*(_[0x0f]
))>>1:!(I^((l/2)*9+004))?042+1:I-(l/2)*30
+02==!l?0x24^13[_]:!((I|((l/2)*32-1))^I)?
35:I+(l/2)*34==I<<1?l+_[14]-(_[4]/5[_]):!
!!!I*040),(I+1)%l==0?putchar(012):l+!l);}
Я покакал
−2
const connectToServerEpic = (
action$,
) => (
action$
.pipe(
ofType(CONNECT_TO_SERVER),
switchMap(({
hostname,
port,
protocol,
protocolVersion,
reconnectionTimeout,
}) => (
action$
.pipe(
ofType(RECONNECT_TO_SERVER),
takeUntil(
action$
.pipe(
ofType(DISCONNECT_FROM_SERVER),
)
),
startWith(null),
map(() => (
webSocket({
protocol: protocolVersion,
url: (
protocol
.concat('://')
.concat(hostname)
.concat(':')
.concat(port)
),
WebSocketCtor: WebSocket,
})
)),
switchMap((
webSocketConnection$,
) => (
webSocketConnection$
.pipe(
takeUntil(
action$
.pipe(
ofType(
RECONNECT_TO_SERVER,
DISCONNECT_FROM_SERVER,
),
)
),
catchError(() => (
timer(
reconnectionTimeout,
)
.pipe(
takeUntil(
action$
.pipe(
ofType(
RECONNECT_TO_SERVER,
DISCONNECT_FROM_SERVER,
),
)
),
mapTo(reconnectToServer()),
)
)),
map(receivedWebSocketMessage),
startWith(
connectionReady(
webSocketConnection$,
)
),
)),
)),
)
)),
)
)
https://itnext.io/simplifying-websockets-in-rxjs-a177b887f3b8