Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-4041-8081-

Post top tier code

Name: Anonymous 2014-07-22 13:29

Can be yours or not, I just want to see something good.

Name: Anonymous 2014-07-22 14:04

#include"stdio.h"
#include"conio.h"
#include"iostream.h"

void main(void){
int i;
while(i<10){
int i2;
printf_s("\rstarting");
while(i2<10){
putchar('.');
i2 = i2 + 1;
}
i = i + 1;
sleep(1);
}
printf_s("press any key...");
getch();
}

Name: Anonymous 2014-07-22 14:27

conio.h
top lel

Name: Anonymous 2014-07-22 15:11

>>3
It's lel

Name: Anonymous 2014-07-22 17:55

Bitpack!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdbool.h>

typedef struct {
unsigned char *p, *q;
size_t n, tmp, bits;
} bitptr;

void bitinit(bitptr *, void *, size_t, size_t);
void bitnext(bitptr *);
void bitprev(bitptr *);
void bitset(bitptr *, bool);
bool bitval(bitptr *);
void bitrewind(bitptr *);
size_t bitsize(bitptr *);
void bitpack(bitptr *, bitptr *, size_t, size_t);
void bitunpack(bitptr *, bitptr *, size_t, size_t);

void bitinit(bitptr *p, void *q, size_t n, size_t bits) {
p->p = p->q = q;
p->tmp = n;
p->bits = bits;
p->n = 0;
while(n--) bitnext(p);
}

void bitnext(bitptr *p) {
if(++p->n == CHAR_BIT) {
p->n = 0;
p->q++;
}
}

void bitprev(bitptr *p) {
if(p->n-- == 0) {
p->n = CHAR_BIT - 1;
p->q--;
}
}

void bitset(bitptr *p, bool b) {
if(b)
*p->q |= (b << p->n);
else
*p->q &= ~(b << p->n);
}

bool bitval(bitptr *p) {
return *p->q & (1 << p->n);
}

void bitrewind(bitptr *p) {
size_t n;

p->q = p->p;
p->n = p->tmp;
for(n = p->tmp; n--; bitnext(p));

}

size_t bitsize(bitptr *p) {
return p->bits;
}
#define bitsize(p) ((p)->bits)

void bitpack(bitptr *p, bitptr *q, size_t size, size_t nmemb) {

size_t n;

while(nmemb--) {
n = size;
while(n--) {
bitset(p, bitval(q));
bitnext(p);
bitnext(q);
}
if((n = bitsize(q) - size) != 0)
while(n--) bitnext(q);
}

}

void bitunpack(bitptr *p, bitptr *q, size_t size, size_t nmemb) {

size_t n;

while(nmemb--) {
n = size;
while(n--) {
bitset(p, bitval(q));
bitnext(p);
bitnext(q);
}
if((n = bitsize(p) - size) != 0)
while(n--) bitnext(p);
}

}

#define objsize(obj) (sizeof obj * CHAR_BIT)
static const char map[] = "abcdefghijklmnopqrstuvwxyz";
#define mapletter(x) (strchr(map, x) - map)

int main(void) {

bitptr p, s;
char buf[3] = {0}, x[] = { mapletter('h'), mapletter('e'), mapletter('l'), mapletter('l'), mapletter('o'), 0 };
size_t n;

bitinit(&p, buf, 0, objsize(buf[0]));
bitinit(&s, x, 0, objsize(x[0]));
bitpack(&p, &s, 4, sizeof x - 1);
bitrewind(&p);
bitrewind(&s);
printf("Message 'hello' stored in 3 bytes array. contents of s.p:\n");
memset(x, 0, sizeof x);
bitunpack(&s, &p, 4, sizeof x - 1);
for(n = 0; n < sizeof x - 1; n++)
s.p[n] = map[s.p[n]];

puts((void *)s.p);

return 0;
}

Name: Anonymous 2014-07-23 1:29

>>5
Packing/unpacking one bit at a time like that is going to be horribly slow. Probably better to use an array of unsigned int and use shifts and masks to pack sizeof(unsigned) * CHAR_BIT bits at a time wherever possible. The cfbcopyarea routines in the Linux kernel do this but the implementation there is rather wizardly.

Name: Anonymous 2014-07-23 4:35

>>5
#define objsize(obj) (sizeof obj * CHAR_BIT)
What if it overflows?

Name: Anonymous 2014-07-23 6:24

>>6
I did not go for efficiency! I'd use assembly if I had to. From a quick glance I didn't understand cfb_copyarea, but it's been some time since I had to write C.

Except bitpacking, >>5 implements the concept of bitpointers, so you get single access to each bit with a pointer called bitptr. For example you can do this:
bitptr *p, *q;
/* p gets initialized to something */
q = p; // now q points to the same bitptr, incrementing q will increment p
*q = *p; // q is a copy of p, incrementing q does not affect p

Of course in C++ this could be written to be almost like a real pointer, with operator overloading.

>>7
AFAIK it can't, but a quick search does not reveal any reputable sources, or heck, even something relevant. The days I searched ISO pdf drafts is over, so I don't know. Assuming it can, the behavior is still defined. Overflow of unsigned integers is defined, therefore you'd just get less bits available than what you asked. Nothing catastrophic, like your PDP-7 exploding.

Name: Anonymous 2014-07-24 17:11

>>8
Yes, I get that. Personally I'd probably just use a plain integer type as the pointer type, and just have each function extract the index within the last word of the bit array via a modulo operation.

Storing an extra position (q) for seeking is an interesting idea; but since it's extra state to manage you might consider adding a stream abstraction on top of the basic bit-buffer implementation instead of combining them like this.

Name: Anonymous 2014-07-25 5:04

>>9
a plain integer type as the pointer type
Don't let lambda hear that

Name: Anonymous 2014-07-25 9:18

/* With gcc3.1, must omit -ansi to compile eol comments */

#include <stdio.h>
#include <stdlib.h>

static int ch, lastch;

/* ---------------- */

static void putlast(void)
{
if (0 != lastch) fputc(lastch, stdout);
lastch = ch;
ch = 0;
} /* putlast */

/* ---------------- */

/* gobble chars until star slash appears */
static int stdcomment(void)
{
int ch, lastch;

ch = 0;
do {
lastch = ch;
if (EOF == (ch = fgetc(stdin))) return EOF;
} while (!(('*' == lastch) && ('/' == ch)));
return ch;
} /* stdcomment */

/* ---------------- */

/* gobble chars until EOLine or EOF. i.e. // comments */
static int eolcomment(void)
{
int ch, lastch;

ch = '\0';
do {
lastch = ch;
if (EOF == (ch = fgetc(stdin))) return EOF;
} while (!(('\n' == ch) && ('\\' != lastch)));
return ch;
} /* eolcomment */

/* ---------------- */

/* echo chars until '"' or EOF */
static int echostring(void)
{
putlast();
if (EOF == (ch = fgetc(stdin))) return EOF;
do {
putlast();
if (EOF == (ch = fgetc(stdin))) return EOF;
if (('\\' == ch) && ('\\' == lastch)) {
putlast();
ch = '\0';
}
} while (!(('"' == ch) && ('\\' != lastch)));
return ch;
} /* echostring */

/* ---------------- */

int main(void)
{
lastch = '\0';
while (EOF != (ch = fgetc(stdin))) {
if ('/' == lastch)
if (ch == '*') {
lastch = '\0';
if (EOF == stdcomment()) break;
ch = ' ';
putlast();
}
else if (ch == '/') {
lastch = '\0';
if (EOF == eolcomment()) break;
ch = '\n';
putlast(); // Eolcomment here
// Eolcomment line \
with continuation line.
}
else {
putlast();
}
else if (('"' == ch) && ('\\' != lastch)
&& ('\'' != lastch)) {
if ('"' != (ch = echostring())) {
fputs("\"Unterminated\" string\n", stderr);

/* You can exercise this code by feeding the
program an unterminated string, then EOF */
fputs("checking for\
continuation line string\n", stderr);
fputs("checking for" "concat string\n", stderr);
printf("What\\" /* embedded string */ "%s joke!\n",
/* doh */ "a /*#(K1N5");

return EXIT_FAILURE;
}
putlast();
}
else {
putlast();
}
} /* while */
putlast(/* embedded comment */);
return 0;
} /* main */

Name: Anonymous 2014-07-29 11:17

>>11
if ('/' == lastch)
if (ch == '*')
I want to kick you in the balls, asshole.

Name: Anonymous 2014-07-29 11:40

function [tblNode, tblPath, mapx] = initGraph(map, m2, node)

moveset = [1,0; 0,-1; -1,0; 0,1];

n = size(node,1);

p = sum(node(:,3)) / 2;

pcount=1;

tblNode = zeros(n, 6);

tblPath = zeros(p, 3);

mapx = map; %% .- (m2>0);

for(iterN = 1:n)

nodeXY = node(iterN, 1:2);

mapx(nodeXY(1), nodeXY(2)) = 0;

for(iterP = 1:4)

pid = 0;

cyx = nodeXY .+ moveset(iterP, :);

if(mapx(cyx(1), cyx(2)) > 1)

pid = mapx(cyx(1), cyx(2)) - 1;

nids = tblPath(pid, [1,2]);

nid = nids(nids!=iterN)

endif;


if(mapx(cyx(1), cyx(2)) == 1)

pid = pcount;

pcount += 1;

[mapx, dC, nid] = scanGraph(mapx, m2, cyx, pid);

tblPath(pid,:) = [iterN, nid, dC];

tblPath(pid,:)

endif;

tblNode(iterN, iterP) = pid;

endfor;

tblNode(iterN, [5,6]) = node(iterN, [1,2]);

tblNode(iterN,:)

mapx(nodeXY(1), nodeXY(2)) = 1;

endfor;

endfunction;

Name: Anonymous 2014-07-29 12:27

Here's a grid graph implemetation of mine, complete with ascii print too. Main feature is the 1-1 encoding of edges to bits, so for a grid of size WxH, exactly 2HW - H - W bits of memory (in theory -- I don't expect std::vector<bool> to behave exactly like that) are used to represent the edges. The magic of this is in the functions Index2Edge and Edge2Index which translate an edge {u, v} to its corresponding index i in the bool vector.

I'm posting it because I think it's kinda relevant to what >>13 does, I think his code does something for ICFP '14?

#include <vector>
#include <deque>
#include <iostream>
#include <algorithm>
#include <cstdlib>

class Grid {
public:
typedef struct { int x, y; } Point;
typedef struct { Point u, v; } Edge;
Grid(void);
Grid(int, int, bool = false);
void Init(int, int, bool = false);
bool IsCorner(const Point&) const;
bool IsOuter(const Point&) const;
bool IsInner(const Point&) const;
int N(const Point&) const;
int N(const Point&, std::deque<Point>&) const;
int Neighbours(const Point&) const;
int Neighbours(const Point&, std::deque<Point>&) const;
void AddEdge(const Edge&);
void RemoveEdge(const Edge&);
bool ExistsEdge(const Edge&) const;
void Print(std::ostream& o, const char * = nullptr) const;
int GetHeight(void) const;
int GetWidth(void) const;
void Edge2Index(const Edge&, int&) const;
void Index2Edge(int, Edge&) const;
private:
int w, h;
std::vector<bool> edges;
};

Grid::Grid(void) {
;
}

Grid::Grid(int w, int h, bool value) {
Grid::Init(w, h, value);
}

void Grid::Init(int w, int h, bool value) {
Grid::w = w;
Grid::h = h;
Grid::edges.resize(2 * h*w - h - w, value);
}

int Grid::GetHeight(void) const {
return Grid::h;
}

int Grid::GetWidth(void) const {
return Grid::w;
}

/* Number of neighbours connected to p */
int Grid::N(const Grid::Point& p) const {
int i, n = 0;
if (p.x != 0) {
Grid::Edge2Index({ p, { p.x - 1, p.y } }, i);
n += Grid::edges[i];
}
if (p.y != 0) {
Grid::Edge2Index({ p, { p.x, p.y - 1 } }, i);
n += Grid::edges[i];
}
if (p.x != Grid::w - 1) {
Grid::Edge2Index({ p, { p.x + 1, p.y } }, i);
n += Grid::edges[i];
}
if (p.y != Grid::h - 1) {
Grid::Edge2Index({ p, { p.x, p.y + 1 } }, i);
n += Grid::edges[i];
}
return n;
}

/* Number and deque list of neighbours connected to p */
int Grid::N(const Grid::Point& p, std::deque<Point>& d) const {
int i, n = 0;
if (p.x != 0) {
Grid::Edge2Index({ p, { p.x - 1, p.y } }, i);
if (Grid::edges[i]) {
n++;
d.push_back({ p.x - 1, p.y });

}
}
if (p.y != 0) {
Grid::Edge2Index({ p, { p.x, p.y - 1 } }, i);
if (Grid::edges[i]) {
n++;
d.push_back({ p.x, p.y - 1 });
}
}
if (p.x != Grid::w - 1) {
Grid::Edge2Index({ p, { p.x + 1, p.y } }, i);
if (Grid::edges[i]) {
n++;
d.push_back({ p.x + 1, p.y });
}
}
if (p.y != Grid::h - 1) {
Grid::Edge2Index({ p, { p.x, p.y + 1 } }, i);
if (Grid::edges[i]) {
n++;
d.push_back({ p.x, p.y + 1 });
}
}
return n;
}

/* Number of points that can possibly be connected to p */
int Grid::Neighbours(const Point& p) const {
if (IsInner(p)) return 4;
else if (IsCorner(p)) return 2;
else return 3;
}

/* List of points that can possibly be connected to p */
int Grid::Neighbours(const Point& p, std::deque<Point>& d) const {
int n = 0;
if (p.x > 0)
n++, d.push_back({ p.x - 1, p.y });
if (p.y > 0)
n++, d.push_back({ p.x, p.y - 1 });
if (p.x < w - 1)
n++, d.push_back({ p.x + 1, p.y });
if (p.y < h - 1)
n++, d.push_back({ p.x, p.y + 1 });
return n;
}

bool Grid::IsCorner(const Grid::Point& p) const {
return (p.x == 0 || p.x == Grid::w - 1)
&& (p.y == 0 || p.y == Grid::h - 1);
}

bool Grid::IsOuter(const Grid::Point& p) const {
return !p.x || !p.y || p.x == Grid::w - 1 || p.y == Grid::h - 1;
}

bool Grid::IsInner(const Grid::Point& p) const {
return p.x && p.y && p.x != Grid::w - 1 && p.y != Grid::h - 1;
}

/* Converts a user edge {p, q} to private class index for the edges vector */
void Grid::Edge2Index(const Grid::Edge& e, int &i) const {
if (e.u.y == e.v.y)
i = e.u.y * (w - 1) + std::min({ e.u.x, e.v.x });
else
i = h*(w - 1) + std::min({ e.u.y, e.v.y }) * w + e.u.x;
}

/* Translates an index to an edge {p, q} */
void Grid::Index2Edge(int i, Grid::Edge& e) const {
div_t x;
if (i < (w - 1)*h) {
x = div(i, w - 1);
e.v.x = 1 + (e.u.x = x.rem);
e.u.y = e.v.y = x.quot;
}
else {
i -= (w - 1)*h;
x = div(i, w);
e.u.x = e.v.x = x.rem;
e.v.y = 1 + (e.u.y = x.quot);
}
}

void Grid::AddEdge(const Grid::Edge& e) {
int i;
Grid::Edge2Index(e, i);
Grid::edges[i] = true;
}

void Grid::RemoveEdge(const Grid::Edge& e) {
int i;
Grid::Edge2Index(e, i);
Grid::edges[i] = false;
}

bool Grid::ExistsEdge(const Grid::Edge& e) const {
int i;
Grid::Edge2Index(e, i);
return Grid::edges[i];
}

void Grid::Print(std::ostream& o, const char *prefix) const {
for (int j = 0; j < Grid::h; j++) {
if (prefix) o << prefix;
for (int i = 0; i < Grid::w; i++) {
if (Grid::N({ i, j }))
o << '*';
else
o << ' ';
if (i != Grid::w - 1) {
if (Grid::ExistsEdge({ { i, j }, { i + 1, j } }))
o << "---";
else
o << " ";
}
}
o << std::endl;
if (prefix) o << prefix;
if (j != Grid::h - 1)
for (int i = 0; i < Grid::w; i++) {
if (Grid::ExistsEdge({ { i, j }, { i, j + 1 } }))
o << '|';
else
o << ' ';
if (i != Grid::w - 1)
o << " ";
}
o << std::endl;
}
}

Name: Anonymous 2014-07-29 20:12

>>14
No comment on the code whatsoever? I'm disappointed...

Name: Anonymous 2014-07-29 21:12

bumping again. These faggots take the #1 post with bullshit unrelated to /prog/.

Name: sage 2014-07-30 0:20

>>14
This will be perfect for my next chess program implemented on a calculator with only 112 bits of memory

Name: Anonymous 2014-07-30 1:05

>>14
Yep, >>13 builds a couple of tables for a recursive graph search, and a spatial edge index. mapx(LocY, LocX) gives an edge index+1 >=2, or ==1 on a Node, then you can get the next two Nodes for a given edge, and up to four Edges for a given Node..
The nice bit is these should work concurrently, so depth 4 and starting on an edge gives [all nodes(4)] connected to [all edges(3)] connected to [all nodes(2)] connected to [initial edge(1)], in four operations =)

Name: Anonymous 2014-07-30 1:25

>>18
What are you searching the graph for? What kind of tables does it build? What do you mean by spatial edge index?

I'm sorry but I don't understand your code nor your post -- undoubtedly it's something smart and I'd appreciate if you could explain it further.

Name: Anonymous 2014-07-30 2:11

So, this would be a spatial edge index for a 5x8 map, with 3 edges marked by values 2-4, two nodes with values of 1, and 0's for the walls.
00000000
02221330
02004030
02221330
00000000

Then you just look-up the element at y,x to find the edge Id for a target item (lambda-man / ghost / remaining pills / power-pill / fruit..)

Name: Anonymous 2014-07-30 2:41

There is two tables that form a circular database =) it's mostly key values with some minimal extra info. So you have a list of edges accessed by the edge id, which just tells you the node id's for that edge, and the length of the edge. And you have a list of nodes that tell you which edge id's connect to that node, and the y,x coord of the node..
So if you're at (2,2) on the map above, the spatial index will tell you you are on edge id 2. Then if you look in the edge table, it tells you the next nodes are node id 1 & 2, and the length of the edge is 7..

Name: Anonymous 2014-07-30 2:44

>>6

Packing/unpacking one bit at a time like that is going to be horribly slow.
It won't be, because memory is the bottleneck and superscalar architecture can unpack several bit at once.
I.e.
x = word & 1;
y = word & 2;
z = word & 4;

would be as fast as single x = word & 1

Name: Anonymous 2014-07-30 2:53

>>21
That's mighty cool. Thanks for explaining.

>>22
Eh, how is memory the bottleneck? I doubt that with all the abstraction my x = bitval(p); bitnext(p); y = bitval(p); bitnext(p); z = bitval(p); will be translated into 3 AND instructors. I don't know how superscalar architecture works, but I doubt it does miracles. This needs to be written in assembly for proper optimization.

Name: Anonymous 2014-07-30 2:58

>>7
Also, to reply to >>7 on a second thought, objsize is not part of the code, but part of the example that followed. So, 1) it won't overflow, since I use it on small objects in the example, 2) objsize is not relevant.

Name: Anonymous 2014-07-30 3:00

>>23

all the abstraction
declare them inline

Name: Anonymous 2014-07-30 3:21

>>25
I just realized that I smoked crack when I wrote the code in >>5. There's a HUGE bug with the variable called 'tmp'. I tried to understand what it does and I finally realize that for values other than tmp = 0, nothing works as expected. I don't use the value of tmp when I increase q whenever n hits CHAR_BIT. That's nonsense, because tmp is supposed to represent (although it's not clear by the variable naming), the offset pointed to by the bitpointer.

So yeah, I will rewrite all this in C++.

Name: Anonymous 2014-07-30 5:15

Delivered, bitptr in C++. I didn't write the bitpack/unpack routines, I just implemented the concept of a bitpointer.
#include <climits> // CHAR_BIT
#include <cstdlib> // div, div_t

class bitref;

class bitptr {
friend class bitref;
public:
bitptr(void *memory = nullptr, int offset = 0);
bitptr& operator+=(int j);
bitptr& operator-=(int j);
bitptr& operator++();
bitptr& operator--();
bitptr operator++(int);
bitptr operator--(int);
bitref operator*() const;
bool operator==(const bitptr& rhs) const;
bitptr& operator=(void *rhs);

private:
unsigned char *p;
int i;
};

class bitref {
public:
bitref(const bitptr& p) : p(p.p), i(p.i) {};
bitref& operator=(bool b) {
if (b)
*p |= 1 << i;
else
*p &= ~(unsigned char)(1 << i);
return *this;
}
bool operator==(bool b) {
return b == (*p & (1 << i));
}
explicit operator bool() const { return *p & (1 << i); }
private:
unsigned char *p;
int i;
};

bitptr::bitptr(void *memory, int offset) {
div_t d;
p = static_cast<unsigned char *>(memory);
d = div(offset, CHAR_BIT);
p += d.quot;
i = d.rem;
}

bitptr& bitptr::operator+=(int j) {
div_t d;
d = div(j + i, CHAR_BIT);
p += d.quot;
i = d.rem;
return *this;
}

bitptr& bitptr::operator-=(int j) {
return *this += -j;
}

bitptr& bitptr::operator++() {
if (++i == CHAR_BIT) ++p, i = 0;
return *this;
}

bitptr& bitptr::operator--() {
if (--i == -1) --p, i = CHAR_BIT - 1;
return *this;
}

bitptr bitptr::operator++(int) {
bitptr val{ *this };
++*this;
return val;
}

bitptr bitptr::operator--(int) {
bitptr val{ *this };
--*this;
return val;
}

bitref bitptr::operator*(void) const {
return bitref(*this);
}

bool bitptr::operator==(const bitptr& q) const {
return p == q.p && i == q.i;
}

bitptr& bitptr::operator=(void *q) {
p = static_cast<unsigned char *>(q);
i = 0;
return *this;
}
// Example
int main(void) {
bitptr p, q;
char c = 0;
p = static_cast<void*>(&c);
q = p;
*p = *q;
q++;
*q = 1;
return 0;
}

Name: Anonymous 2014-07-30 5:25

>>27
Ah, I forgot to overload []. Add these definitions (and appropriate declarations in the class declaration of course):
bitptr bitptr::operator+(int j) const {
bitptr val{ *this };
val += j;
return val;
}

bitptr bitptr::operator-(int j) const {
bitptr val{ *this };
val -= j;
return val;
}

bitref bitptr::operator[](int j) const {
return *(*this + j);
};


With this, you can dump the binary of "Hello world" to output, like this:
char s = "Hello world";
bitptr p{static_cast<void*>(s)};
for(int i = 0; i < 11*CHAR_BIT; i++)
std::cout << p[i] ? "1" : "0";
std::cout << std::endl;

Name: Anonymous 2014-07-30 5:27

>>28
also to make + symmetric, more definitions need to be added (to make things like *(42 + p) and 42[p] work).

Name: Anonymous 2014-07-31 4:48

More fragments... =)

%% initmap.m %%

Fname = "classic.txt"

b = getMap(Fname);

b2 = b != tvalues(2);

bx = b == tvalues(6);

%%imshow(bx)

%%pause;

bz = reMap(bx, b2);

%%break;

zf = [0,1,0; 1,4,1; 0,1,0];

x = size(b2,2);

y = size(b2,1);

b3 = zeros(y,x);

b3(2:end-1, 2:end-1) = zfilter(bz, zf);

%imshow(b3 ./ 8)

bx = ((b3 > 4) .- (b3 == 6)) == 1;

by = zeros(y,x);

by(bx) = [1:sum(bx(:))];

imshow(by ./ sum(bx(:)));

nodes = sum(bx(:));

node = zeros(nodes, 3);

for(itery = 1:y)

for(iterx = 1:x)

if(bx(itery, iterx))

item = by(itery, iterx);

link = b3(itery, iterx) - 4;

node(item, :) = [itery, iterx, link];

endif;

endfor;

endfor;

figure(2);

plot(node(:,1), '-r', node(:,2), '-b', node(:,3), '-g');

maxTicks = fun_Eol(y,x);

%% end %%

function bx = reMap(bx, b2);

z2 = [0,1,0; 1,1,1; 0,1,0];

oldbx = b2;

i=0;

%%imshow(bx)

%%pause;

while(sum(oldbx(:) == bx(:)) < length(bx(:)))

oldbx = bx;

bn = (zfilter(bx, z2) > 0);

bx(2:end-1, 2:end-1) = bn;

bx = bx .* b2;

%%imshow(bx);

%%sleep(0.5);

%%++i

endwhile;

endfunction;

Name: Anonymous 2014-07-31 18:13

>>30
what is this language? matlab?

Name: Anonymous 2014-07-31 22:55

Octave, so pretty much matlab...
matlab doesn't like the endif, endfor, etc.. but everything else should be fine =)

Name: Anonymous 2014-07-31 23:14

This is the main loop as it is currently, everything else (~11 scripts) is just setting up this bit..

%% simstep.m %%

for(iterx = 1:ghosts+1)

tick = 0;

inktick = min([gtcounter, lmancounter] .- tick);

tick += inktick;

g_move = sum(gtcounter == tick);

g_id = [1:ghosts];

if(g_move>0)

gidx = g_id(gtcounter == tick);

for(iterg = 1:g_move)

id = gidx(iterg);

[gl, gs] = MoveGhost(glocate(id, :), gstatus(id,:), bz);

glocate(id,:) = gl;

gstatus(id, 2:3) = gs;

gtcounter(id) += tickgh(1, mod(id-1, 4)+1);

endfor;

endif;

lmove = lmancounter == tick;

if(lmove)

[xl, xs] = MoveGhost(lmanlocate, lmanstatus, bz); %%MoveLman();

lmanlocate = xl;

lmanstatus([2,3]) = xs;

lmancounter += ticklman(1);

endif;

endfor;

clf;

imshow(bz);

hold on; plot(glocate(:,2), glocate(:,1), 'rx', 'linewidth', 2);

plot(lmanlocate(:,2), lmanlocate(:,1), 'b+', 'linewidth', 2);

%% end %%

function [nloc,nstat] = MoveGhost(loc, status, map)

moveset = [1,0; 0,-1; -1,0; 0,1];

moves = zeros(4,1);

mid = [1:4];

for(iter = 1:4)

y = loc(1) + moveset(iter,1);

x = loc(2) + moveset(iter,2);

if( (status(2) == -moveset(iter,1)) + (status(3) == -moveset(iter,2))== 2)

lastmove = iter;

endif;

moves(iter) = map(y,x);

endfor;

nmoves = sum(moves);

if(nmoves == 1)

nstat = moveset(lastmove, :);

endif;

if(nmoves == 2)

moves(lastmove) = 0;

nstat = moveset(mid(moves==1),:);

endif;

if(nmoves > 2)

moves(lastmove) = 0;

rp = randperm(nmoves-1);

xm = mid(moves==1);

xm = xm(rp(1));

nstat = moveset(xm, :);

endif;

%%nstat

nloc = loc .+ nstat(1,:);

nstat = nstat(1,:);

endfunction;

Name: Anonymous 2014-08-02 15:48

val _ = print ("Hello, world!\n")

implement main0 () = ()

Name: Anonymous 2014-08-03 0:35

Octave/Matlab/Scilab are shit languages, Luke. Learn Mathematica and Scheme.

Name: Anonymous 2014-08-03 4:33

>>35
Actually, all languages are shit.

Name: Anonymous 2014-08-03 6:41

If it ain't Ruby, it's crap.

Name: od says 2014-08-03 7:34

inb4 sicp

for our databases: PostgreSQL
for our services: Go
for our scripts: Racket
for our frontends: AngularJS (to be replaced asap by Web Components)

Name: od says 2014-08-03 7:41

Name: Anonymous 2014-08-03 8:45

>>39

static typing
instant fail.

Name: Anonymous 2014-08-03 12:13

Name: Anonymous 2014-08-03 13:03

>>41
Actually, it will unable to build the PCI board that has a function which satisfied the PCI standard with only standard logic ICs. […] Therefore, it is possible that a PCI board to operate only as a target device uses small-scale PLD and it is made.
Smells like Markov chains.

Name: Anonymous 2014-08-03 16:14

>>40
War is peace, freedom is slavery, static typing is a failure.
Also, all languages are statically typed, even Scheme.

Name: Anonymous 2014-08-03 16:55

>>38
The typical webmonkey toolset?

Name: Anonymous 2014-08-03 17:39

>>38
Why are people so ignorant of their history?

Name: Anonymous 2014-08-03 18:20

So basically like prolog then.

Name: Anonymous 2014-08-06 18:41

take Int x ... from Range(100) as numbers.
loop for n in numbers do
take Bool from NModM(n; 3) as fizz.
take Bool from NModM(n; 5) as buzz.
if not fizz and not buzz then
PrintInt(n).
else
if fizz then Print("Fizz"). fi.
if buzz then Print("Buzz"). fi.
fi.
Print("\n").
done.

proc Range take Int as len.
create Int x len as range.
declare Int of 1 as i.
loop while i <= len do
range:i <- i.
i <- i + 1.
done.
corp.

Name: Anonymous 2014-08-07 11:07

>>47
Imperative loops are in no way "top-tier", dumbass.

Name: Anonymous 2014-08-07 11:12

>>47
What language is this? Seems like a weird version of Ada

Name: Anonymous 2014-08-07 17:43

>>48,49
It's an experiment I'm working on. Part of the design concept is being able to run in constant stack space (ie. static allocation of procedure activation records) so there are some limitations on calling functions. The compiler doesn't actually work yet though.

Name: Anonymous 2014-08-07 17:47

>>50
Part of the design concept is being able to run in constant stack space (ie. static allocation of procedure activation records)
I remember some Ada users did something like this, I am not so sure

Name: Anonymous 2014-08-08 6:21

>>50
Why do this when a static call graph analysis will tell you the maximum stack extent anyway (provided recursion is not allowed)?

Name: Anonymous 2014-08-08 6:22

>>52
recursion is not allowed
recursion is not allowed
recursion is not allowed

Imperative numbskulls have gone totally cuckoo.

Name: Anonymous 2014-08-08 6:43

Nah, you can still do recursion in imperative stylee

Name: Anonymous 2014-08-08 9:40

>>53
It's funny because in OpenCL recursion is not allowed, not even tail recursion

Name: Anonymous 2014-08-08 9:51

>>55
Well, I didn't have any doubts that OpenCL is a failure. Also, nice dubs.

Name: >>47,50 2014-08-08 23:13

>>55
Tail calls are in fact the only place I allow recursion, and at the moment, only to the calling function. I'm sure I could loosen up those rules with better analysis, but it's not a priority right now.

Name: Anonymous 2014-08-09 0:38

If recursion is just a feedback loop (current state x -> next state y via function z)... isn't all `imperative' coding recursive?

Name: Anonymous 2014-08-09 0:51

loop
y = z(x)
x = y

is the same as y = z(z(z(z(z(z(x))))))

except you have access to other variables in the former?

Name: Anonymous 2014-08-09 1:15

functions are good for cleaning up junk variables and redundant code though =)

Name: Anonymous 2014-08-09 1:42

Consider this

printf( fibs( fibs( fibs( 1:n ))))

Name: Anonymous 2014-08-09 1:51

>>58
coding
Shalom!

Name: Anonymous 2014-08-09 2:57

ah, just about needs a bignum library... fibs(fibs(10)) is nearly too big for 64 bit ints =)

maybe fibx(n) = fibs(n+8) - fibs(n+4) + fibs(n+2)

Name: Anonymous 2014-08-09 3:35

fibs(2n) = fibs(n)^2 + fibs(n+1)^2 ?

Name: Anonymous 2014-08-09 3:50

>>63,64 hasn't read SICP.

Name: Anonymous 2014-08-09 4:04

Fuerst Hash.

Faster than xxhash, MumurHash, SpookyHash, SBox, CityHash, and all FNV variants. Even faster than Intel's CRC32 instructions. It also has better properties and less collisions than all of the above, due to the 256-bit accumulation window. None of the plebs know about it, and probably never will. They prefer to use shit.

I hand rolled this for x86. x86-64 version was easier and cleaner, due to the larger register count and native 64-bit x 64-bit -> 128-bit integer multiplies.

#
# uint64_t memhash(void const* key, size_t n, uint64_t seed);
#
# Based off of the fast byteswap hash function by Steven Fuerst.
# http://locklessinc.com/articles/fast_hash/
#

.text
.align 16, 0x90

factor128:
.octa 0xd6c573e9c613993d5a379ab38dc5a46b

mix1:
.octa 0x1591aefa5e7e5a171591aefa5e7e5a17

mix2:
.octa 0x2bb6863566c4e7612bb6863566c4e761

.global memhash
.type memhash, @function

memhash:
movl 4(%esp), %ecx # key
movl 8(%esp), %edx # n
movq 12(%esp), %xmm2 # seed
pushl %edi
movd %edx, %xmm1
pushl %esi
movdqa (factor128), %xmm3
movdqa (mix1), %xmm6
movdqa (mix2), %xmm7
cmpl $32, %edx
jb 2f
mov %edx, %eax
shr $5, %eax
testb $15, %cl
jne 5f

# Aligned main loop, process 32-byte aligned chunks at a time

.align 8, 0x90
1: paddq (%ecx), %xmm1
paddq 16(%ecx), %xmm2
pmullw %xmm3, %xmm1
pmullw %xmm3, %xmm2
add $32, %ecx
movdqa %xmm1, %xmm0
punpckhbw %xmm2, %xmm1
punpcklbw %xmm0, %xmm2
dec %eax
jne 1b
pxor %xmm2, %xmm1

# Check for remaining chunk, otherwise extract 128 bits state and proceed to final mix

2: testb $31, %dl
jne 3f
movhlps %xmm1, %xmm2
jmp 4f

# Hash remaining chunk, up to 31-bytes in size

3: testb $16, %dl
je 3f
movdqu (%ecx), %xmm0
add $16, %ecx
pxor %xmm0, %xmm1
pmullw %xmm3, %xmm1
3: pxor %xmm3, %xmm3
movhlps %xmm1, %xmm2
testb $8, %dl
je 3f
movq (%ecx), %xmm0
add $8, %ecx
pxor %xmm0, %xmm1
3: testb $4, %dl
je 3f
movd (%ecx), %xmm3
add $4, %ecx
3: testb $2, %dl
je 3f
movzwl (%ecx), %eax
psllq $16, %xmm3
movd %eax, %xmm0
add $2, %ecx
paddq %xmm0, %xmm3
3: testb $1, %dl
je 3f
movzbl (%ecx), %eax
psllq $8, %xmm3
movd %eax, %xmm0
paddq %xmm0, %xmm3
3: pxor %xmm3, %xmm2

# Use 3x 128bit multiply and xorshift for final mix

4: # Iteration #0

pshufd $0b10110001, %xmm6, %xmm3
punpckldq %xmm1, %xmm1
pmuludq %xmm1, %xmm3 # [H|G|F|E] = [hash1.high * mix1.high | hash1.low * mix1.high]
punpckldq %xmm2, %xmm2
pmuludq %xmm6, %xmm1 # [D|C|B|A] = [hash1.high * mix1.low | hash1.low * mix1.low]
movd %xmm3, %ecx
pshufd $0b11100001, %xmm1, %xmm1
pshufd $0b11100001, %xmm3, %xmm3
movd %xmm1, %edx
movd %xmm3, %esi
pshufd $0b11010010, %xmm1, %xmm1
pshufd $0b01110010, %xmm3, %xmm3
movd %xmm1, %eax
xor %edi, %edi
pshufd $0b00100111, %xmm1, %xmm1
add %eax, %edx # X = B + C
movd %xmm1, %eax
adc $0, %eax # Y = D + carry
adc $0, %edi # Z = carry
add %ecx, %edx # X = X + E
punpckhdq %xmm1, %xmm1 # [0|0|0|A]
movd %edx, %xmm0 # [0|0|0|X]
adc %esi, %eax # Y = Y + F + carry
movd %xmm3, %edx
punpckhdq %xmm3, %xmm3
adc $0, %edi # Z = Z + carry
movd %xmm3, %esi
add %edx, %eax # Y = Y + G
pshufd $0b10101111, %xmm7, %xmm3
adc %esi, %edi # Z = Z + H + carry
movd %eax, %xmm5 # [0|0|0|Y]
movd %edi, %xmm4 # [0|0|0|Z]
punpckldq %xmm0, %xmm1 # [0|0|X|A] = [0 | lower 64-bits of hash1 * mix1]
punpckldq %xmm4, %xmm5 # [0|0|Z|Y] = [0 | upper 64-bits of hash1 * mix1]
pmuludq %xmm2, %xmm3 # [h|g|f|e] = [hash2.high * mix2.low | hash2.low * mix2.high]
pxor %xmm0, %xmm0
pmuludq %xmm7, %xmm2 # [d|c|b|a] = [hash2.high * mix2.high | hash2.low * mix2.low]
punpckldq %xmm3, %xmm0 # [e|0|e|0]
pxor %xmm4, %xmm4
paddd %xmm0, %xmm2 # [d+e|c|b+e|a]
punpckhdq %xmm3, %xmm4 # [g|0|g|0]
paddd %xmm4, %xmm2 # [d+e+g|c|b+e+g|a] = [garbage | lower 64-bits of hash2 * mix2]
paddq %xmm5, %xmm2 # hash2 = (hash2 * mix2) + upper_64bits(hash1 * mix1)
pxor %xmm2, %xmm1 # hash1 = hash2 ^ lower_64bits(hash1 * mix1)

# Iteration #1

pshufd $0b10110001, %xmm6, %xmm3
punpckldq %xmm1, %xmm1
pmuludq %xmm1, %xmm3 # [H|G|F|E] = [hash1.high * mix1.high | hash1.low * mix1.high]
punpckldq %xmm2, %xmm2
pmuludq %xmm6, %xmm1 # [D|C|B|A] = [hash1.high * mix1.low | hash1.low * mix1.low]
movd %xmm3, %ecx
pshufd $0b11100001, %xmm1, %xmm1
pshufd $0b11100001, %xmm3, %xmm3
movd %xmm1, %edx
movd %xmm3, %esi
pshufd $0b11010010, %xmm1, %xmm1
pshufd $0b01110010, %xmm3, %xmm3
movd %xmm1, %eax
xor %edi, %edi
pshufd $0b00100111, %xmm1, %xmm1
add %eax, %edx # X = B + C
movd %xmm1, %eax
adc $0, %eax # Y = D + carry
adc $0, %edi # Z = carry
add %ecx, %edx # X = X + E
punpckhdq %xmm1, %xmm1 # [0|0|0|A]
movd %edx, %xmm0 # [0|0|0|X]
adc %esi, %eax # Y = Y + F + carry
movd %xmm3, %edx
punpckhdq %xmm3, %xmm3
adc $0, %edi # Z = Z + carry
movd %xmm3, %esi
add %edx, %eax # Y = Y + G
pshufd $0b10101111, %xmm7, %xmm3
adc %esi, %edi # Z = Z + H + carry
movd %eax, %xmm5 # [0|0|0|Y]
movd %edi, %xmm4 # [0|0|0|Z]
punpckldq %xmm0, %xmm1 # [0|0|X|A] = [0 | lower 64-bits of hash1 * mix1]
punpckldq %xmm4, %xmm5 # [0|0|Z|Y] = [0 | upper 64-bits of hash1 * mix1]
pmuludq %xmm2, %xmm3 # [h|g|f|e] = [hash2.high * mix2.low | hash2.low * mix2.high]
pxor %xmm0, %xmm0
pmuludq %xmm7, %xmm2 # [d|c|b|a] = [hash2.high * mix2.high | hash2.low * mix2.low]
punpckldq %xmm3, %xmm0 # [e|0|e|0]
pxor %xmm4, %xmm4
paddd %xmm0, %xmm2 # [d+e|c|b+e|a]
punpckhdq %xmm3, %xmm4 # [g|0|g|0]
paddd %xmm4, %xmm2 # [d+e+g|c|b+e+g|a] = [garbage | lower 64-bits of hash2 * mix2]
paddq %xmm5, %xmm2 # hash2 = (hash2 * mix2) + upper_64bits(hash1 * mix1)
pxor %xmm2, %xmm1 # hash1 = hash2 ^ lower_64bits(hash1 * mix1)

# Iteration #2

pshufd $0b10110001, %xmm6, %xmm3
punpckldq %xmm1, %xmm1
pmuludq %xmm1, %xmm3 # [H|G|F|E] = [hash1.high * mix1.high | hash1.low * mix1.high]
punpckldq %xmm2, %xmm2
pmuludq %xmm6, %xmm1 # [D|C|B|A] = [hash1.high * mix1.low | hash1.low * mix1.low]
movd %xmm3, %ecx
pshufd $0b11100001, %xmm1, %xmm1
pshufd $0b11100001, %xmm3, %xmm3
movd %xmm1, %edx
movd %xmm3, %esi
pshufd $0b11010010, %xmm1, %xmm1
pshufd $0b01110010, %xmm3, %xmm3
movd %xmm1, %eax
xor %edi, %edi
pshufd $0b00100111, %xmm1, %xmm1
add %eax, %edx # X = B + C
movd %xmm1, %eax
adc $0, %eax # Y = D + carry
adc $0, %edi # Z = carry
add %ecx, %edx # X = X + E
punpckhdq %xmm1, %xmm1 # [0|0|0|A]
movd %edx, %xmm0 # [0|0|0|X]
adc %esi, %eax # Y = Y + F + carry
movd %xmm3, %edx
punpckhdq %xmm3, %xmm3
adc $0, %edi # Z = Z + carry
movd %xmm3, %esi
add %edx, %eax # Y = Y + G
pshufd $0b10101111, %xmm7, %xmm3
adc %esi, %edi # Z = Z + H + carry
movd %eax, %xmm5 # [0|0|0|Y]
movd %edi, %xmm4 # [0|0|0|Z]
punpckldq %xmm0, %xmm1 # [0|0|X|A] = [0 | lower 64-bits of hash1 * mix1]
punpckldq %xmm4, %xmm5 # [0|0|Z|Y] = [0 | upper 64-bits of hash1 * mix1]
pmuludq %xmm2, %xmm3 # [h|g|f|e] = [hash2.high * mix2.low | hash2.low * mix2.high]
pxor %xmm0, %xmm0
pmuludq %xmm7, %xmm2 # [d|c|b|a] = [hash2.high * mix2.high | hash2.low * mix2.low]
punpckldq %xmm3, %xmm0 # [e|0|e|0]
pxor %xmm4, %xmm4
paddd %xmm0, %xmm2 # [d+e|c|b+e|a]
punpckhdq %xmm3, %xmm4 # [g|0|g|0]
paddd %xmm4, %xmm2 # [d+e+g|c|b+e+g|a] = [garbage | lower 64-bits of hash2 * mix2]
paddq %xmm5, %xmm2 # hash2 = (hash2 * mix2) + upper_64bits(hash1 * mix1)
pxor %xmm2, %xmm1 # hash1 = hash2 ^ lower_64bits(hash1 * mix1)

# Place 64-bit result in %edx:%eax and return

popl %esi
movd %xmm1, %eax
pshufd $0b11100001, %xmm1, %xmm1
popl %edi
movd %xmm1, %edx
ret

# Unaligned main-loop, process 32-byte unaligned chunks at a time

.align 16, 0x90
5: movdqu (%ecx), %xmm0
add $32, %ecx
paddq %xmm0, %xmm1
movdqu -16(%ecx), %xmm0
pmullw %xmm3, %xmm1
paddq %xmm0, %xmm2
pmullw %xmm3, %xmm2
movdqa %xmm1, %xmm0
punpckhbw %xmm2, %xmm1
punpcklbw %xmm0, %xmm2
dec %eax
jne 5b
pxor %xmm2, %xmm1
jmp 2b

.size memhash, .-memhash


Also, check em.

Name: Anonymous 2014-08-09 4:05

id0/v0, 1/1, 2/1, 3/2, 4/3, 5/5, 6/8, 7/13, 8/21, 9/34
2*2 + 3*3 = 13
3+4 = 7
2n+1

Name: Anonymous 2014-08-09 4:13

fibs(2n) = fibs(2n+1) - fibs(2(n-1)+1)

The Ultimate Fibs!!! =D

Name: Anonymous 2014-08-09 4:31

/* 2 bit adder in C
if any of the input parameters is bigger than 2 bits, the behavior is undefined
if the result of addition is more than 2 bits, the behavior is undefined.
int add(int a, int b) {
return a + b;
}

Name: Anonymous 2014-08-09 7:54

>>69
*/
Nice code.

Name: Anonymous 2014-08-09 9:00

>>66
uint64_t memhash(void const* key, size_t n, uint64_t seed);
Did you mean void *const key/const void *const key? Or do you need to modify the pointed data of key?

Name: Anonymous 2014-08-12 1:43

>>71
No, I meant void const*. I'm just being idiomatic in how const modifies what precedes it (unless nothing precedes it). I read it right to left. A lot of Boost code and other third party C++ libraries are written like this.

const int* const makes my autism flare up, I much prefer int const* const. Reading right from right to left, that's constant pointer to a constant integer type.

Name: Anonymous 2014-08-12 14:41

>>71
Don't tell me you actually read that garbage.

Name: Anonymous 2014-08-12 18:53

Why is there no Io code in this thread? Io-fag, where art thou?

Name: Anonymous 2014-08-14 18:07

Delimited continuations rule. Here's a top-tier demonstration of throwing away a continuation and producing a value of a totally different (to what the cont was expecting type):

#lang racket
(require racket/control)

(print
(string-join (list "Delimit"
(reset
(+ 10 (shift k "my anus"))))))

Name: Anonymous 2014-08-14 19:52

>>75
a totally different (to what the cont was expecting type):
Fix:
a totally different (to what the cont was expecting) type:
Can't trust a lisper misplacing his parenthesis.

Name: Anonymous 2014-08-15 1:29

#lang racket
(require racket/control)

(print
(string-join (list "Delimit"
(reset
(+ 10 (shift k "my anus"))))))

Name: Anonymous 2014-08-15 1:34

#include <ncurses.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef CONNECT4_H
#define CONNECT4_H
typedef struct {
char name[30];
int score;
}Player;
/* External Variables*/
extern FILE *f, *saveFile;
extern Player p[2];
extern char menuList[3][20], players[2][30], saveFileName[15];
extern int maxx, maxy, boardState[8][9], colorChoice[3],
winningPositions[2][7], curPointsPlayer[2], turn, colsFull,
popOutActive, difTime;
extern WINDOW *board, *prompt, *title;
extern time_t start_time;
/* Menu functions */
void ErrorMessage(char *s);
void Initialize();
int InitializeMenu();
void DrawMenu(int choice);
void PlayerSelect();
void DrawPickColor(int y, int colorChoice);
int Pause();
void SaveGame();
void Load();
void DrawPrompt(char *s);
void PopOutSelection();
void DrawTitle(int y);
/* Gameplay functions */
void DrawBoardLayout();
void DrawBoard();
void PrintTime();
void PrintScore();
void Play();
void PreviewPiece(int row, int colChosen, int color);
int GetAvailableRow(int col);
void AnimatePiece(int turn, int colChosen);
int CheckEndOfGameFromPosition(int row, int col);
void InitializeWinningPositions();
void BlinkWinningPositions();
void ResetBoard();
void GameIsDraw();
void PopOut(int colChosen);
void GameOver();
void PopOutSelection();
/* Score database functions */
void AddPlayer(Player p);
int SearchPlayer(Player p);
int GetPlayerScore(Player p);
void UpdatePlayer(Player p);
void PrintDatabase();
void Quit();
#endif

//game.c

#include "connect4.h"

void DrawBoardLayout() {
clear();

int c;
int x, y, boardmaxx = 44, boardmaxy = 19;
board = newwin(boardmaxy, boardmaxx, 4, 3);
wattron(board, COLOR_PAIR(3));

for(x = 0; x < boardmaxx; x++) {
mvwaddch(board, 0, x, '*');
mvwaddch(board, boardmaxy - 1, x, '*');
}

for(y = 0; y < boardmaxy; y++) {
mvwaddstr(board, y, 0, "**");
mvwaddstr(board, y, boardmaxx - 2, "**");
}

for(y = 1; y <= boardmaxy - 2; y++)
for(x = 0; x < boardmaxx; x += 6)
mvwaddstr(board, y, x, "**");

for(x = 1; x <= boardmaxx - 2; x++)
for(y = 0; y < boardmaxy; y += 3)
mvwaddch(board, y, x, '*');

refresh();
wrefresh(board);
}

void DrawBoard() {
int i, j, x, y;
for(i = 1; i <= 6; i++) {
y = 1 + 3 * (i - 1);
for(j = 1; j <= 7; j++) {
x = 2 + 6 * (j - 1);
if(boardState[i][j] != 0) {
switch(boardState[i][j]) {
case 1:
wattrset(board, COLOR_PAIR(colorChoice[1]));
break;
case 2:
wattrset(board, COLOR_PAIR(colorChoice[2]));
break;
case 3:
wattrset(board, COLOR_PAIR(8));
break;
}
mvwaddstr(board, y, x, "****");
mvwaddstr(board, y + 1, x, "****");
wattrset(board, A_NORMAL);
}
else {
wattrset(board, COLOR_PAIR(1));
mvwaddstr(board, y, x, " ");
mvwaddstr(board, y + 1, x, " ");
}
}
}
refresh();
wrefresh(board);
}

void Play() {
int c, availableRow, colChosen = 0, color = colorChoice[1];
turn = 1;
nodelay(stdscr, TRUE);
while(1) {
c = getch();
PrintTime();
PrintScore();
if(c == 'q') {
int ch;
DrawPrompt("REALLY QUIT?\n YES(y)/NO(n)");
do {
ch = getch();
}while(ch != 'y' && ch != 'n');
if(ch == 'y') {
UpdatePlayer(p[0]);
UpdatePlayer(p[1]);
Quit();
break;
}
if(ch == 'n') {
DrawBoardLayout();
DrawBoard();
}
}
if(c == 'o' && popOutActive == 1 && boardState[6][colChosen + 1] == turn) {
if(GetAvailableRow(colChosen + 1) == 0) {
colsFull--;
}
PopOut(colChosen);
DrawBoard();
turn = 3 - turn;
color = colorChoice[turn];
}
if(c == 'p') {
int diff = Pause();
start_time += diff;
}
if(c == 's') {
time_t t = time(NULL);
difTime = t - start_time;
SaveGame();
}
if(c == ' ' || c == 10) {
availableRow = GetAvailableRow(colChosen + 1);
if(availableRow > 0) {
AnimatePiece(turn, colChosen);
boardState[availableRow][colChosen + 1] = turn;
DrawBoard(boardState);
if(CheckEndOfGameFromPosition(availableRow, colChosen + 1)) {
GameOver();
}
turn = 3 - turn;
color = colorChoice[turn];
if(availableRow == 1) {
colsFull++;
if(colsFull == 7) {
colsFull = 0;
GameIsDraw();
}
}
}
}
PreviewPiece(2, colChosen, color);
if(c == KEY_LEFT || c == 'a') {
colChosen = (colChosen + 6) % 7;
PreviewPiece(2, colChosen, color);
}
if(c == KEY_RIGHT || c == 'd') {
colChosen = (colChosen + 1) % 7;
PreviewPiece(2, colChosen, color);
}
}
}
int CheckEndOfGameFromPosition(int row, int col) {
int ok = 0, count = 0, i = row, j = col;
InitializeWinningPositions();
/* check vertical */
while(boardState[i][j] == boardState[row][col] && i <= 6) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
i++;
}
if(count >= 4) {
return 1;
}
/* check horizontal */
count = 0; i = row; j = col;
InitializeWinningPositions();
while(boardState[i][j] == boardState[row][col] && j >= 1) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j--;
}
j = col + 1;
while(boardState[i][j] == boardState[row][col] && j <= 7) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j++;
}
if(count >= 4) {
return 1;
}
/* check first diagonal */
count = 0; i = row; j = col;
InitializeWinningPositions();
while(boardState[i][j] == boardState[row][col] && j <=7 && i >= 1) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j++;
i--;
}
i = row + 1;
j = col - 1;
while(boardState[i][j] == boardState[row][col] && j >=1 && i <= 6) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j--;
i++;
}
if(count >= 4) {
return 1;
}
/* check second diagonal */
count = 0; i = row; j = col;
InitializeWinningPositions();
while(boardState[i][j] == boardState[row][col] && j >=1 && i >= 1) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j--;
i--;
}
i = row + 1;
j = col + 1;
while(boardState[i][j] == boardState[row][col] && j <= 7 && i <= 6) {
count++;
winningPositions[0][count - 1] = i;
winningPositions[1][count - 1] = j;
j++;
i++;
}
if(count >= 4) {
return 1;
}
return 0;
}
void InitializeWinningPositions() {
int i, j;
for(i = 0; i < 2; i++)
for(j = 0; j < 7; j++)
winningPositions[i][j] = 0;
}
void BlinkWinningPositions() {
int i, blinked = 0, prevValue;
while(blinked < 5) {
i = 0;
while(i < 7 && winningPositions[0][i] != 0) {
prevValue = boardState[winningPositions[0][i]][winningPositions[1][i]];
boardState[winningPositions[0][i]][winningPositions[1][i]] = 3;
i++;
}
DrawBoard(boardState);
napms(150);
i = 0;
while(i < 7 && winningPositions[0][i] != 0) {
boardState[winningPositions[0][i]][winningPositions[1][i]] = prevValue;
i++;
}
DrawBoard(boardState);
napms(120);
blinked++;
}
}
void AnimatePiece(int turn, int colChosen) {
int i = 1, availableRow = GetAvailableRow(colChosen + 1);
while(i < availableRow) {
boardState[i][colChosen + 1] = turn;
DrawBoard(boardState);
refresh();
wrefresh(board);
napms(120);
boardState[i][colChosen + 1] = 0;
DrawBoard(boardState);
refresh();
i++;
}
}

void PreviewPiece(int row, int colChosen, int color) {
int i;
for(i = 0; i < 7; i++) {
if(i == colChosen) {
attron(COLOR_PAIR(color));
mvprintw(row, 5 + 6 * i, "****");
mvprintw(row + 1, 5 + 6 * i, "****");
attroff(COLOR_PAIR(color));
}
else {
mvprintw(row, 5 + 6 * i, " ");
mvprintw(row + 1, 5 + 6 * i, " ");
}
refresh();
}
}

int GetAvailableRow(int col) {
int i = 0;
while(boardState[i + 1][col] == 0 && i <= 5)
i++;
return i;
}
/* Prints current time and time spent since the beginning of the game */
void PrintTime() {
struct tm *cur_time;
time_t t, dif;
t = time(NULL);
int hours, minutes, seconds;
cur_time = localtime(&t);
mvprintw(2, 50, "Local Time:");
mvprintw(3, 50, "%02d:%02d:%02d", cur_time -> tm_hour,
cur_time -> tm_min, cur_time -> tm_sec);
dif = t - start_time;
seconds = dif % 60;
dif= dif / 60;
minutes = dif% 60;
hours = dif / 60;
mvprintw(15, 50, "In-game time:");
mvprintw(16, 50, "%02d:%02d:%02d", hours, minutes, seconds);
}
void PrintScore() {
switch(turn) {
case 1:
mvprintw(5, 51 + strlen(p[0].name) +
strlen(" vs ") + strlen(p[1].name), " ");
attron(COLOR_PAIR(colorChoice[1]));
mvprintw(5, 48, "*");
attroff(COLOR_PAIR(colorChoice[1]));
break;
case 2:
mvprintw(5, 48, " ");
attron(COLOR_PAIR(colorChoice[2]));
mvprintw(5, 51 + strlen(p[0].name) +
strlen(" vs ") + strlen(p[1].name), "*");
attroff(COLOR_PAIR(colorChoice[2]));
break;
}
attron(A_BOLD);
mvprintw(5, 50, "%s VS %s", p[0].name, p[1].name);
attroff(A_BOLD);
/* print current score */
mvprintw(7, 50, "Score for the current session:");
mvprintw(8, 50, "%s: %d", p[0].name, curPointsPlayer[0]);
mvprintw(9, 50, "%s: %d", p[1].name, curPointsPlayer[1]);
/* print total score for each player */
mvprintw(11, 50, "Lifetime Player Score:");
mvprintw(12, 50, "%s: %d", p[0].name, p[0].score);
mvprintw(13, 50, "%s: %d", p[1].name, p[1].score);
if(popOutActive == 1) {
mvprintw(18, 50, "POPOUT: O");
}
else {
mvprintw(18, 50, "Default Key bindings:");
}
mvprintw(19, 50, "LEFT: A | LEFT: <-");
mvprintw(20, 50, "RIGHT: D | RIGHT: ->");
mvprintw(21, 50, "_____________________________");
mvprintw(22, 50, "ACTION: SPACE | ACTION: ENTER");
mvprintw(23, 50, "SAVE:S | QUIT:Q | PAUSE:P");
}
/* Put zeroes in the boardState matrix */
void ResetBoard() {
int i, j;
for(i = 0; i < 8; i++)
for(j = 0; j < 9; j++)
boardState[i][j] = 0;
}
void GameIsDraw() {
char *msg = "DRAW!\n PLAY AGAIN?\n YES(y) / NO(n)";
int ch;
DrawPrompt(msg);
do {
ch = getch();
}while(ch != 'y' && ch != 'n');
if(ch == 'n') {
UpdatePlayer(p[0]);
UpdatePlayer(p[1]);
Quit();
endwin();
exit(0);
}
if(ch == 'y') {
ResetBoard();
DrawBoardLayout();
DrawBoard();
}
}
void PopOut(int colChosen) {
int i, winningCombinations[2] = {0};
for(i = 6; i >= 1; i--) {
if(boardState[i][colChosen + 1] != 0) {
boardState[i][colChosen + 1] = 0;
DrawBoard();
napms(180);
boardState[i][colChosen + 1] = boardState[i - 1][colChosen + 1];
}
}
for(i = 6; i >= 1; i--) {
if(boardState[i][colChosen + 1] != 0) {
if(CheckEndOfGameFromPosition(i, colChosen + 1)) {
BlinkWinningPositions();
winningCombinations[boardState[i][colChosen + 1] - 1]++;
}
}
}
if(winningCombinations[0] > 0 && winningCombinations[1] > 0) {
GameIsDraw();
}
else
for(i = 0; i < 2; i++) {
if(winningCombinations[i] > 0) {
char msg[100];
int ch;
colsFull = 0;
sprintf(msg, "%s WINS!\n PLAY AGAIN?\n YES(y)/NO(n)",
p[i].name);
curPointsPlayer[i]++;
p[i].score++;
PrintScore();
DrawPrompt(msg);
while((ch = getch()) != 'y' && ch != 'n');
if(ch == 'n') {
UpdatePlayer(p[0]);
UpdatePlayer(p[1]);
Quit();
endwin();
exit(0);
}
if(ch == 'y') {
ResetBoard();
DrawBoardLayout();
DrawBoard();
}
}
}
}
/* Update variables and print message when the game is over */
void GameOver() {
char msg[100];
int ch;
colsFull = 0;
sprintf(msg, "%s WINS!\n PLAY AGAIN OR EXIT?\n YES(y)/NO(n)",
p[turn - 1].name);
curPointsPlayer[turn - 1]++;
p[turn - 1].score++;
PrintScore();
BlinkWinningPositions();
DrawPrompt(msg);
while((ch = getch()) != 'y' && ch != 'n');
if(ch == 'n') {
UpdatePlayer(p[0]);
UpdatePlayer(p[1]);
Quit();
endwin();
exit(0);
}
if(ch == 'y') {
ResetBoard();
DrawBoardLayout();
DrawBoard();
}
}

Name: Anonymous 2014-08-15 1:49

>>78
I wanted to write a connect 4 after I read about your implementation here on /prog/. Now I see that you post it :) Nice. I will hopefully read your code and discover bugs, if any. Thanks.

Name: Anonymous 2014-08-15 16:50

//menu
#include "connect4.h"

void ErrorMessage(char *s) {
addstr(s);
refresh();
getch();
endwin();
exit(1);
}

void Initialize() {
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
start_color();
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_MAGENTA, COLOR_MAGENTA);
init_pair(5, COLOR_RED, COLOR_RED);
init_pair(6, COLOR_GREEN, COLOR_GREEN);
init_pair(7, COLOR_BLUE, COLOR_BLUE);
init_pair(8, COLOR_WHITE, COLOR_WHITE);
init_pair(9, COLOR_CYAN, COLOR_CYAN);
}

int InitializeMenu() {
int c, i = 0;
int choice = 0;
char *s = "PRESS ENTER/SPACE TO SELECT OPTION";
nodelay(stdscr, TRUE);
DrawMenu(choice);
DrawTitle(0);
while(1) {
refresh();
wrefresh(title);

c = getch();
if(c == 10 || c == ' ')
break;
if(c == KEY_DOWN) {
choice = (choice + 1) % 3;
DrawMenu(choice);
}
if(c == KEY_UP) {
choice = (choice + 2) % 3;
DrawMenu(choice);
}

if(i < strlen(s)) {
mvaddstr(maxy - 1, maxx - 1 - i, s);
napms(60);
i++;
}
refresh();
}
return choice;
}

void DrawMenu(int choice) {
int i;
for(i = 0; i < 3; i++) {
move(maxy / 2 + 2 * (i - 1), (maxx - strlen(menuList[1])) / 2 );
if(i == choice) {
attron(A_REVERSE);
printw("%s", menuList[i]);
attroff(A_REVERSE);
}
else
printw("%s", menuList[i]);
}
}

/* Select name and color for both players */
void PlayerSelect() {
char *msg1 = "CHOOSE COLOR, ";
int c, i;
nodelay(stdscr, FALSE);
clear();
echo();
mvprintw(maxy / 4, maxx / 6, "ENTER P1 NAME: ");
refresh();
getnstr(p[0].name, 10);
mvprintw(maxy / 4 + 2, maxx / 6, "ENTER P2 NAME: ");
getnstr(p[1].name, 10);

/* Check if player is in database */
for(i = 0; i <= 1; i++) {
if(SearchPlayer(p[i]))
p[i].score = GetPlayerScore(p[i]);
else {
p[i].score = 0;
AddPlayer(p[i]);
}
}
clear();
noecho();

/* Print Color Choice Menu for Player 1 */
mvprintw(1, (maxx - strlen(msg1) - strlen(p[0].name)) / 2,
"%s%s", msg1, p[0].name);
DrawPickColor(3, colorChoice[1]);
while(1) {
c = getch();
if(c == ' ' || c == 10)
break;
if(c == KEY_LEFT) {
colorChoice[1] = (colorChoice[1] + 2 ) % 3;
DrawPickColor(3, colorChoice[1]);
}
if(c == KEY_RIGHT) {
colorChoice[1] = (colorChoice[1] + 1) % 3;
DrawPickColor(3, colorChoice[1]);
}
refresh();
}

/* Print Color Choice Menu for Player 2 */
mvprintw(6, (maxx - strlen(msg1) - strlen(p[1].name)) / 2,
"%s%s", msg1, p[1].name);
DrawPickColor(8, colorChoice[2]);
while(1) {
c = getch();
if(c == ' ' || c == 10) {
if(colorChoice[2] == colorChoice[1]) {
char msg[100];
sprintf(msg, "%s are you sure you want \
to play with the same color as %s?", p[1].name, p[0].name);
mvprintw(14, (maxx - strlen(msg)) / 2, "%s", msg);
mvprintw(15, (maxx - strlen("YES(y) / NO(n)")) / 2, "YES(y) / NO(n)");
int ch;
do {
ch = getch();
}while(ch != 'y' && ch != 'n');

if(ch == 'y')
break;
else {
DrawPickColor(8, colorChoice[2]);
mvprintw(14, 0, " \
");
mvprintw(15, (maxx - strlen("YES(y) / NO(n)")) / 2, " ");
}
}
else
break;
}

if(c == KEY_LEFT) {
colorChoice[2] = (colorChoice[2] + 2 ) % 3;
DrawPickColor(8, colorChoice[2]);
}
if(c == KEY_RIGHT) {
colorChoice[2] = (colorChoice[2] + 1) % 3;
DrawPickColor(8, colorChoice[2]);
}
refresh();
}

/* Increase colorChoice so that would match the COLOR_PAIR */
colorChoice[1] += 5;
colorChoice[2] += 5;
}

void DrawPickColor(int y, int colorChoice) {
int i;
switch(colorChoice) {
case 0:
mvaddch(y, 6, '*');
mvaddch(y, maxx / 2 - 2, ' ');
mvaddch(y, maxx - 13, ' ');
break;
case 1:
mvaddch(y, 6, ' ');
mvaddch(y, maxx / 2 - 2, '*');
mvaddch(y, maxx - 13, ' ');
break;
case 2:
mvaddch(y, 6, ' ');
mvaddch(y, maxx / 2 - 2, ' ');
mvaddch(y, maxx - 13, '*');
break;
}
attrset(COLOR_PAIR(1));
mvprintw(y, 7, "RED");
attrset(COLOR_PAIR(2));
mvprintw(y, maxx / 2 - 1, "GREEN");
attrset(COLOR_PAIR(3));
mvprintw(y, maxx - 12, "BLUE");
attrset(A_NORMAL);
}


void Quit() {
clear();
char *msg = "EXIT";
mvaddstr(maxy / 2, (maxx - strlen(msg)) / 2, msg);
DrawTitle(0);
refresh();
wrefresh(title);
napms(1500);
}

int Pause() {
int c;
time_t start_pause = time(NULL), end_pause;
char *msg = "GAME PAUSED ---> PRESS P TO RESUME",
*msg2 = " ";
mvprintw(0, (maxx - strlen(msg)) / 2, "%s", msg);
while(1) {
c = getch();
if(c == 'p') {
end_pause = time(NULL);
mvprintw(0, (maxx - strlen(msg2)) / 2, "%s", msg2);
break;
}
}
int diff = end_pause - start_pause;
return diff;
}

void SaveGame() {
clear();
nodelay(stdscr, FALSE);
echo();
mvprintw(4, 4, "Insert the name for save file: ");

DrawTitle(14);

getnstr(saveFileName, 10);
saveFile = fopen(saveFileName, "ab");
if(saveFile == NULL)
ErrorMessage("Error at opening save file!");
fwrite(p, sizeof(Player), 2, saveFile);
fwrite(curPointsPlayer, sizeof(curPointsPlayer[1]), 2, saveFile);
fwrite(boardState, sizeof(boardState), 1, saveFile);
fwrite(colorChoice, sizeof(colorChoice), 1, saveFile);
fwrite(&colsFull, sizeof(colsFull), 1, saveFile);
fwrite(&difTime, sizeof(int), 1, saveFile);
fwrite(&popOutActive, sizeof(int), 1, saveFile);
noecho();
nodelay(stdscr, TRUE);
DrawBoardLayout();
DrawBoard();
fclose(saveFile);
}

void Load() {
clear();
nodelay(stdscr, FALSE);
echo();
mvprintw(4, 4, "Insert the name for save file: ");
getnstr(saveFileName, 10);
noecho();
saveFile = fopen(saveFileName, "rb");
if(saveFile == NULL)
ErrorMessage("Error at opening save file!");

fread(&p[0], sizeof(Player), 1, saveFile);
fread(&p[1], sizeof(Player), 1, saveFile);
fread(&curPointsPlayer[0], sizeof(curPointsPlayer[0]), 1, saveFile);
fread(&curPointsPlayer[1], sizeof(curPointsPlayer[1]), 1, saveFile);
fread(boardState, sizeof(boardState), 1, saveFile);
fread(colorChoice, sizeof(colorChoice), 1, saveFile);
fread(&colsFull, sizeof(colsFull), 1, saveFile);
fread(&difTime, sizeof(int), 1, saveFile);
fread(&popOutActive, sizeof(int), 1, saveFile);

init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_MAGENTA, COLOR_MAGENTA);
init_pair(5, COLOR_RED, COLOR_RED);
init_pair(6, COLOR_GREEN, COLOR_GREEN);
init_pair(7, COLOR_BLUE, COLOR_BLUE);
init_pair(8, COLOR_WHITE, COLOR_WHITE);
fclose(saveFile);
start_time = time(NULL);
start_time = start_time - difTime;
DrawBoardLayout();
DrawBoard();
Play();
}

void DrawPrompt(char *s) {
int x, y;
prompt = newwin(5, 40, 5, 5);
getmaxyx(prompt, y, x);
mvwprintw(prompt, 1, 1, "%s", s);
refresh();
touchwin(prompt);
wrefresh(prompt);
getch();
}

void PopOutSelection() {
clear();
mvprintw(1, (maxx - strlen("Choose a gamestyle")) / 2, "Choose a gamestyle");
int c;
char options[2][30] = {"Normal", "Pop Out"};
nodelay(stdscr, FALSE);
attron(A_REVERSE);
mvprintw(5, (maxx - strlen(options[1])) / 2, options[0]);
attroff(A_REVERSE);
mvprintw(7, (maxx - strlen(options[1])) / 2, options[1]);

DrawTitle(11);

while(1) {
refresh();
wrefresh(title);
c = getch();
if(c == ' ' || c == 10) {
break;
}

if(c == KEY_DOWN || c == KEY_UP) {
popOutActive = (popOutActive + 1) % 2;
if(popOutActive == 0) {
attron(A_REVERSE);
mvprintw(5, (maxx - strlen(options[1])) / 2, options[0]);
attroff(A_REVERSE);
mvprintw(7, (maxx - strlen(options[1])) / 2, options[1]);
}
else {
mvprintw(5, (maxx - strlen(options[1])) / 2, options[0]);
attron(A_REVERSE);
mvprintw(7, (maxx - strlen(options[1])) / 2, options[1]);
attroff(A_REVERSE);
}
}
}
}

void DrawTitle(int y) {
title = newwin(7, 79, y, 0);
wattron(title, COLOR_PAIR(3));
int i;
for(i = 0; i < 5; i++) {
refresh();
wclear(title);
/* First Row */
mvwprintw(title, i - 4, 1, "********");
mvwprintw(title, i - 4, 11, "********");
mvwprintw(title, i - 4, 21, "********");
mvwprintw(title, i - 4, 31, "********");
mvwprintw(title, i - 4, 41, "********");
mvwprintw(title, i - 4, 51, "********");
mvwprintw(title, i - 4, 61, "********");
mvwprintw(title, i - 4, 71, "*");
mvwprintw(title, i - 4, 78, "*");

/* Second Row */
/* C */
mvwprintw(title, i - 3, 1, "*");
/* O */
mvwprintw(title, i - 3, 11, "*");
mvwprintw(title, i - 3, 18, "*");
/* N */
mvwprintw(title, i - 3, 21, "*");
mvwprintw(title, i - 3, 28, "*");
/* N */
mvwprintw(title, i - 3, 31, "*");
mvwprintw(title, i - 3, 38, "*");
/* E */
mvwprintw(title, i - 3, 41, "*");
/* C */
mvwprintw(title, i - 3, 51, "*");
/* T */
mvwprintw(title, i - 3, 65, "*");
/* 4 */
mvwprintw(title, i - 3, 71, "*");
mvwprintw(title, i - 3, 78, "*");

/* Third Row */
/* C */
mvwprintw(title, i - 2, 1, "*");
/* O */
mvwprintw(title, i - 2, 11, "*");
mvwprintw(title, i - 2, 18, "*");
/* N */
mvwprintw(title, i - 2, 21, "*");
mvwprintw(title, i - 2, 28, "*");
/* N */
mvwprintw(title, i - 2, 31, "*");
mvwprintw(title, i - 2, 38, "*");
/* E */
mvwprintw(title, i - 2, 41, "********");
/* C */
mvwprintw(title, i - 2, 51, "*");
/* T */
mvwprintw(title, i - 2, 65, "*");
/* 4 */
mvwprintw(title, i - 2, 71, "********");

/* Fourth Row */
/* C */
mvwprintw(title, i - 1, 1, "*");
/* O */
mvwprintw(title, i - 1, 11, "*");
mvwprintw(title, i - 1, 18, "*");
/* N */
mvwprintw(title, i - 1, 21, "*");
mvwprintw(title, i - 1, 28, "*");
/* N */
mvwprintw(title, i - 1, 31, "*");
mvwprintw(title, i - 1, 38, "*");
/* E */
mvwprintw(title, i - 1, 41, "*");
/* C */
mvwprintw(title, i - 1, 51, "*");
/* T */
mvwprintw(title, i - 1, 65, "*");
/* 4 */
mvwprintw(title, i - 1, 78, "*");

/* Fifth Row */
/* C */
mvwprintw(title, i, 1, "********");
/* O */
mvwprintw(title, i, 11, "********");
/* N */
mvwprintw(title, i, 21, "*");
mvwprintw(title, i, 28, "*");
/* N */
mvwprintw(title, i, 31, "*");
mvwprintw(title, i, 38, "*");
/* E */
mvwprintw(title, i, 41, "********");
/* C */
mvwprintw(title, i, 51, "********");
/* T */
mvwprintw(title, i, 65, "*");
/* 4 */
mvwprintw(title, i, 78, "*");
napms(150);
refresh();
wrefresh(title);
}

wattroff(title, COLOR_PAIR(10));
}

Name: Anonymous 2014-08-15 17:02

>>78
Why ncurses? Why not just curses?

Name: Anonymous 2014-08-15 17:25

Self-hosting Symta compiler...

use prelude compiler reader macro

GRootFolder = Void
GSrcFolders = Void
GDstFolder = Void
GHeaderTimestamp = Void
GMacros = Void

read_normalized Text =
| Expr = read Text
| case Expr [`|` @As] Expr
X [`|` X]

skip_macros Xs = Xs.skip{X => X.1.is_macro}

// FIXME: do caching
get_lib_exports LibName =
| for Folder GSrcFolders
| LibFile = "[Folder][LibName].s"
| when file_exists LibFile
| Text = load_text LibFile
| Expr = read_normalized Text
| leave: case Expr.last [export @Xs] | skip_macros Xs
Else | Void
| bad "no [LibName].s"

c_runtime_compiler Dst Src =
| RtFolder = "[GRootFolder]runtime"
| unix "gcc -O1 -Wno-return-type -Wno-pointer-sign -I '[RtFolder]' -g -o '[Dst]' '[Src]'"

c_compiler Dst Src =
| RtFolder = "[GRootFolder]runtime"
| unix "gcc -O1 -Wno-return-type -Wno-pointer-sign -I '[RtFolder]' -g -fpic -shared -o '[Dst]' '[Src]'"

file_older Src Dst =
| DstDate = if file_exists Dst then file_time Dst else 0
| Src^file_time << DstDate and GHeaderTimestamp << DstDate

compile_runtime Src Dst =
| when file_older Src Dst: leave Void
| say "compiling runtime..."
| Result = c_runtime_compiler Dst Src
| when Result <> "": bad Result

add_imports Expr Deps =
| unless Deps.size: leave Expr
| [[_fn (map D Deps D.1) Expr]
@(map D Deps [_import [_quote D.0] [_quote D.1]])]

compile_expr Name Dst Expr =
| Uses = [core]
| Expr <= case Expr
[`|` [use @Us] @Xs]
| Uses <= [@Uses @Us]
| [`|` @Xs]
Else | Expr
| Deps = Uses.tail
| for D Deps: unless compile_module D: bad "cant compile [D].s"
| say "compiling [Name]..."
| Imports = (map U Uses: map E U^get_lib_exports: [U E]).join
| Imports = Imports.keep{X => X.1.is_text} // skip macros
| ExprWithDeps = add_imports Expr Imports
| ExpandedExpr = macroexpand ExprWithDeps GMacros
| CFile = "[Dst].c"
| ssa_produce_file CFile ExpandedExpr
| Result = c_compiler Dst CFile
| unless file_exists Dst: bad "[CFile]: [Result]"
| Deps

load_symta_file Filename =
| Text = load_text Filename
| read_normalized Text

compile_module Name =
| for Folder GSrcFolders
| SrcFile = "[Folder][Name].s"
| when file_exists SrcFile
| DstFile = "[GDstFolder][Name]"
| DepFile = "[DstFile].dep"
| when file_exists DepFile
| Deps = DepFile^load_symta_file.1
| CompiledDeps = map D Deps: compile_module D
| when file_older SrcFile DstFile and CompiledDeps.all{X => have X and file_older X DstFile}:
| leave DstFile
| Expr = load_symta_file SrcFile
| Deps = compile_expr Name DstFile Expr
| DepsText = Deps.infix{' '}.unchars
| save_text DepFile DepsText
| leave DstFile
| Void

build BuildFolder =
| let GMacros 'macro'^load_library.keep{X => X.1.is_macro}.as_table
GRootFolder '/Users/nikita/Documents/git/symta/'
GSrcFolders ["[BuildFolder]src/" "[GRootFolder]src/"]
GDstFolder "[BuildFolder]lib/"
GHeaderTimestamp (file_time "[GRootFolder]/runtime/runtime.c")
| RuntimeSrc = "[GRootFolder]/runtime/runtime.c"
| RuntimePath = "[BuildFolder]run"
| compile_runtime RuntimeSrc RuntimePath
| DstFile = compile_module main
| when no DstFile: bad "cant compile main.s"
| unix "[RuntimePath] '[GDstFolder]'"

export build

// /Users/nikita/Documents/git/symta/build/test/src/main.s
use build

// compile self second time
build "/Users/nikita/Documents/git/symta/build/test2/"

Name: od says 2014-08-15 18:36

not that any of you fucking nigger deserve it:

(
s.waitForBoot{

// stack of detuned sins
SynthDef(\bd, {
arg out = 0, amp= 1, pan = 0, attack = 0, rel= 0.1,
freq = 160, click = 0, depth = 3, detune = 10;
var env, layers, sig;

env = EnvGen.ar(Env.perc(0, rel, amp, -10), doneAction:2);

layers = [];
depth.do {|i|
layers = layers ++ SinOsc.ar(i * detune + freq, click, env);
};

Out.ar(out, Pan2.ar(Mix(layers), 0));
}).add;

// 3 detuned swooping sins
SynthDef(\bd2, {|amp= 1, rel= 0.1, freq = 160, click = 0|
var e= EnvGen.ar(Env.perc(0, rel, amp, -10), doneAction:2);
var layers = [
SinOsc.ar(Line.kr(freq - 10 * 2, freq - 10, rel), click, e*0.4),
SinOsc.ar(Line.kr(freq * 2, freq, rel), click, e*0.4),
SinOsc.ar(Line.kr(freq + 10 * 2, freq + 10, rel), click, e*0.4),
];
var z= Mix(layers);
Out.ar(0, Pan2.ar(z, 0));
}).add;

SynthDef(\bz, {|amp= 1, rel= 0.25, freq= 400|
var e= EnvGen.ar(Env.perc(0.01, rel, amp), doneAction:2);
var z= BPF.ar(Blip.ar(e+1*(freq*0.1), 3), freq*2, 0.1, amp*10*e);
Out.ar(0, Pan2.ar(z, 0));
}).add;

// 5k bpf whitenoise
SynthDef(\hh, {|amp= 1, rel= 0.05|
var e= EnvGen.ar(Env.perc(0, rel, amp, -10), doneAction:2);
var z= WhiteNoise.ar(e);
z= BPF.ar(z, 5000, 0.4);
Out.ar(0, Pan2.ar(z, 0, 1.5));
}).add;

SynthDef(\clap, {|out=0, amp=1, rel=0.2|
var e= EnvGen.ar(Env.perc(0.01, rel, amp), doneAction:2);
var sig=BPF.ar(PinkNoise.ar(e), Line.kr(300, 30, rel), 4);
Out.ar(out, Pan2.ar(sig, 0));
}).add;
};
)

(
t = TempoClock.default;
t.tempo = 135 / 60;
)

(
~bd.stop;
~bd = Pbind(
\instrument, \bd,
// \dur, Pseq(#[1, 1, 1, 1], inf),

// \dur, Pseq(#[1, 1, 1, 0.75, 0.25], inf),
// \click, Pseq(#[0, 0, 0.1, 0.1, 0.2], inf),

\dur, Pseq(#[1, 1, 0.75, 0.25, 0.5, 0.5], inf),
\amp, 0.6,
// \dur, Pseq(#[1, 1, 1, 0.5, 0.5], inf),
// \dur, Pseq(#[1, 1, 0.5, 0.5, 0.5, 0.5], inf),
).play(t, quant: 4);
)

(
~hh.stop;
~hh = Pbind(
\instrument, \hh,
\amp, Pseq(0.15 * [0, 1], inf).value,
\dur, 0.5,
).play(t, quant: 4);
)

(
~clap.stop;
~clap = Pbind(
\instrument, \clap,
\dur, 2,
\amp, 1,
\rel, Pseq([0.1, 0.1, 0.07, 0.15], inf),
).play(t, quant: [4, 1]);
)

(
~bd2.stop;
~bd2 = Pbind(
\instrument, \bd2,
\amp, 0.6,
).play(t, quant: [4, 0.48]);
)

(
~bz.stop;
~bz = Pbind(
\instrument, \bz,
\amp, Pseq([0, 0, 1, 0, 1], inf),
\dur, 0.5,
).play(t, quant: 4);
)

Name: od says 2014-08-15 18:37

(and that's SuperCollider if you had to ask)

ADMIN WHERE IS THE POSTFRES

Name: Anonymous 2014-08-15 23:26

>>83,84
Where's your meds?

Name: Anonymous 2014-08-16 0:56

>>81
What's wrong with ncurses?

Name: Anonymous 2014-08-16 1:06

>>84
that looks pretty interesting, thanks kat =)

Name: Anonymous 2014-08-16 7:13

>>84
Why the hell do you want a postgres server?

Name: Anonymous 2014-08-16 9:33

>>84

Lisp Music >>> SuperCollider >>>>>>>>>>> PoopyLoops

Name: Anonymous 2014-08-16 11:51

>>85
I'm not on any medication thank you very much. I'm what you could call "a functional lunatic". Sometimes yeah, I guess idgaf. I do though. I mean can you believe that this is what I do for fun?

>>88
I don't know why, I just know that we need a Postgres server. I don't deal in rationalisations.

A preliminary schema has been put on the SVN. It is not in a working condition right now (IIRC). Already though, I am unsatisfied with it.

We cannot impose "accounts" on people who want to use the system. The most we can really allow for is the notion of "sessions", which can be started anonymously. After a session has been established, additional capabilities can be loaded into it (or dropped) by proving that you posses a certain secret.

Therefor, the public interface of the schema needs to change. I guess it'll take a few iterations. If you want GOD tier code keep an eye on that or better yet help out. I feel like once we get the model down, we can start thinking about P2P distribution and world domination. Probably not on a postgres level though, we'll need to write something on top first so the masses can enjoy it.

Name: Anonymous 2014-08-16 12:33

Prominent organizations and products that use PostgreSQL as the primary database include:
International Space Station

=)

Name: Anonymous 2014-08-16 17:55

>>90
I'm not on any medication
Just whom are you kidding, American? You all are constantly on medication because the pharmaceutical industry controls your mind and turns you into pill-gulping drug addicts for life.

Name: Anonymous 2014-08-17 10:18

entry-level restricted boltzmann machine (missing the energy function)

%%data = [1,0,0,1; 1,0,1,0]

%%data = rand(8,4)

n = size(data, 1);

m = size(data, 2);

neurons = 50;

decay = 0.95;

lr = 0.2;

weights = [];

weights(1:m, 1:neurons) = 0;

weights = randn(size(weights)) ./ 100.0;

delta = zeros(size(weights));

pdata = [];

batchsize = 2000;

blocki = [1:batchsize];

for(iter=1:2000)

blocki = mod(blocki .+ batchsize, n) .+ 1;

shortdata = data(blocki, :);

insig1b = shortdata * weights;

sig1b = sigmoid(insig1b);

pos = shortdata' * sig1b;

insig2a = sig1b * weights';

sig2a = sigmoid(insig2a);

insig2b = sig2a * weights;

sig2b = sigmoid(insig2b);

%% neg = data' * sig2b; %%??

neg = sig2a' * sig2b;

delta = delta .* decay .+ ((pos .- neg) ./ n) .* lr;

weights = weights .+ delta;

pdata(iter) = sum(abs(shortdata(:) .- sig2a(:)) ./ (batchsize * m));

fprintf("%citer %i, err %i / 100 ", 13, iter, pdata(iter) * 100);

endfor;

hold on;

plot(pdata, '-b')

Name: Anonymous 2014-08-17 10:40

>>89
I love LISP, especially Kana. Too bad they only did one album.

Name: Anonymous 2014-08-17 10:52

>>93
oh and sampling too..

sig = @(z) 1.0 ./ (1.0 .+ e .^ -z);

Name: Anonymous 2014-08-18 13:35

I did this program that counts from 1 to 10

#include <stdio.h>

int main(void)
{
int i = 0;
do if(++i-2>2<<2) break;
while (printf("%d\n",i));
}

Name: Anonymous 2014-08-18 20:20

>>96
it looks like perl

Name: Anonymous 2014-08-21 16:02

>>96

2>2<<2
This looks like some kind of smilie >>2<<

Name: Anonymous 2014-08-21 17:05

>>97

likely some mathlab rip off

Name: Anonymous 2014-08-21 23:54

>>97
>>99
fuk u
that's some rock-solid straight C! Right there!

>>98
Thanks

Don't change these.
Name: Email:
Entire Thread Thread List