Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 40

16 JUEGOS PROGRAMADOS EN LENGUAJE C

1...........TETRIS....

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

const int M = 20;


const int N = 10;

int field[M][N] = {0};

struct Point
{int x,y;} a[4], b[4];

int figures[7][4] =
{
1,3,5,7, // I
2,4,5,7, // Z
3,5,4,6, // S
3,5,4,7, // T
2,3,5,7, // L
3,5,7,6, // J
2,3,4,5, // O
};

bool check()
{
for (int i=0;i<4;i++)
if (a[i].x<0 || a[i].x>=N || a[i].y>=M) return 0;
else if (field[a[i].y][a[i].x]) return 0;

return 1;
};

int main()
{
srand(time(0));

RenderWindow window(VideoMode(320, 480), "The Game!");

Texture t1,t2,t3;
t1.loadFromFile("images/tiles.png");
t2.loadFromFile("images/background.png");
t3.loadFromFile("images/frame.png");

Sprite s(t1), background(t2), frame(t3);

int dx=0; bool rotate=0; int colorNum=1;


float timer=0,delay=0.3;

Clock clock;

while (window.isOpen())
{
float time = clock.getElapsedTime().asSeconds();
clock.restart();
timer+=time;

Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();

if (e.type == Event::KeyPressed)
if (e.key.code==Keyboard::Up) rotate=true;
else if (e.key.code==Keyboard::Left) dx=-1;
else if (e.key.code==Keyboard::Right) dx=1;
}

if (Keyboard::isKeyPressed(Keyboard::Down)) delay=0.05;

//// <- Move -> ///


for (int i=0;i<4;i++) { b[i]=a[i]; a[i].x+=dx; }
if (!check()) for (int i=0;i<4;i++) a[i]=b[i];

//////Rotate//////
if (rotate)
{
Point p = a[1]; //center of rotation
for (int i=0;i<4;i++)
{
int x = a[i].y-p.y;
int y = a[i].x-p.x;
a[i].x = p.x - x;
a[i].y = p.y + y;
}
if (!check()) for (int i=0;i<4;i++) a[i]=b[i];
}

///////Tick//////
if (timer>delay)
{
for (int i=0;i<4;i++) { b[i]=a[i]; a[i].y+=1; }

if (!check())
{
for (int i=0;i<4;i++) field[b[i].y][b[i].x]=colorNum;

colorNum=1+rand()%7;
int n=rand()%7;
for (int i=0;i<4;i++)
{
a[i].x = figures[n][i] % 2;
a[i].y = figures[n][i] / 2;
}
}

timer=0;
}

///////check lines//////////
int k=M-1;
for (int i=M-1;i>0;i--)
{
int count=0;
for (int j=0;j<N;j++)
{
if (field[i][j]) count++;
field[k][j]=field[i][j];
}
if (count<N) k--;
}

dx=0; rotate=0; delay=0.3;

/////////draw//////////
window.clear(Color::White);
window.draw(background);

for (int i=0;i<M;i++)


for (int j=0;j<N;j++)
{
if (field[i][j]==0) continue;
s.setTextureRect(IntRect(field[i][j]*18,0,18,18));
s.setPosition(j*18,i*18);
s.move(28,31); //offset
window.draw(s);
}

for (int i=0;i<4;i++)


{
s.setTextureRect(IntRect(colorNum*18,0,18,18));
s.setPosition(a[i].x*18,a[i].y*18);
s.move(28,31); //offset
window.draw(s);
}

window.draw(frame);
window.display();
}

return 0;
}

2.........................DOODLE JUMP.....

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

struct point
{ int x,y;};

int main()
{
srand(time(0));

RenderWindow app(VideoMode(400, 533), "Doodle Game!");


app.setFramerateLimit(60);
Texture t1,t2,t3;
t1.loadFromFile("images/background.png");
t2.loadFromFile("images/platform.png");
t3.loadFromFile("images/doodle.png");

Sprite sBackground(t1), sPlat(t2), sPers(t3);

point plat[20];

for (int i=0;i<10;i++)


{
plat[i].x=rand()%400;
plat[i].y=rand()%533;
}

int x=100,y=100,h=200;
float dx=0,dy=0;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();
}

if (Keyboard::isKeyPressed(Keyboard::Right)) x+=3;
if (Keyboard::isKeyPressed(Keyboard::Left)) x-=3;

dy+=0.2;
y+=dy;
if (y>500) dy=-10;

if (y<h)
for (int i=0;i<10;i++)
{
y=h;
plat[i].y=plat[i].y-dy;
if (plat[i].y>533) {plat[i].y=0; plat[i].x=rand()%400;}
}

for (int i=0;i<10;i++)


if ((x+50>plat[i].x) && (x+20<plat[i].x+68)
&& (y+70>plat[i].y) && (y+70<plat[i].y+14) && (dy>0)) dy=-10;

sPers.setPosition(x,y);

app.draw(sBackground);
app.draw(sPers);
for (int i=0;i<10;i++)
{
sPlat.setPosition(plat[i].x,plat[i].y);
app.draw(sPlat);
}

app.display();
}
return 0;
}

3.........................ARKANOID........

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main()
{
srand(time(0));

RenderWindow app(VideoMode(520, 450), "Arkanoid!");


app.setFramerateLimit(60);

Texture t1,t2,t3,t4;
t1.loadFromFile("images/block01.png");
t2.loadFromFile("images/background.jpg");
t3.loadFromFile("images/ball.png");
t4.loadFromFile("images/paddle.png");

Sprite sBackground(t2), sBall(t3), sPaddle(t4);


sPaddle.setPosition(300,440);

Sprite block[1000];

int n=0;
for (int i=1;i<=10;i++)
for (int j=1;j<=10;j++)
{
block[n].setTexture(t1);
block[n].setPosition(i*43,j*20);
n++;
}

float dx=6, dy=5;


float x=300, y=300;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();
}

x+=dx;
for (int i=0;i<n;i++)
if ( FloatRect(x+3,y+3,6,6).intersects(block[i].getGlobalBounds()) )
{block[i].setPosition(-100,0); dx=-dx;}

y+=dy;
for (int i=0;i<n;i++)
if ( FloatRect(x+3,y+3,6,6).intersects(block[i].getGlobalBounds()) )
{block[i].setPosition(-100,0); dy=-dy;}
if (x<0 || x>520) dx=-dx;
if (y<0 || y>450) dy=-dy;

if (Keyboard::isKeyPressed(Keyboard::Right)) sPaddle.move(6,0);
if (Keyboard::isKeyPressed(Keyboard::Left)) sPaddle.move(-6,0);

if ( FloatRect(x,y,12,12).intersects(sPaddle.getGlobalBounds()) ) dy=-(rand()
%5+2);

sBall.setPosition(x,y);

app.clear();
app.draw(sBackground);
app.draw(sBall);
app.draw(sPaddle);

for (int i=0;i<n;i++)


app.draw(block[i]);

app.display();
}

return 0;
}

4.........................SNAKE...........

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int N=30,M=20;
int size=16;
int w = size*N;
int h = size*M;

int dir,num=4;

struct Snake
{ int x,y;} s[100];

struct Fruit
{ int x,y;} f;

void Tick()
{
for (int i=num;i>0;--i)
{s[i].x=s[i-1].x; s[i].y=s[i-1].y;}

if (dir==0) s[0].y+=1;
if (dir==1) s[0].x-=1;
if (dir==2) s[0].x+=1;
if (dir==3) s[0].y-=1;

if ((s[0].x==f.x) && (s[0].y==f.y))


{num++; f.x=rand()%N; f.y=rand()%M;}
if (s[0].x>N) s[0].x=0; if (s[0].x<0) s[0].x=N;
if (s[0].y>M) s[0].y=0; if (s[0].y<0) s[0].y=M;

for (int i=1;i<num;i++)


if (s[0].x==s[i].x && s[0].y==s[i].y) num=i;
}

int main()
{
srand(time(0));

RenderWindow window(VideoMode(w, h), "Snake Game!");

Texture t1,t2;
t1.loadFromFile("images/white.png");
t2.loadFromFile("images/red.png");

Sprite sprite1(t1);
Sprite sprite2(t2);

Clock clock;
float timer=0, delay=0.1;

f.x=10;
f.y=10;

while (window.isOpen())
{
float time = clock.getElapsedTime().asSeconds();
clock.restart();
timer+=time;

Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();
}

if (Keyboard::isKeyPressed(Keyboard::Left)) dir=1;
if (Keyboard::isKeyPressed(Keyboard::Right)) dir=2;
if (Keyboard::isKeyPressed(Keyboard::Up)) dir=3;
if (Keyboard::isKeyPressed(Keyboard::Down)) dir=0;

if (timer>delay) {timer=0; Tick();}

////// draw ///////


window.clear();

for (int i=0; i<N; i++)


for (int j=0; j<M; j++)
{ sprite1.setPosition(i*size, j*size); window.draw(sprite1); }

for (int i=0;i<num;i++)


{ sprite2.setPosition(s[i].x*size, s[i].y*size); window.draw(sprite2); }

sprite2.setPosition(f.x*size, f.y*size); window.draw(sprite2);

window.display();
}

return 0;
}

5.........................MINESWEEPER.....

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main()
{
srand(time(0));

RenderWindow app(VideoMode(400, 400), "Minesweeper!");

int w=32;
int grid[12][12];
int sgrid[12][12]; //for showing

Texture t;
t.loadFromFile("images/tiles.jpg");
Sprite s(t);

for (int i=1;i<=10;i++)


for (int j=1;j<=10;j++)
{
sgrid[i][j]=10;
if (rand()%5==0) grid[i][j]=9;
else grid[i][j]=0;
}

for (int i=1;i<=10;i++)


for (int j=1;j<=10;j++)
{
int n=0;
if (grid[i][j]==9) continue;
if (grid[i+1][j]==9) n++;
if (grid[i][j+1]==9) n++;
if (grid[i-1][j]==9) n++;
if (grid[i][j-1]==9) n++;
if (grid[i+1][j+1]==9) n++;
if (grid[i-1][j-1]==9) n++;
if (grid[i-1][j+1]==9) n++;
if (grid[i+1][j-1]==9) n++;
grid[i][j]=n;
}

while (app.isOpen())
{
Vector2i pos = Mouse::getPosition(app);
int x = pos.x/w;
int y = pos.y/w;

Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();

if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left) sgrid[x][y]=grid[x][y];
else if (e.key.code == Mouse::Right) sgrid[x][y]=11;
}

app.clear(Color::White);

for (int i=1;i<=10;i++)


for (int j=1;j<=10;j++)
{
if (sgrid[x][y]==9) sgrid[i][j]=grid[i][j];
s.setTextureRect(IntRect(sgrid[i][j]*w,0,w,w));
s.setPosition(i*w, j*w);
app.draw(s);
}

app.display();
}

return 0;
}

6.........................FIFTEEN PUZZLE..

#include <SFML/Graphics.hpp>
#include <iostream>

using namespace sf;

int main()
{
RenderWindow app(VideoMode(256,256), "15-Puzzle!");
app.setFramerateLimit(60);

Texture t;
t.loadFromFile("images/15.png");

int w = 64;
int grid[6][6] = {0};
Sprite sprite[20];

int n=0;
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
{
n++;
sprite[n].setTexture(t);
sprite[n].setTextureRect( IntRect(i*w,j*w,w,w) );
grid[i+1][j+1]=n;
}

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();

if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left)
{
Vector2i pos = Mouse::getPosition(app);
int x = pos.x/w + 1;
int y = pos.y/w + 1;

int dx=0;
int dy=0;

if (grid[x+1][y]==16) {dx=1; dy=0;};


if (grid[x][y+1]==16) {dx=0; dy=1;};
if (grid[x][y-1]==16) {dx=0; dy=-1;};
if (grid[x-1][y]==16) {dx=-1;dy=0;};

int n = grid[x][y];
grid[x][y] = 16;
grid[x+dx][y+dy] = n;

//animation
sprite[16].move(-dx*w,-dy*w);
float speed=3;

for (int i=0;i<w;i+=speed)


{sprite[n].move(speed*dx,speed*dy);
app.draw(sprite[16]);
app.draw(sprite[n]);
app.display(); }
}

app.clear(Color::White);
for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
{
int n = grid[i+1][j+1];
sprite[n].setPosition(i*w,j*w);
app.draw(sprite[n]);
}

app.display();
}

return 0;
}

7.........................RACING (TOP DOWN)....

#include <SFML/Graphics.hpp>
using namespace sf;

const int num=8; //checkpoints


int points[num][2] = {300, 610,
1270,430,
1380,2380,
1900,2460,
1970,1700,
2550,1680,
2560,3150,
500, 3300};

struct Car
{
float x,y,speed,angle; int n;

Car() {speed=2; angle=0; n=0;}

void move()
{
x += sin(angle) * speed;
y -= cos(angle) * speed;
}

void findTarget()
{
float tx=points[n][0];
float ty=points[n][1];
float beta = angle-atan2(tx-x,-ty+y);
if (sin(beta)<0) angle+=0.005*speed; else angle-=0.005*speed;
if ((x-tx)*(x-tx)+(y-ty)*(y-ty)<25*25) n=(n+1)%num;
}
};

int main()
{
RenderWindow app(VideoMode(640, 480), "Car Racing Game!");
app.setFramerateLimit(60);

Texture t1,t2,t3;
t1.loadFromFile("images/background.png");
t2.loadFromFile("images/car.png");
t1.setSmooth(true);
t2.setSmooth(true);

Sprite sBackground(t1), sCar(t2);


sBackground.scale(2,2);

sCar.setOrigin(22, 22);
float R=22;

const int N=5;


Car car[N];
for(int i=0;i<N;i++)
{
car[i].x=300+i*50;
car[i].y=1700+i*80;
car[i].speed=7+i;
}

float speed=0,angle=0;
float maxSpeed=12.0;
float acc=0.2, dec=0.3;
float turnSpeed=0.08;

int offsetX=0,offsetY=0;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();
}

bool Up=0,Right=0,Down=0,Left=0;
if (Keyboard::isKeyPressed(Keyboard::Up)) Up=1;
if (Keyboard::isKeyPressed(Keyboard::Right)) Right=1;
if (Keyboard::isKeyPressed(Keyboard::Down)) Down=1;
if (Keyboard::isKeyPressed(Keyboard::Left)) Left=1;

//car movement
if (Up && speed<maxSpeed)
if (speed < 0) speed += dec;
else speed += acc;

if (Down && speed>-maxSpeed)


if (speed > 0) speed -= dec;
else speed -= acc;

if (!Up && !Down)


if (speed - dec > 0) speed -= dec;
else if (speed + dec < 0) speed += dec;
else speed = 0;

if (Right && speed!=0) angle += turnSpeed * speed/maxSpeed;


if (Left && speed!=0) angle -= turnSpeed * speed/maxSpeed;

car[0].speed = speed;
car[0].angle = angle;

for(int i=0;i<N;i++) car[i].move();


for(int i=1;i<N;i++) car[i].findTarget();

//collision
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
{
int dx=0, dy=0;
while (dx*dx+dy*dy<4*R*R)
{
car[i].x+=dx/10.0;
car[i].x+=dy/10.0;
car[j].x-=dx/10.0;
car[j].y-=dy/10.0;
dx = car[i].x-car[j].x;
dy = car[i].y-car[j].y;
if (!dx && !dy) break;
}
}
app.clear(Color::White);

if (car[0].x>320) offsetX = car[0].x-320;


if (car[0].y>240) offsetY = car[0].y-240;

sBackground.setPosition(-offsetX,-offsetY);
app.draw(sBackground);

Color colors[10] = {Color::Red, Color::Green, Color::Magenta, Color::Blue,


Color::White};

for(int i=0;i<N;i++)
{
sCar.setPosition(car[i].x-offsetX,car[i].y-offsetY);
sCar.setRotation(car[i].angle*180/3.141593);
sCar.setColor(colors[i]);
app.draw(sCar);
}

app.display();
}

return 0;
}

8.........................OUTRUN...........

#include <SFML/Graphics.hpp>
using namespace sf;

int width = 1024;


int height = 768;
int roadW = 2000;
int segL = 200; //segment length
float camD = 0.84; //camera depth

void drawQuad(RenderWindow &w, Color c, int x1,int y1,int w1,int x2,int y2,int w2)
{
ConvexShape shape(4);
shape.setFillColor(c);
shape.setPoint(0, Vector2f(x1-w1,y1));
shape.setPoint(1, Vector2f(x2-w2,y2));
shape.setPoint(2, Vector2f(x2+w2,y2));
shape.setPoint(3, Vector2f(x1+w1,y1));
w.draw(shape);
}

struct Line
{
float x,y,z; //3d center of line
float X,Y,W; //screen coord
float curve,spriteX,clip,scale;
Sprite sprite;

Line()
{spriteX=curve=x=y=z=0;}
void project(int camX,int camY,int camZ)
{
scale = camD/(z-camZ);
X = (1 + scale*(x - camX)) * width/2;
Y = (1 - scale*(y - camY)) * height/2;
W = scale * roadW * width/2;
}

void drawSprite(RenderWindow &app)


{
Sprite s = sprite;
int w = s.getTextureRect().width;
int h = s.getTextureRect().height;

float destX = X + scale * spriteX * width/2;


float destY = Y + 4;
float destW = w * W / 266;
float destH = h * W / 266;

destX += destW * spriteX; //offsetX


destY += destH * (-1); //offsetY

float clipH = destY+destH-clip;


if (clipH<0) clipH=0;

if (clipH>=destH) return;
s.setTextureRect(IntRect(0,0,w,h-h*clipH/destH));
s.setScale(destW/w,destH/h);
s.setPosition(destX, destY);
app.draw(s);
}
};

int main()
{
RenderWindow app(VideoMode(width, height), "Outrun Racing!");
app.setFramerateLimit(60);

Texture t[50];
Sprite object[50];
for(int i=1;i<=7;i++)
{
t[i].loadFromFile("images/"+std::to_string(i)+".png");
t[i].setSmooth(true);
object[i].setTexture(t[i]);
}

Texture bg;
bg.loadFromFile("images/bg.png");
bg.setRepeated(true);
Sprite sBackground(bg);
sBackground.setTextureRect(IntRect(0,0,5000,411));
sBackground.setPosition(-2000,0);

std::vector<Line> lines;

for(int i=0;i<1600;i++)
{
Line line;
line.z = i*segL;

if (i>300 && i<700) line.curve=0.5;


if (i>1100) line.curve=-0.7;

if (i<300 && i%20==0) {line.spriteX=-2.5; line.sprite=object[5];}


if (i%17==0) {line.spriteX=2.0; line.sprite=object[6];}
if (i>300 && i%20==0) {line.spriteX=-0.7; line.sprite=object[4];}
if (i>800 && i%20==0) {line.spriteX=-1.2; line.sprite=object[1];}
if (i==400) {line.spriteX=-1.2; line.sprite=object[7];}

if (i>750) line.y = sin(i/30.0)*1500;

lines.push_back(line);
}

int N = lines.size();
float playerX = 0;
int pos = 0;
int H = 1500;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();
}

int speed=0;

if (Keyboard::isKeyPressed(Keyboard::Right)) playerX+=0.1;
if (Keyboard::isKeyPressed(Keyboard::Left)) playerX-=0.1;
if (Keyboard::isKeyPressed(Keyboard::Up)) speed=200;
if (Keyboard::isKeyPressed(Keyboard::Down)) speed=-200;
if (Keyboard::isKeyPressed(Keyboard::Tab)) speed*=3;
if (Keyboard::isKeyPressed(Keyboard::W)) H+=100;
if (Keyboard::isKeyPressed(Keyboard::S)) H-=100;

pos+=speed;
while (pos >= N*segL) pos-=N*segL;
while (pos < 0) pos += N*segL;

app.clear(Color(105,205,4));
app.draw(sBackground);
int startPos = pos/segL;
int camH = lines[startPos].y + H;
if (speed>0) sBackground.move(-lines[startPos].curve*2,0);
if (speed<0) sBackground.move( lines[startPos].curve*2,0);

int maxy = height;


float x=0,dx=0;

///////draw road////////
for(int n = startPos; n<startPos+300; n++)
{
Line &l = lines[n%N];
l.project(playerX*roadW-x, camH, startPos*segL - (n>=N?N*segL:0));
x+=dx;
dx+=l.curve;

l.clip=maxy;
if (l.Y>=maxy) continue;
maxy = l.Y;

Color grass = (n/3)%2?Color(16,200,16):Color(0,154,0);


Color rumble = (n/3)%2?Color(255,255,255):Color(0,0,0);
Color road = (n/3)%2?Color(107,107,107):Color(105,105,105);

Line p = lines[(n-1)%N]; //previous line

drawQuad(app, grass, 0, p.Y, width, 0, l.Y, width);


drawQuad(app, rumble,p.X, p.Y, p.W*1.2, l.X, l.Y, l.W*1.2);
drawQuad(app, road, p.X, p.Y, p.W, l.X, l.Y, l.W);
}

////////draw objects////////
for(int n=startPos+300; n>startPos; n--)
lines[n%N].drawSprite(app);

app.display();
}

return 0;
}

9.........................XONIX............

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

const int M = 25;


const int N = 40;

int grid[M][N] = {0};


int ts = 18; //tile size

struct Enemy
{int x,y,dx,dy;

Enemy()
{
x=y=300;
dx=4-rand()%8;
dy=4-rand()%8;
}

void move()
{
x+=dx; if (grid[y/ts][x/ts]==1) {dx=-dx; x+=dx;}
y+=dy; if (grid[y/ts][x/ts]==1) {dy=-dy; y+=dy;}
}
};
void drop(int y,int x)
{
if (grid[y][x]==0) grid[y][x]=-1;
if (grid[y-1][x]==0) drop(y-1,x);
if (grid[y+1][x]==0) drop(y+1,x);
if (grid[y][x-1]==0) drop(y,x-1);
if (grid[y][x+1]==0) drop(y,x+1);
}

int main()
{
srand(time(0));

RenderWindow window(VideoMode(N*ts, M*ts), "Xonix Game!");


window.setFramerateLimit(60);

Texture t1,t2,t3;
t1.loadFromFile("images/tiles.png");
t2.loadFromFile("images/gameover.png");
t3.loadFromFile("images/enemy.png");

Sprite sTile(t1), sGameover(t2), sEnemy(t3);


sGameover.setPosition(100,100);
sEnemy.setOrigin(20,20);

int enemyCount = 4;
Enemy a[10];

bool Game=true;
int x=0, y=0, dx=0, dy=0;
float timer=0, delay=0.07;
Clock clock;

for (int i=0;i<M;i++)


for (int j=0;j<N;j++)
if (i==0 || j==0 || i==M-1 || j==N-1) grid[i][j]=1;

while (window.isOpen())
{
float time = clock.getElapsedTime().asSeconds();
clock.restart();
timer+=time;

Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();

if (e.type == Event::KeyPressed)
if (e.key.code==Keyboard::Escape)
{
for (int i=1;i<M-1;i++)
for (int j=1;j<N-1;j++)
grid[i][j]=0;

x=10;y=0;
Game=true;
}
}

if (Keyboard::isKeyPressed(Keyboard::Left)) {dx=-1;dy=0;};
if (Keyboard::isKeyPressed(Keyboard::Right)) {dx=1;dy=0;};
if (Keyboard::isKeyPressed(Keyboard::Up)) {dx=0;dy=-1;};
if (Keyboard::isKeyPressed(Keyboard::Down)) {dx=0;dy=1;};

if (!Game) continue;

if (timer>delay)
{
x+=dx;
y+=dy;

if (x<0) x=0; if (x>N-1) x=N-1;


if (y<0) y=0; if (y>M-1) y=M-1;

if (grid[y][x]==2) Game=false;
if (grid[y][x]==0) grid[y][x]=2;
timer=0;
}

for (int i=0;i<enemyCount;i++) a[i].move();

if (grid[y][x]==1)
{
dx=dy=0;

for (int i=0;i<enemyCount;i++)


drop(a[i].y/ts, a[i].x/ts);

for (int i=0;i<M;i++)


for (int j=0;j<N;j++)
if (grid[i][j]==-1) grid[i][j]=0;
else grid[i][j]=1;
}

for (int i=0;i<enemyCount;i++)


if (grid[a[i].y/ts][a[i].x/ts]==2) Game=false;

/////////draw//////////
window.clear();

for (int i=0;i<M;i++)


for (int j=0;j<N;j++)
{
if (grid[i][j]==0) continue;
if (grid[i][j]==1) sTile.setTextureRect(IntRect( 0,0,ts,ts));
if (grid[i][j]==2) sTile.setTextureRect(IntRect(54,0,ts,ts));
sTile.setPosition(j*ts,i*ts);
window.draw(sTile);
}

sTile.setTextureRect(IntRect(36,0,ts,ts));
sTile.setPosition(x*ts,y*ts);
window.draw(sTile);

sEnemy.rotate(10);
for (int i=0;i<enemyCount;i++)
{
sEnemy.setPosition(a[i].x,a[i].y);
window.draw(sEnemy);
}

if (!Game) window.draw(sGameover);

window.display();
}

return 0;
}

10........................BEJEWELED........

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int ts = 54; //tile size


Vector2i offset(48,24);

struct piece
{ int x,y,col,row,kind,match,alpha;
piece(){match=0; alpha=255;}
} grid[10][10];

void swap(piece p1,piece p2)


{
std::swap(p1.col,p2.col);
std::swap(p1.row,p2.row);

grid[p1.row][p1.col]=p1;
grid[p2.row][p2.col]=p2;
}

int main()
{
srand(time(0));

RenderWindow app(VideoMode(740,480), "Match-3 Game!");


app.setFramerateLimit(60);

Texture t1,t2;
t1.loadFromFile("images/background.png");
t2.loadFromFile("images/gems.png");

Sprite background(t1), gems(t2);

for (int i=1;i<=8;i++)


for (int j=1;j<=8;j++)
{
grid[i][j].kind=rand()%3;
grid[i][j].col=j;
grid[i][j].row=i;
grid[i][j].x = j*ts;
grid[i][j].y = i*ts;
}

int x0,y0,x,y; int click=0; Vector2i pos;


bool isSwap=false, isMoving=false;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();

if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left)
{
if (!isSwap && !isMoving) click++;
pos = Mouse::getPosition(app)-offset;
}
}

// mouse click
if (click==1)
{
x0=pos.x/ts+1;
y0=pos.y/ts+1;
}
if (click==2)
{
x=pos.x/ts+1;
y=pos.y/ts+1;
if (abs(x-x0)+abs(y-y0)==1)
{swap(grid[y0][x0],grid[y][x]); isSwap=1; click=0;}
else click=1;
}

//Match finding
for(int i=1;i<=8;i++)
for(int j=1;j<=8;j++)
{
if (grid[i][j].kind==grid[i+1][j].kind)
if (grid[i][j].kind==grid[i-1][j].kind)
for(int n=-1;n<=1;n++) grid[i+n][j].match++;

if (grid[i][j].kind==grid[i][j+1].kind)
if (grid[i][j].kind==grid[i][j-1].kind)
for(int n=-1;n<=1;n++) grid[i][j+n].match++;
}

//Moving animation
isMoving=false;
for (int i=1;i<=8;i++)
for (int j=1;j<=8;j++)
{
piece &p = grid[i][j];
int dx,dy;
for(int n=0;n<4;n++) // 4 - speed
{dx = p.x-p.col*ts;
dy = p.y-p.row*ts;
if (dx) p.x-=dx/abs(dx);
if (dy) p.y-=dy/abs(dy);}
if (dx||dy) isMoving=1;
}

//Deleting amimation
if (!isMoving)
for (int i=1;i<=8;i++)
for (int j=1;j<=8;j++)
if (grid[i][j].match) if (grid[i][j].alpha>10) {grid[i][j].alpha-=10;
isMoving=true;}

//Get score
int score=0;
for (int i=1;i<=8;i++)
for (int j=1;j<=8;j++)
score+=grid[i][j].match;

//Second swap if no match


if (isSwap && !isMoving)
{if (!score) swap(grid[y0][x0],grid[y][x]); isSwap=0;}

//Update grid
if (!isMoving)
{
for(int i=8;i>0;i--)
for(int j=1;j<=8;j++)
if (grid[i][j].match)
for(int n=i;n>0;n--)
if (!grid[n][j].match) {swap(grid[n][j],grid[i][j]); break;};

for(int j=1;j<=8;j++)
for(int i=8,n=0;i>0;i--)
if (grid[i][j].match)
{
grid[i][j].kind = rand()%7;
grid[i][j].y = -ts*n++;
grid[i][j].match=0;
grid[i][j].alpha = 255;
}
}

//////draw///////
app.draw(background);

for (int i=1;i<=8;i++)


for (int j=1;j<=8;j++)
{
piece p = grid[i][j];
gems.setTextureRect( IntRect(p.kind*49,0,49,49));
gems.setColor(Color(255,255,255,p.alpha));
gems.setPosition(p.x,p.y);
gems.move(offset.x-ts,offset.y-ts);
app.draw(gems);
}

app.display();
}
return 0;
}

11........................NETWALK (PIPE PUZZLE)...

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

const int N = 6;
int ts = 54; //tile size
Vector2f offset(65,55);

Vector2i Up(0,-1);
Vector2i Down(0,1);
Vector2i Right(1,0);
Vector2i Left(-1,0);

Vector2i DIR[4] = {Up,Right,Down,Left};

struct pipe
{
std::vector<Vector2i> dirs;
int orientation;
float angle; bool on;

pipe() {angle=0;}

void rotate()
{
for(int i=0;i<dirs.size();i++)
if (dirs[i]==Up) dirs[i]=Right;
else if (dirs[i]==Right) dirs[i]=Down;
else if (dirs[i]==Down) dirs[i]=Left;
else if (dirs[i]==Left) dirs[i]=Up;
}

bool isConnect(Vector2i dir)


{
for(auto d: dirs)
if (d==dir) return true;
return false;
}
};

pipe grid[N][N];
pipe& cell(Vector2i v) {return grid[v.x][v.y];}
bool isOut(Vector2i v) {return !IntRect(0,0,N,N).contains(v);}

void generatePuzzle()
{
std::vector<Vector2i> nodes;
nodes.push_back(Vector2i(rand()%N,rand()%N));

while(!nodes.empty())
{
int n = rand()%nodes.size();
Vector2i v = nodes[n];
Vector2i d = DIR[rand()%4];

if (cell(v).dirs.size()==3) {nodes.erase(nodes.begin() + n); continue;}


if (cell(v).dirs.size()==2) if (rand()%50) continue;

bool complete=1;
for(auto D:DIR)
if (!isOut(v+D) && cell(v+D).dirs.empty()) complete=0;
if (complete) {nodes.erase(nodes.begin() + n); continue; }

if (isOut(v+d)) continue;
if (!cell(v+d).dirs.empty()) continue;
cell(v).dirs.push_back(d);
cell(v+d).dirs.push_back(-d);
nodes.push_back(v+d);
}
}

void drop(Vector2i v)
{
if (cell(v).on) return;
cell(v).on=true;

for(auto d:DIR)
if (!isOut(v+d))
if (cell(v).isConnect(d) && cell(v+d).isConnect(-d))
drop(v+d);
}

int main()
{
srand(time(0));

RenderWindow app(VideoMode(390, 390), "The Pipe Puzzle!");

Texture t1,t2,t3,t4;
t1.loadFromFile("images/background.png");
t2.loadFromFile("images/comp.png");
t3.loadFromFile("images/server.png");
t4.loadFromFile("images/pipes.png");
t4.setSmooth(true);

Sprite sBackground(t1), sComp(t2), sServer(t3), sPipe(t4);


sPipe.setOrigin(27,27);
sComp.setOrigin(18,18);
sServer.setOrigin(20,20);

generatePuzzle();

for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
{
pipe &p = grid[j][i];
for(int n=4;n>0;n--) //find orientation//
{
std::string s="";
for(auto d: DIR) s+=p.isConnect(d)? '1':'0';
if (s=="0011" || s=="0111" || s=="0101" || s=="0010") p.orientation=n;
p.rotate();
}

for(int n=0;n<rand()%4;n++) //shuffle//


{grid[j][i].orientation++; grid[j][i].rotate();}
}

Vector2i servPos;
while(cell(servPos).dirs.size()==1) {servPos = Vector2i(rand()%N, rand()%N);}
sServer.setPosition(Vector2f(servPos*ts));
sServer.move(offset);

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();

if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left)
{
Vector2i pos = Mouse::getPosition(app) + Vector2i(ts/2,ts/2) -
Vector2i(offset);
pos/=ts;
if (isOut(pos)) continue;
cell(pos).orientation++;
cell(pos).rotate();

for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
grid[j][i].on=0;

drop(servPos);
}
}

app.clear();
app.draw(sBackground);

for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
{
pipe &p = grid[j][i];

int kind = p.dirs.size();


if (kind==2 && p.dirs[0]==-p.dirs[1]) kind=0;

p.angle+=5;
if (p.angle>p.orientation*90) p.angle=p.orientation*90;

sPipe.setTextureRect(IntRect(ts*kind,0,ts,ts));
sPipe.setRotation(p.angle);
sPipe.setPosition(j*ts,i*ts);sPipe.move(offset);
app.draw(sPipe);

if (kind==1)
{ if (p.on) sComp.setTextureRect(IntRect(53,0,36,36));
else sComp.setTextureRect(IntRect(0,0,36,36));
sComp.setPosition(j*ts,i*ts);sComp.move(offset);
app.draw(sComp);
}
}

app.draw(sServer);
app.display();
}

return 0;
}

12........................MAHJONG SOLITAIRE....

#include <SFML/Graphics.hpp>
#include <fstream>
#include <time.h>
using namespace sf;

int field[50][50][50] = {0};

int& f(int x,int y,int z){return field[y+2][x+2][z];}


int& f(Vector3i v){return f(v.x,v.y,v.z);}

bool isOpen(int x,int y,int z)


{
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
if (f(x+2,y+i,z)>0 && f(x-2,y+j,z)>0) return 0;

for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
if ( f(x+i,y+j,z+1)>0 ) return 0;

return 1;
}

int main()
{
srand(time(0));

RenderWindow app(VideoMode(740, 570), "Mahjong Solitaire!");

Texture t1,t2;
t1.loadFromFile("files/tiles.png");
t2.loadFromFile("files/background.png");
Sprite s(t1), sBackground(t2);
int w=48, h=66;
int stepX=w/2-2, stepY=h/2-2;
float offX=4.6, offY=7.1; // z offset
Vector3i v1,v2;
std::vector<Vector3i> moves;

////load from file////


std::fstream myfile("files/map.txt");
for(int y=0;y<18;y++)
for(int x=0;x<30;x++)
{
char a; myfile >> a;
int n = a - '0';
for(int z=0;z<n;z++)
if (f(x-1,y-1,z)) f(x-1,y,z)=f(x,y-1,z)=0;
else f(x,y,z)=1;
}

////create map//////
for(int k=1;;k++)
{
std::vector<Vector3i> opens;
for(int z=0;z<10;z++)
for(int y=0;y<18;y++)
for(int x=0;x<30;x++)
if (f(x,y,z)>0 && isOpen(x,y,z)) opens.push_back(Vector3i(x,y,z));

int n=opens.size();
if (n<2) break;
int a=0,b=0;
while(a==b){a=rand()%n;b=rand()%n;}
f(opens[a])=-k; if (k>34) k++;
f(opens[b])=-k;
k%=42;
}

for(int z=0;z<10;z++)
for(int y=0;y<18;y++)
for(int x=0;x<30;x++) f(x,y,z)*=-1;

while (app.isOpen())
{
Event e;
while (app.pollEvent(e))
{
if (e.type == Event::Closed)
app.close();

//move back
if (e.type == Event::MouseButtonReleased)
if (e.key.code == Mouse::Right)
{
int n = moves.size();
if (n==0) continue;
f(moves[n-1])*=-1; moves.pop_back();
f(moves[n-2])*=-1; moves.pop_back();
}
if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left)
for(int z=0;z<10;z++)
{
Vector2i pos = Mouse::getPosition(app) - Vector2i(30,0); // 30
- desk offset
int x = (pos.x-z*offX)/stepX;
int y = (pos.y+z*offY)/stepY;

for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
if (f(x-i,y-j,z)>0 && isOpen(x-i,y-j,z))
v1=Vector3i(x-i,y-j,z);

if (v1==v2) continue;

int a=f(v1),b=f(v2);
if ( a==b || (a>34 && a<39 && b>34 && b<39) || (a>=39 &&
b>=39) )
{
f(v1)*=-1; moves.push_back(v1);
f(v2)*=-1; moves.push_back(v2);
}
v2=v1;
}
}

app.clear();
app.draw(sBackground);
for(int z=0;z<10;z++)
for(int x=30;x>=0;x--)
for(int y=0;y<18;y++)
{
int k = f(x,y,z)-1;
if (k<0) continue;
s.setTextureRect(IntRect(k*w,0,w,h));
if (isOpen(x,y,z)) s.setTextureRect(IntRect(k*w,h,w,h));
s.setPosition(x*stepX + z*offX, y*stepY - z*offY);
s.move(30,0); //desk offset
app.draw(s);
}

app.display();
}

return 0;
}

13.......................TRON..................

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

const int W=600;


const int H=480;
int speed = 4;
bool field[W][H]={0};
struct player
{ int x,y,dir;
Color color;
player(Color c)
{
x=rand() % W;
y=rand() % H;
color=c;
dir=rand() % 4;
}
void tick()
{
if (dir==0) y+=1;
if (dir==1) x-=1;
if (dir==2) x+=1;
if (dir==3) y-=1;

if (x>=W) x=0; if (x<0) x=W-1;


if (y>=H) y=0; if (y<0) y=H-1;
}

Vector3f getColor()
{return Vector3f(color.r,color.g,color.b);}
};

int main()
{
srand(time(0));

RenderWindow window(VideoMode(W, H), "The Tron Game!");


window.setFramerateLimit(60);

Texture texture;
texture.loadFromFile("background.jpg");
Sprite sBackground(texture);

player p1(Color::Red), p2(Color::Green);

Sprite sprite;
RenderTexture t;
t.create(W, H);
t.setSmooth(true);
sprite.setTexture(t.getTexture());
t.clear(); t.draw(sBackground);

bool Game=1;

while (window.isOpen())
{
Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();
}

if (Keyboard::isKeyPressed(Keyboard::Left)) if (p1.dir!=2) p1.dir=1;


if (Keyboard::isKeyPressed(Keyboard::Right)) if (p1.dir!=1) p1.dir=2;
if (Keyboard::isKeyPressed(Keyboard::Up)) if (p1.dir!=0) p1.dir=3;
if (Keyboard::isKeyPressed(Keyboard::Down)) if (p1.dir!=3) p1.dir=0;

if (Keyboard::isKeyPressed(Keyboard::A)) if (p2.dir!=2) p2.dir=1;


if (Keyboard::isKeyPressed(Keyboard::D)) if (p2.dir!=1) p2.dir=2;
if (Keyboard::isKeyPressed(Keyboard::W)) if (p2.dir!=0) p2.dir=3;
if (Keyboard::isKeyPressed(Keyboard::S)) if (p2.dir!=3) p2.dir=0;

if (!Game) continue;

for(int i=0;i<speed;i++)
{
p1.tick(); p2.tick();
if (field[p1.x][p1.y]==1) Game=0;
if (field[p2.x][p2.y]==1) Game=0;
field[p1.x][p1.y]=1;
field[p2.x][p2.y]=1;

CircleShape c(3);
c.setPosition(p1.x,p1.y); c.setFillColor(p1.color); t.draw(c);
c.setPosition(p2.x,p2.y); c.setFillColor(p2.color); t.draw(c);
t.display();
}

////// draw ///////


window.clear();
window.draw(sprite);
window.display();
}

return 0;
}

14.......................CHESS.................

#include <SFML/Graphics.hpp>
#include <time.h>
#include "Connector.hpp"
using namespace sf;

int size = 56;


Vector2f offset(28,28);

Sprite f[32]; //figures


std::string position="";

int board[8][8] =
{-1,-2,-3,-4,-5,-3,-2,-1,
-6,-6,-6,-6,-6,-6,-6,-6,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
6, 6, 6, 6, 6, 6, 6, 6,
1, 2, 3, 4, 5, 3, 2, 1};

std::string toChessNote(Vector2f p)
{
std::string s = "";
s += char(p.x/size+97);
s += char(7-p.y/size+49);
return s;
}

Vector2f toCoord(char a,char b)


{
int x = int(a) - 97;
int y = 7-int(b)+49;
return Vector2f(x*size,y*size);
}

void move(std::string str)


{
Vector2f oldPos = toCoord(str[0],str[1]);
Vector2f newPos = toCoord(str[2],str[3]);

for(int i=0;i<32;i++)
if (f[i].getPosition()==newPos) f[i].setPosition(-100,-100);

for(int i=0;i<32;i++)
if (f[i].getPosition()==oldPos) f[i].setPosition(newPos);

//castling //if the king didn't move


if (str=="e1g1") if (position.find("e1")==-1) move("h1f1");
if (str=="e8g8") if (position.find("e8")==-1) move("h8f8");
if (str=="e1c1") if (position.find("e1")==-1) move("a1d1");
if (str=="e8c8") if (position.find("e8")==-1) move("a8d8");
}

void loadPosition()
{
int k=0;
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{
int n = board[i][j];
if (!n) continue;
int x = abs(n)-1;
int y = n>0?1:0;
f[k].setTextureRect( IntRect(size*x,size*y,size,size) );
f[k].setPosition(size*j,size*i);
k++;
}

for(int i=0;i<position.length();i+=5)
move(position.substr(i,4));
}

int main()
{
RenderWindow window(VideoMode(504, 504), "The Chess! (press SPACE)");

ConnectToEngine("stockfish.exe");

Texture t1,t2;
t1.loadFromFile("images/figures.png");
t2.loadFromFile("images/board.png");

for(int i=0;i<32;i++) f[i].setTexture(t1);


Sprite sBoard(t2);

loadPosition();

bool isMove=false;
float dx=0, dy=0;
Vector2f oldPos,newPos;
std::string str;
int n=0;

while (window.isOpen())
{
Vector2i pos = Mouse::getPosition(window) - Vector2i(offset);

Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();

////move back//////
if (e.type == Event::KeyPressed)
if (e.key.code == Keyboard::BackSpace)
{ if (position.length()>6) position.erase(position.length()-6,5);
loadPosition();}

/////drag and drop///////


if (e.type == Event::MouseButtonPressed)
if (e.key.code == Mouse::Left)
for(int i=0;i<32;i++)
if (f[i].getGlobalBounds().contains(pos.x,pos.y))
{
isMove=true; n=i;
dx=pos.x - f[i].getPosition().x;
dy=pos.y - f[i].getPosition().y;
oldPos = f[i].getPosition();
}

if (e.type == Event::MouseButtonReleased)
if (e.key.code == Mouse::Left)
{
isMove=false;
Vector2f p = f[n].getPosition() + Vector2f(size/2,size/2);
newPos = Vector2f( size*int(p.x/size), size*int(p.y/size) );
str = toChessNote(oldPos)+toChessNote(newPos);
move(str);
if (oldPos!=newPos) position+=str+" ";
f[n].setPosition(newPos);
}
}

//comp move
if (Keyboard::isKeyPressed(Keyboard::Space))
{
str = getNextMove(position);
oldPos = toCoord(str[0],str[1]);
newPos = toCoord(str[2],str[3]);

for(int i=0;i<32;i++) if (f[i].getPosition()==oldPos) n=i;

/////animation///////
for(int k=0;k<50;k++)
{
Vector2f p = newPos - oldPos;
f[n].move(p.x/50, p.y/50);
window.draw(sBoard);
for(int i=0;i<32;i++) f[i].move(offset);
for(int i=0;i<32;i++) window.draw(f[i]); window.draw(f[n]);
for(int i=0;i<32;i++) f[i].move(-offset);
window.display();
}

move(str); position+=str+" ";


f[n].setPosition(newPos);
}

if (isMove) f[n].setPosition(pos.x-dx,pos.y-dy);

////// draw ///////


window.clear();
window.draw(sBoard);
for(int i=0;i<32;i++) f[i].move(offset);
for(int i=0;i<32;i++) window.draw(f[i]); window.draw(f[n]);
for(int i=0;i<32;i++) f[i].move(-offset);
window.display();
}

CloseConnection();

return 0;
}

15.......................VOLLEYBALL............

#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
using namespace sf;

const float SCALE = 30.f;


const float DEG = 57.29577f;

b2Vec2 Gravity(0.f, 9.8f);


b2World World(Gravity);

void setWall(int x,int y,int w,int h)


{
b2PolygonShape gr;
gr.SetAsBox(w/SCALE,h/SCALE);

b2BodyDef bdef;
bdef.position.Set(x/SCALE, y/SCALE);

b2Body *b_ground = World.CreateBody(&bdef);


b_ground->CreateFixture(&gr,1);
}

int main()
{
RenderWindow window(VideoMode(800, 600), "Volleyball Game!");
window.setFramerateLimit(60);
window.setSize(Vector2u(800*0.8,600*0.8));

Texture t1,t2,t3;
t1.loadFromFile("images/background.png");
t2.loadFromFile("images/ball.png");
t3.loadFromFile("images/blobby.png");
t1.setSmooth(true);
t2.setSmooth(true);
t3.setSmooth(true);

Sprite sBackground(t1), sBall(t2), sPlayer(t3);


sPlayer.setOrigin(75/2,90/2);
sBall.setOrigin(32,32);

/////////box2d///////////
setWall(400,520,2000,10);
setWall(400, 450,10,170);
setWall(0,0,10,2000);
setWall(800,0,10,2000);

b2PolygonShape shape;
shape.SetAsBox(30/SCALE,30/SCALE);
b2BodyDef bdef;
bdef.type=b2_dynamicBody;
///players///////////////
b2Body *pBody[2];
for(int i=0;i<2;i++){
bdef.position.Set(20*i,2);
b2CircleShape circle;
circle.m_radius=32/SCALE;
circle.m_p.Set(0,13/SCALE);
pBody[i] = World.CreateBody(&bdef);
pBody[i]->CreateFixture(&circle,5);
circle.m_radius=25/SCALE;
circle.m_p.Set(0,-20/SCALE);
pBody[i]->CreateFixture(&circle,5);
pBody[i]->SetFixedRotation(true);
}
pBody[0]->SetUserData("player1");
pBody[1]->SetUserData("player2");

/// ball /////////////


bdef.position.Set(5,1);
b2CircleShape circle;
circle.m_radius=32/SCALE;
b2Body *b = World.CreateBody(&bdef);
b2FixtureDef fdef;
fdef.shape=&circle;
fdef.restitution=0.95;
fdef.density=0.2;
b->CreateFixture(&fdef);
b->SetUserData("ball");
/////////////////////////

bool onGround=0;

while (window.isOpen())
{
Event e;
while (window.pollEvent(e))
{
if (e.type == Event::Closed)
window.close();
}

for(int n=0;n<2;n++) // 2 - speed


World.Step(1/60.f, 8, 3);

//player1
b2Vec2 pos = pBody[0]->GetPosition();
b2Vec2 vel = pBody[0]->GetLinearVelocity();

if (Keyboard::isKeyPressed(Keyboard::Right)) vel.x=5;
if (Keyboard::isKeyPressed(Keyboard::Left)) vel.x=-5;
if (Keyboard::isKeyPressed(Keyboard::Up)) if (pos.y*SCALE>=463) vel.y=-
13;

if (!Keyboard::isKeyPressed(Keyboard::Right))
if (!Keyboard::isKeyPressed(Keyboard::Left))
vel.x=0;

pBody[0]->SetLinearVelocity(vel);

//player2
pos = pBody[1]->GetPosition();
vel = pBody[1]->GetLinearVelocity();

if (Keyboard::isKeyPressed(Keyboard::D)) vel.x=5;
if (Keyboard::isKeyPressed(Keyboard::A)) vel.x=-5;
if (Keyboard::isKeyPressed(Keyboard::W)) if (pos.y*SCALE>=463) vel.y=-
13;

if (!Keyboard::isKeyPressed(Keyboard::D))
if (!Keyboard::isKeyPressed(Keyboard::A))
vel.x=0;

pBody[1]->SetLinearVelocity(vel);

//ball max speed


vel = b->GetLinearVelocity();
if (vel.Length()>15) b->SetLinearVelocity( 15/vel.Length() * vel );

//////////Draw///////////////
window.draw(sBackground);

for (b2Body* it = World.GetBodyList(); it != 0; it = it->GetNext())


{
b2Vec2 pos = it->GetPosition();
float angle = it->GetAngle();

if (it->GetUserData()=="player1")
{
sPlayer.setPosition(pos.x*SCALE,pos.y*SCALE);
sPlayer.setRotation(angle*DEG);
sPlayer.setColor(Color::Red);
window.draw(sPlayer);
}

if (it->GetUserData()=="player2")
{
sPlayer.setPosition(pos.x*SCALE,pos.y*SCALE);
sPlayer.setRotation(angle*DEG);
sPlayer.setColor(Color::Green);
window.draw(sPlayer);
}

if (it->GetUserData()=="ball")
{
sBall.setPosition(pos.x*SCALE,pos.y*SCALE);
sBall.setRotation(angle*DEG);
window.draw(sBall);
}
}

window.display();
}
return 0;
}

16.......................ASTEROIDS.............

#include <SFML/Graphics.hpp>
#include <time.h>
#include <list>
using namespace sf;

const int W = 1200;


const int H = 800;

float DEGTORAD = 0.017453f;

class Animation
{
public:
float Frame, speed;
Sprite sprite;
std::vector<IntRect> frames;

Animation(){}

Animation (Texture &t, int x, int y, int w, int h, int count, float Speed)
{
Frame = 0;
speed = Speed;

for (int i=0;i<count;i++)


frames.push_back( IntRect(x+i*w, y, w, h) );

sprite.setTexture(t);
sprite.setOrigin(w/2,h/2);
sprite.setTextureRect(frames[0]);
}

void update()
{
Frame += speed;
int n = frames.size();
if (Frame >= n) Frame -= n;
if (n>0) sprite.setTextureRect( frames[int(Frame)] );
}

bool isEnd()
{
return Frame+speed>=frames.size();
}

};

class Entity
{
public:
float x,y,dx,dy,R,angle;
bool life;
std::string name;
Animation anim;

Entity()
{
life=1;
}

void settings(Animation &a,int X,int Y,float Angle=0,int radius=1)


{
anim = a;
x=X; y=Y;
angle = Angle;
R = radius;
}

virtual void update(){};

void draw(RenderWindow &app)


{
anim.sprite.setPosition(x,y);
anim.sprite.setRotation(angle+90);
app.draw(anim.sprite);

CircleShape circle(R);
circle.setFillColor(Color(255,0,0,170));
circle.setPosition(x,y);
circle.setOrigin(R,R);
//app.draw(circle);
}
virtual ~Entity(){};
};

class asteroid: public Entity


{
public:
asteroid()
{
dx=rand()%8-4;
dy=rand()%8-4;
name="asteroid";
}

void update()
{
x+=dx;
y+=dy;

if (x>W) x=0; if (x<0) x=W;


if (y>H) y=0; if (y<0) y=H;
}

};

class bullet: public Entity


{
public:
bullet()
{
name="bullet";
}

void update()
{
dx=cos(angle*DEGTORAD)*6;
dy=sin(angle*DEGTORAD)*6;
// angle+=rand()%7-3; /*try this*/
x+=dx;
y+=dy;

if (x>W || x<0 || y>H || y<0) life=0;


}

};

class player: public Entity


{
public:
bool thrust;

player()
{
name="player";
}
void update()
{
if (thrust)
{ dx+=cos(angle*DEGTORAD)*0.2;
dy+=sin(angle*DEGTORAD)*0.2; }
else
{ dx*=0.99;
dy*=0.99; }

int maxSpeed=15;
float speed = sqrt(dx*dx+dy*dy);
if (speed>maxSpeed)
{ dx *= maxSpeed/speed;
dy *= maxSpeed/speed; }

x+=dx;
y+=dy;

if (x>W) x=0; if (x<0) x=W;


if (y>H) y=0; if (y<0) y=H;
}

};

bool isCollide(Entity *a,Entity *b)


{
return (b->x - a->x)*(b->x - a->x)+
(b->y - a->y)*(b->y - a->y)<
(a->R + b->R)*(a->R + b->R);
}

int main()
{
srand(time(0));

RenderWindow app(VideoMode(W, H), "Asteroids!");


app.setFramerateLimit(60);

Texture t1,t2,t3,t4,t5,t6,t7;
t1.loadFromFile("images/spaceship.png");
t2.loadFromFile("images/background.jpg");
t3.loadFromFile("images/explosions/type_C.png");
t4.loadFromFile("images/rock.png");
t5.loadFromFile("images/fire_blue.png");
t6.loadFromFile("images/rock_small.png");
t7.loadFromFile("images/explosions/type_B.png");

t1.setSmooth(true);
t2.setSmooth(true);

Sprite background(t2);

Animation sExplosion(t3, 0,0,256,256, 48, 0.5);


Animation sRock(t4, 0,0,64,64, 16, 0.2);
Animation sRock_small(t6, 0,0,64,64, 16, 0.2);
Animation sBullet(t5, 0,0,32,64, 16, 0.8);
Animation sPlayer(t1, 40,0,40,40, 1, 0);
Animation sPlayer_go(t1, 40,40,40,40, 1, 0);
Animation sExplosion_ship(t7, 0,0,192,192, 64, 0.5);

std::list<Entity*> entities;

for(int i=0;i<15;i++)
{
asteroid *a = new asteroid();
a->settings(sRock, rand()%W, rand()%H, rand()%360, 25);
entities.push_back(a);
}

player *p = new player();


p->settings(sPlayer,200,200,0,20);
entities.push_back(p);

/////main loop/////
while (app.isOpen())
{
Event event;
while (app.pollEvent(event))
{
if (event.type == Event::Closed)
app.close();

if (event.type == Event::KeyPressed)
if (event.key.code == Keyboard::Space)
{
bullet *b = new bullet();
b->settings(sBullet,p->x,p->y,p->angle,10);
entities.push_back(b);
}
}

if (Keyboard::isKeyPressed(Keyboard::Right)) p->angle+=3;
if (Keyboard::isKeyPressed(Keyboard::Left)) p->angle-=3;
if (Keyboard::isKeyPressed(Keyboard::Up)) p->thrust=true;
else p->thrust=false;

for(auto a:entities)
for(auto b:entities)
{
if (a->name=="asteroid" && b->name=="bullet")
if ( isCollide(a,b) )
{
a->life=false;
b->life=false;

Entity *e = new Entity();


e->settings(sExplosion,a->x,a->y);
e->name="explosion";
entities.push_back(e);

for(int i=0;i<2;i++)
{
if (a->R==15) continue;
Entity *e = new asteroid();
e->settings(sRock_small,a->x,a->y,rand()%360,15);
entities.push_back(e);
}

if (a->name=="player" && b->name=="asteroid")


if ( isCollide(a,b) )
{
b->life=false;

Entity *e = new Entity();


e->settings(sExplosion_ship,a->x,a->y);
e->name="explosion";
entities.push_back(e);

p->settings(sPlayer,W/2,H/2,0,20);
p->dx=0; p->dy=0;
}
}

if (p->thrust) p->anim = sPlayer_go;


else p->anim = sPlayer;

for(auto e:entities)
if (e->name=="explosion")
if (e->anim.isEnd()) e->life=0;

if (rand()%150==0)
{
asteroid *a = new asteroid();
a->settings(sRock, 0,rand()%H, rand()%360, 25);
entities.push_back(a);
}

for(auto i=entities.begin();i!=entities.end();)
{
Entity *e = *i;

e->update();
e->anim.update();

if (e->life==false) {i=entities.erase(i); delete e;}


else i++;
}

//////draw//////
app.draw(background);
for(auto i:entities) i->draw(app);
app.display();
}

return 0;
}

You might also like