Instantly share code, notes, and snippets.

Embed
What would you like to do?
AuraSnakegame
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Board.cpp *
* Made by Popa Aurelia *
******************************************************************************************/
#include "Board.h"
#include "Location.h"
#include "Graphics.h"
#include<assert.h>
Board::Board(Graphics& gfx)
:
gfx ( gfx )
{
}
void Board::DrawCell( const Location& loc, Color c )
{
// pt ca cineva sa nu poata chema Draw dinafara board-ului
assert( loc.x >= 0 );
assert( loc.x < width );
assert( loc.y >= 0 );
assert( loc.y < height );
// gridul de celule
// dimension = 20 pixeli
const int off_x = x + borderWidth + borderPadding;
const int off_y = y + borderWidth + borderPadding;
// 2 pixeli intre 2 celule
gfx.DrawRectDim(loc.x * dimension + off_x + paddingCells, loc.y * dimension + off_y + paddingCells,
dimension - 2 * paddingCells, dimension - 2 * paddingCells, c);
int Board::GetGridWidth() const
{
return width;
}
int Board::GetGridHeight() const
{
return height;
}
bool Board::IsInsideBoard(const Location& loc) const
{
// ne asiguram ca ramanem in interiorul board-ului
return loc.x >= 0 && loc.x < width &&
loc.y >= 0 && loc.y < height ;
}
void Board::DrawBorder()
{
const int top = y;
const int left = x;
const int bottom = top + ( borderWidth + borderPadding ) * 2 + height * dimension;
const int right = left + ( borderWidth + borderPadding ) * 2 + width * dimension;
// desenam cele 4 dreptunghiuri
// top
gfx.DrawRect( left, top, right, top + borderWidth, borderColor );
// left
gfx.DrawRect( left, top + borderWidth, left + borderWidth, bottom - borderWidth, borderColor );
// bottom
gfx.DrawRect( left, bottom - borderWidth, right, bottom, borderColor );
// right
gfx.DrawRect( right - borderWidth, top + borderWidth, right, bottom - borderWidth, borderColor );
}
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Board.h *
* Made by Popa Aurelia *
******************************************************************************************/
#pragma once
#include "Graphics.h"
#include "Location.h"
class Board
{
public :
// constructor care initializeaza grafica
Board( Graphics& gfx );
// deseneaza patrate pe ecran, locatia o dam prin referinta
// schimba membrii din grafica
void DrawCell( const Location& loc, Color c );
// luam dimensiunile gridului
int GetGridWidth() const;
int GetGridHeight() const;
bool IsInsideBoard( const Location& loc ) const;
// facem 4 dreptunghiuri in jurul la board 1sus-1jos-1dr-1stg
void DrawBorder();
private:
// constexpr specifier este posibil sa evaluam valoarea functiei sau variabilei in timpul compilarii
static constexpr Color borderColor = Colors::Cyan;
static constexpr int paddingCells = 1;
static constexpr int dimension = 20;// dimensiunea unei celule a boardului
static constexpr int height = 24; // inaltime board
static constexpr int width = 32; // latime board
//valori pt dreptunghiurile ce delimiteaza boardul
static constexpr int borderWidth = 4;
// padding dintre border si board
static constexpr int borderPadding = 2;
// valori pe care le folosim sa desenam boardul
static constexpr int x = 70;
static constexpr int y = 50;
Graphics& gfx; // stocam o copie locala pt performanta ,sau convenienta ca acum, a referintei obiectului de grafica gfx;
};
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Game.cpp *
* Made by Popa Aurelia *
******************************************************************************************/
#include "MainWindow.h"
#include "Game.h"
#include "SpriteCodex.h"
Game::Game( MainWindow& wnd )
:
wnd( wnd ),
gfx( wnd ),
brd( gfx ),
rng( std::random_device()() ),
// initializam snake
sarpe({ 2,2 }),
goal( rng,brd,sarpe )
{
}
void Game::Go()
{
gfx.BeginFrame();
UpdateModel();
ComposeFrame();
gfx.EndFrame();
}
//scope resolution operator :: identifica carei clasei ii apartine functia
void Game::UpdateModel()
{
if ( gameStarted ) // daca a inceput jocul
{
if ( !gameOver )
{
// tastele seteaza o locatie
if ( wnd.kbd.KeyIsPressed( VK_LEFT ))
{
delta_loc = { -1,0 };
}
else if ( wnd.kbd.KeyIsPressed( VK_RIGHT ))
{
delta_loc = { 1,0 };
}
else if ( wnd.kbd.KeyIsPressed( VK_UP ))
{
delta_loc = { 0,-1 };
}
else if ( wnd.kbd.KeyIsPressed( VK_DOWN ))
{
delta_loc = { 0,1 };
}
// pt ca snake sa nu se miste prea repede
snakeMoveCounter++;
if ( snakeMoveCounter >= snakeMovePeriod )
{
// se reseteaza counterul
snakeMoveCounter = 0;
// verificam daca miscarea la snake il va omora = sarpe.GetNextHeadLoc
const Location next = sarpe.GetNextHeadLoc( delta_loc );
// daca capul sarpelui nu este in interiorul la board atunci snake este mort
// verificam pozitia capului snake cu vechea pozitie netinand cont de coada
// care se va misca si ea in alta pozitie
if ( !brd.IsInsideBoard( next ) || sarpe.IsInTileExceptEnd( next ))
{
gameOver = true;
}
else // facem update la snake
{
// vrem sa apara un alt patratel adica respawn dupa ce ne miscam, dupa ce crestem cu un patratel
// vrem pozitia update a snake pt testele de respawn
const bool eating = next == goal.GetLocation();
if ( eating )
{
sarpe.Grow();
}
// snake primeste update in functie de delta, mutam snake
sarpe.Moveby(delta_loc);
// daca mancam dupa ce ne-am miscat
if ( eating )
{
goal.Respawn( rng, brd, sarpe );
}
}
}
snakeSpeedUpCounter++;
if ( snakeSpeedUpCounter >= snakeSpeedUpPeriod )
{
snakeSpeedUpCounter = 0;
snakeMovePeriod = std::max( snakeMovePeriod -1, snakeMovePeriodMin );
}
}
}
else
{
gameStarted = wnd.kbd.KeyIsPressed( VK_RETURN );
}
}
void Game::ComposeFrame()
{
if ( gameStarted ) // daca a inceput jocul desenam sarpele si goalul, iar daca s-a terminat jocul afiseaza game over
{
sarpe.Draw( brd );
goal.Draw( brd );
if ( gameOver )
{
SpriteCodex::DrawGameOver( 320, 200, gfx );
}
brd.DrawBorder();
}
else // nu a inceput jocul
{
SpriteCodex::DrawTitle( 290, 225, gfx );
}
}
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Game.h *
* Made by Popa Aurelia *
******************************************************************************************/
#pragma once
#include "Keyboard.h"
#include "Mouse.h"
#include "Graphics.h"
#include "Board.h"
#include <random>
#include "Snake.h"
#include "Goal.h"
class Game
{
public:
Game( class MainWindow& wnd );
Game( const Game& ) = delete;
Game& operator=( const Game& ) = delete;
void Go();
private:
void ComposeFrame();
void UpdateModel();
/********************************/
/* User Functions */
/********************************/
private:
MainWindow& wnd;
Graphics gfx;
/********************************/
/* User Variables */
Board brd;
Snake sarpe;
//initializat inainte de goal avem nevoie de el pt initializare
std::mt19937 rng;
// obiectul goal trebuie sa fie creat dupa board si sarpe de care avem nevoie pt initializare goal
Goal goal;
Location delta_loc = { 1,0 };
// 20 frames = 3 miscari / sec
static constexpr int snakeMovePeriodMin = 4;
int snakeMovePeriod = 20;
int snakeMoveCounter = 0;
static constexpr int snakeSpeedUpPeriod = 180;// creste viteza odata la 3 secunde- 60 frames /sec
int snakeSpeedUpCounter = 0;
bool gameOver = false;
bool gameStarted = false;
/********************************/
};
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Game.cpp *
* Made by Popa Aurelia *
******************************************************************************************/
#include "Goal.h"
Goal::Goal( std::mt19937& rng, const Board& brd, const Snake& snake )
{
Respawn( rng, brd, snake );
}
void Goal::Respawn( std::mt19937& rng, const Board& brd, const Snake& snake )
{
// sunt asezate aleator x si y prin crearea a 2 distributii
std::uniform_int_distribution<int> xDist( 0, brd.GetGridWidth() - 1 );
std::uniform_int_distribution<int> yDist( 0, brd.GetGridHeight() - 1 );
Location newLoc;
// vom crea patratelul inafara zonelor in care este sarpele
do
{
newLoc.x = xDist( rng );
newLoc.y = yDist( rng );
} while ( snake.IsInTile( newLoc ));
// cat timp snake ocupa locatia care a fost creata ca newLoc , genereaza alta locatie random
loc = newLoc;
}
void Goal::Draw( Board& brd ) const
{
brd.DrawCell( loc, c );
}
// returneaza locatia in care se gaseste patratelul
const Location& Goal::GetLocation() const
{
return loc;
}
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Goal.h *
* Made by Popa Aurelia *
******************************************************************************************/
#pragma once
#include "Snake.h"
#include "Board.h"
#include <random>
class Goal
{
public:
// constructor va avea aceleasi informatii ca Respawn pe care o apeleaza
// seteaza pozitia initiala a sarpelui
Goal( std::mt19937& rng, const Board& brd, const Snake& snake );
// pt aparitia unui patratel aleator pe ecran
void Respawn( std::mt19937& rng, const Board& brd, const Snake& snake );
void Draw( Board& brd ) const;
const Location& GetLocation()const;
private:
static constexpr Color c = Colors::Red;
// pozitia
Location loc;
};
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Snake.cpp *
* Made by Popa Aurelia *
******************************************************************************************/
#include "Snake.h"
#include<assert.h>
// constructor
Snake::Snake( const Location& loc )
{
constexpr int nrBodyColors = 4;
constexpr Color bodyColours[nrBodyColors] = { { 10,100,32 },
{ 10,130,48 },
{ 18,160,48 },
{ 10,130,48 }
};
// trecem prin toate segmentele array-ului si initializam culoarea fiecarui segment
for (int i = 0; i < nrSegmentsMax; i++)
{
// trecem prin toate indexurile si de folosim remainder de index avem doar 4 variante
segments[i].InitBody( bodyColours[i % nrBodyColors] );
}
// setam locatia care a fost data de constructor pt capul snake-ului
segments[0].InitHead( loc );
}
void Snake::Moveby( const Location& delta_loc )
{
// incepem cu ultimul segment din snake care este folosit si pana la segmentul de la cap , nu procesam capul
for ( int i = nrSegments - 1; i > 0; i-- )
{
// segmentul din spate il urmareste pe cel din fata lui
segments[i].Follow( segments[i-1] );
}
// muta tot snake-ul in functie de valoarea delta_loc
segments[0].Moveby( delta_loc );
}
Location Snake::GetNextHeadLoc( const Location& delta_loc ) const
{
// headPozition este o copie a locatiei capului
// copy constructor este un membru automat creat de compiler
// initializam headPozition ca o copie a locatiei capului
// dupa ce este adaugata delta location adica noua pozitie la vechea pozitie
// daca am incerca sa returnam valoarea la delta_loc avand in vedere ca este o variabila locala
// care dispare dupa ce functia returneaza ar returna o referinta invalida
Location headPozition( segments[0].GetLocation() );
headPozition.Add( delta_loc );
return headPozition;
}
void Snake::Grow()
{
if ( nrSegments < nrSegmentsMax )
{
// apoi incrementam nr de segmente folosite
nrSegments++;
}
}
void Snake::Draw( Board& brd ) const
{
for ( int i = 0; i < nrSegments; i++ )
{
// desenam fiecare segment prin care trecem
segments[i].Draw( brd );
}
}
bool Snake::IsInTileExceptEnd( const Location& target ) const
{
for ( int i = 0; i < nrSegments - 1 ; i++ )
{
// daca snake este in tile-ul care este target
if ( segments[i].GetLocation() == target )
{
return true;
}
}
return false;
}
bool Snake::IsInTile( const Location& target ) const
{
for ( int i = 0; i < nrSegments; i++ )
{
// daca snake este in tile-ul care este target
if ( segments[i].GetLocation() == target )
{
return true;
}
}
return false;
}
void Snake::Segment::InitHead( const Location& in_loc )
{
// functii automate de default ale constructorului daca incercam sa le folosim
// atribuim un obiect altui obiect cu ajutorul default compilerului numit asigment operator
// ia datele de la un obiect si le atribuie celuilalt obiect
// x din in_loc se duce in x din loc
loc = in_loc;
// the inner class can access var of the top class
c = Snake::headColor;
}
void Snake::Segment::InitBody( Color c_in )
{
c = c_in;
}
void Snake::Segment::Follow( const Segment& next )
{
// atribuim in locatie urmatoarea locatie
loc = next.loc;
}
// mutam snake o patratica orizontal sau vertical
void Snake::Segment::Moveby( const Location& delta_loc )
{
assert( abs( delta_loc.x ) + abs( delta_loc.y ) == 1 );
// adaugam o locatie
loc.Add( delta_loc );
}
void Snake::Segment::Draw( Board & brd ) const
{
brd.DrawCell( loc, c );
}
// returneaza o referinta constanta la locatia segmentului
const Location& Snake::Segment::GetLocation() const
{
return loc;
}
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Snake.h *
* Made by Popa Aurelia *
******************************************************************************************/
#pragma once
#include "Board.h"
// va fi un array de obiecte Segment
class Snake
{
private:
// inner class care ajuta la crearea de Snake
// partile componente ale Snake-ului
class Segment
{
public:
// capul tine locatia
void InitHead( const Location& in_loc );
// urmareste pozitia segmentului din fata
void InitBody( Color c );
// snake se misca incepand cu coada care vine in locatia segmentului urmator,
//iar primul segment capul se misca in delta_loc
void Follow( const Segment& next );
// muta un segment cu o anumita distanta
void Moveby( const Location& delta_loc ) ;
// desenam un segment
void Draw( Board& brd ) const;
// luam valoarea ca referinta
const Location& GetLocation() const;
private:
Location loc;
Color c;
};
public :
// constructor pt creare snake, locatia unde incepe snake
Snake( const Location& loc );
// delta_loc reprezinta zona in care ajunge snake
// snake se misca incepand cu coada care vine in locatia segmentului urmator,
// iar primul segment capul se misca in delta_loc , pt delta_loc( 0,1 ) se misca in jos
void Moveby( const Location& delta_loc );
// verificam care este pozitia capului la snake dupa ce aplicam delta_loc daca ajunge intr-o situatie in care poate muri
Location GetNextHeadLoc( const Location& delta_loc ) const;
void Grow();
// o functie care deseneaza snake-ul pe board
void Draw( Board& brd ) const;
bool IsInTileExceptEnd(const Location& target)const;
bool IsInTile(const Location& target)const;
private:
// facem o diferenta intre cap si corp ca si culoare
static constexpr Color headColor = Colors::Yellow;
// cate segmente poate avea snake folosite sau nefolosite
static constexpr int nrSegmentsMax = 100;
// cream un array de segmente
Segment segments[nrSegmentsMax];
// nr de segmente care sunt folosite momentan
int nrSegments = 1;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment