text:
<repo_name>spicycoder/TaleOfTheWarrior<file_sep>/GameEngine.Specs/WarriorElf.feature
Feature: Warrior elf character design
	Character design of the warrior elf
	Who eats, fights and has big ears

Scenario: Initial health is 30
	Given A new player
	Then Health should be 30

Scenario Outline: Feed Food
	Given A new player
	When Eat a <food>
	Then Health should be <health>
	Examples:
	| food    | health |
	| Carrot  | 40     |
	| Bread   | 50     |
	| Portion | 60     |

Scenario Outline: Feed multiple food
	Given A new player
	When Eat a <food1>
	And Eat a <food2>
	Then Health should be <health>
	Examples:
	| food1  | food2   | health |
	| Carrot | Bread   | 60     |
	| Carrot | Portion | 70     |
	| Bread  | Portion | 80     |
	| Wine   | Wine    | 100    |

Scenario Outline: When attacked
	Given A new player
	When Attacked <count> times
	Then Health should be <health>
	Examples:
	| count | health |
	| 1     | 20     |
	| 2     | 10     |
	| 3     | 0      |
	| 5     | 0      |<file_sep>/GameEngine.Specs/WarriorElfCharacterDesignSteps.cs
using NFluent;
using System;
using System.Linq;
using TechTalk.SpecFlow;

namespace GameEngine.Specs
{
    [Binding]
    public class WarriorElfCharacterDesignSteps
    {
        private ElfWarrior _player;

        [Given(@"A new player")]
        public void GivenANewPlayer()
        {
            _player = new ElfWarrior();
        }

        [When(@"Eat a (.*)")]
        public void WhenEatA(FoodTypes food)
        {
            _player.Eat(food);
        }

        [Then(@"Health should be (.*)")]
        public void ThenHealthShouldBe(int health)
        {
            Check.That<int>(_player.Health).IsEqualTo(health);
        }

        [When(@"Attacked (.*) times")]
        public void WhenAttackedTimes(int count)
        {
            for (int i = 0; i < count; i++)
            {
                _player.Hit();
            }
        }

    }
}
<file_sep>/GameEngine.Build/coverage-and-documentation.bat
REM Create a 'CodeCoverage' folder if it does not exist
if not exist "%~dp0CodeCoverage" mkdir "%~dp0CodeCoverage"

REM Remove any previous test execution files to prevent issues overwriting
IF EXIST "%~dp0Testreport.trx" del "%~dp0Testreport.trx%"

REM Remove any previously created test output directories
CD %~dp0
FOR /D /R %%X IN (%USERNAME%*) DO RD /S /Q "%%X"

REM - Run Code Coverage
Call :RunCodeCoverage

Rem - Generate & Launch Coverage Report
Call :GenerateAndLaunchCoverageReport

Rem - Generate & Launch Pickles Documents
Call :GenerateAndlaunchPicklesDocuments

:RunCodeCoverage
"%~dp0..\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"%VS140COMNTOOLS%\..\IDE\mstest.exe" ^
-targetargs:"/testcontainer:\"%~dp0..\GameEngine.Specs\bin\Debug\GameEngine.Specs.dll\" /resultsfile:\"%~dp0Testreport.trx\"" ^
-filter:"+[GameEngine*]* -[*]*Steps" ^
-mergebyhash ^
-skipautoprops ^
-output:"%~dp0CodeCoverage\GameEngine.Specs.xml"
exit /b %errorlevel%

:GenerateAndLaunchCoverageReport
"%~dp0..\packages\ReportGenerator.3.1.2\tools\ReportGenerator.exe" ^
-reports:"%~dp0CodeCoverage\GameEngine.Specs.xml" ^
-targetdir:"%~dp0CodeCoverage\ReportGenerator Output"

start "report" "%~dp0\CodeCoverage\ReportGenerator Output\index.htm"
exit /b %errorlevel%

:GenerateAndlaunchPicklesDocuments
"%~dp0..\packages\pickles.commandline.2.20.0\tools\pickles.exe" ^
-f:"%~dp0..\GameEngine.Specs" ^
-o:"%~dp0GeneratedReports\Html" ^
--trfmt:"mstest" ^
--lr:"%~dp0Testreport.trx" ^
--df:"Html"

start "document" "%~dp0\GeneratedReports\Html\index.html"
exit /b %errorlevel%<file_sep>/GamePlay/MainWindow.xaml.cs
using MahApps.Metro.Controls;
using System.IO;
using System.Reflection;
using System.Windows;
using XamlAnimatedGif;

namespace GamePlay
{
    public partial class MainWindow : MetroWindow
    {
        private int _health = 0;

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _health = 30;
            UpdateHealth();
        }

        private void UpdateHealth(int health = 0)
        {
            _health += health;

            if (_health <= 0)
            {
                MessageBox.Show("Game over", "Wasted", MessageBoxButton.OK, MessageBoxImage.Information);
                this.Close();
            }
            else if (_health >= 100)
            {
                _health = 100;
                FoodPopup.IsEnabled = false;
            }
            else
            {
                FoodPopup.IsEnabled = true;
            }

            var fileName = _health < 50 ? "Media/elf.gif" : "Media/jump.gif";

            if (WeaponToggleButton.IsChecked.GetValueOrDefault())
            {
                fileName = "Media/arrow.gif";
            }

            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
            AnimationBehavior.SetSourceUri(CharacterMedia, new System.Uri(path));

            this.HealthLabel.Text = _health.ToString();
            this.HealthProgress.Value = _health;
        }

        private void WeaponToggleButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateHealth();
        }

        private void CarrotButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateHealth(10);
        }

        private void BreadButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateHealth(20);
        }

        private void PortionButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateHealth(30);
        }

        private void AttackButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateHealth(-10);
        }

        private void WineButton_Click(object sender, RoutedEventArgs e)
        {
            UpdateHealth(50);
        }
    }
}<file_sep>/README.md
# TaleOfTheWarrior
![Alt Demo](demo.gif)

# Status
- [ ] Build
- [x] Code Coverage with reports
- [x] Live Documentation
<file_sep>/GameEngine/Food.cs
using System.Collections.Generic;

namespace GameEngine
{
    public enum FoodTypes
    {
        Carrot,
        Bread,
        Portion,
        Wine
    }

    public class Food
    {
        public static readonly Dictionary<FoodTypes, int> CalariesIndex =
            new Dictionary<FoodTypes, int>
            {
                { FoodTypes.Carrot, 10 },
                { FoodTypes.Bread, 20 },
                { FoodTypes.Portion, 30 },
                { FoodTypes.Wine, 40 }
            };
    }
}<file_sep>/GameEngine/ElfWarrior.cs
using System;

namespace GameEngine
{
    public class ElfWarrior
    {
        public int Health { get; set; }

        public ElfWarrior()
        {
            Health = 30;
        }

        public void Eat(FoodTypes food)
        {
            Health = Math.Min(Health + Food.CalariesIndex[food], 100);
        }

        public void Hit()
        {
            Health = Math.Max(Health - 10, 0);
        }
    }
}

languages: C# Markdown Batchfile Gherkin

repo_language: C#

repo_name: spicycoder/TaleOfTheWarrior


text:
<file_sep>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
#include <iostream>

#include "CentralSystem.h"

#include "Ships.h"
#include "EventDispatcher.h"
#include "FactionManager.hpp"
#include "HUD.hpp"
#include <stdlib.h>
#include <time.h>
#include "Textures.hpp"

using namespace std;

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

    CentralSystem *cs = new CentralSystem;
    cs->setScreenSize(700,700);

    sf::RenderWindow window(sf::VideoMode(cs->winWidth, cs->winHeight), "Xeddos v0.1.4: Build Mode", sf::Style::Default, sf::ContextSettings(32));
    window.setKeyRepeatEnabled(false);
    sf::View view;
    sf::View buildView;//TODO move to view manager

    // Initialize the view to a rectangle located at (0, 0) and with a size of 300x300
    view.reset(sf::FloatRect(0, 0, cs->winWidth, cs->winHeight));
    // Set its target viewport to be half of the window
    view.setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));

    // Initialize the view to a rectangle located at (0, 0) and with a size of 300x300
    buildView.reset(sf::FloatRect(0, 0, cs->winWidth, cs->winHeight));
    // Set its target viewport to be half of the window
    buildView.setViewport(sf::FloatRect(0.f, 0.f, 1.f, 1.f));

    buildView.move(-cs->winWidth/2, -cs->winHeight/2);

    cs->mSFWindow = &window;
    cs->mSFView = &view;
    cs->mSFBuildView = &buildView;

    HUD hud(cs);
    hud.display( sf::String("Controls: Space for Build Mode, W, A, S, D, Q, E, F, B, Arrow keys, Ctrl, LShift") );

    Ship *sh;
    sh = new MatrixShip();
    sh->init(cs, "Player Ship");
    sh->build(MatrixShip::PROBE);
    sh->setPosition(sf::Vector2f(250,450));
    sh->setOwnership(FactionManager::getPlayerEntityFaction());
    sh->boardPlayer();
    cs->entities.push_back(sh);

    sh = new Ship();
    sh->init(cs, "Pirate");
    sh->setPosition(sf::Vector2f(250,50));
    sh->setRotation(180);
    sh->setOwnership(FactionManager::getPirateFaction());
    cs->entities.push_back(sh);

    EventDispatcher ds(cs);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {

            if (event.type == sf::Event::Closed) {
                window.close();
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
                glViewport(0, 0, event.size.width, event.size.height);
            }
            else if (event.type == sf::Event::KeyPressed)
            {
                ds.keyPressed(event);
            }
            else if (event.type == sf::Event::KeyReleased)
            {
                ds.keyReleased(event);
            }
            else if (event.type == sf::Event::MouseButtonPressed)
            {
                ds.mouseButtonPressed(event);
            }
            else if (event.type == sf::Event::MouseButtonReleased)
            {
                ds.mouseButtonReleased(event);
            }
        }
        ds.tick();
        cs->tick();

        // Apply view
        switch (cs->mode) {
        case CentralSystem::MODE_PLAY:
            window.setView(view);
            break;
        case CentralSystem::MODE_BUILD:
            window.setView(buildView);
            break;
        }

        window.clear();
        cs->draw();

        window.setView(window.getDefaultView());
        hud.draw();

        window.display();

        // Set the default view back
        window.setView(window.getDefaultView());
    }

    return 0;
}

//TODO pause while build mode
<file_sep>

#include "BuildSystem.hpp"
#include "CentralSystem.h"

void BuildSystem::mouseButtonPressed(sf::Event event) {
    if (event.mouseButton.x < 30) {
        elementsPanel->click(event);
    } else {
    	cs->getPlayerEntity()->mouseButtonPressed(event);
    }
}

void BuildSystem::mouseButtonReleased(sf::Event event) {
    cs->getPlayerEntity()->mouseButtonReleased(event);
}

<file_sep>#pragma once

#include "Entity.hpp"
#include "Character.hpp"

class Player : public Character {
public:
	Player() {
		shape.setFillColor(sf::Color(70,70,240));
	}
};

<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include "BaseObjects.hpp"
#include "CentralSystem.h"
#include "Entity.hpp"
#include "MultipartObject.hpp"

class Station : public NamedEntity, public StaticSpaceObject, public MultipartObject {
  CentralSystem *cs;
  sf::RectangleShape *body;
public:
  Station();
  Station(CentralSystem *cs);
  void rotate(float angle);
  void setRotation(float angle);
  void draw();
};

class TradeStation : public Station
{

};

class PirateStation : public Station {

};
<file_sep>
#include <SFML/Graphics.hpp>
#include "Stations.hpp"

Station::Station(CentralSystem *cs) {
    this->cs = cs;
    body = new sf::RectangleShape();
    body->setSize(sf::Vector2f(60, 50));
    body->setOrigin(30, 25);
    body->setPosition(100, 100);
}

void Station::rotate(float angle) {
    body->rotate(angle);
}

void Station::setRotation(float angle) {
    body->setRotation(angle);
}

void Station::draw() {
    //for (std::vector<sf::RectangleShape*>::iterator it = st.shapes.begin() ;
    //    it != st.shapes.end(); ++it)
    //{
        cs->mSFWindow->draw(*body);
    //}
}
<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include "CentralSystem.h"

class HUD {
  sf::Text text;
  sf::Font font;
  CentralSystem *cs;
  sf::RectangleShape viewFollow;

public:
  HUD(CentralSystem *cs): viewFollow(sf::Vector2f(12,10)) {
    this->cs = cs;
    if (!font.loadFromFile("media/fonts/orbitron-medium.otf"))
    {
         // error...
    }

    cs->defaultFont = font; // TODO move inside CS

    // select the font
    text.setFont(font); // font is a sf::Font

    // set the character size
    text.setCharacterSize(12); // in pixels, not points!

    // set the color
    text.setColor(sf::Color::White);

    viewFollow.setOutlineColor(sf::Color::White);
    viewFollow.setOutlineThickness(1);
    viewFollow.setFillColor(sf::Color::Transparent);
    viewFollow.setPosition(cs->winWidth-15, cs->winHeight-15);

  }

  void display(sf::String message) {
    // set the string to display
    text.setString(message);

  }

  void draw();
};
<file_sep>
#include <iostream>
#include <SFML/Graphics.hpp>
#include "EventDispatcher.h"
#include "BuildSystem.hpp"

using namespace std;

    EventDispatcher::EventDispatcher(CentralSystem *cs) {
        this->cs = cs;
    }

    void EventDispatcher::keyPressed(sf::Event event) {
        switch (event.key.code) {
            case sf::Keyboard::A:
                keyStates[sf::Keyboard::A] = true;
                break;
            case sf::Keyboard::D:
                keyStates[sf::Keyboard::D] = true;
                break;
            case sf::Keyboard::W:
                keyStates[sf::Keyboard::W] = true;
                break;
            case sf::Keyboard::S:
                keyStates[sf::Keyboard::S] = true;
                break;
            case sf::Keyboard::Q:
                keyStates[sf::Keyboard::Q] = true;
                break;
            case sf::Keyboard::E:
                keyStates[sf::Keyboard::E] = true;
                break;
            case sf::Keyboard::B:
                break;
            case sf::Keyboard::LControl:
                if (cs->currentEntity())
                cs->currentEntity()->mainAction();
                break;
            case sf::Keyboard::Space:
                break;
            case sf::Keyboard::Left:
                keyStates[sf::Keyboard::Left] = true;
                break;
            case sf::Keyboard::Right:
                keyStates[sf::Keyboard::Right] = true;
                break;
            case sf::Keyboard::Up:
                keyStates[sf::Keyboard::Up] = true;
                break;
            case sf::Keyboard::Down:
                keyStates[sf::Keyboard::Down] = true;
                break;
        }
    }

    void EventDispatcher::keyReleased(sf::Event event) {
        switch (event.key.code) {
            case sf::Keyboard::A:
                keyStates[sf::Keyboard::A] = false;
                break;
            case sf::Keyboard::D:
                keyStates[sf::Keyboard::D] = false;
                break;
            case sf::Keyboard::W:
                keyStates[sf::Keyboard::W] = false;
                break;
            case sf::Keyboard::S:
                keyStates[sf::Keyboard::S] = false;
                break;
            case sf::Keyboard::Q:
                keyStates[sf::Keyboard::Q] = false;
                break;
            case sf::Keyboard::E:
                keyStates[sf::Keyboard::E] = false;
                break;
            case sf::Keyboard::B:
                cs->cmdBoard();
                break;
            case sf::Keyboard::Space:
                cs->toggleBuildMode();
                break;
            case sf::Keyboard::LShift:
                //brakes
                break;
            case sf::Keyboard::F:
                cs->toggleViewFollow();
                break;
            case sf::Keyboard::Left:
                keyStates[sf::Keyboard::Left] = false;
                break;
            case sf::Keyboard::Right:
                keyStates[sf::Keyboard::Right] = false;
                break;
            case sf::Keyboard::Up:
                keyStates[sf::Keyboard::Up] = false;
                break;
            case sf::Keyboard::Down:
                keyStates[sf::Keyboard::Down] = false;
                break;
        }
    }

    void EventDispatcher::mouseButtonPressed(sf::Event event) {
        if (!cs->currentEntity()) return;
        switch (cs->mode) {
            case CentralSystem::MODE_PLAY:
                if (event.mouseButton.button == sf::Mouse::Left)
                {
                    cs->currentEntity()->cmdLMB(sf::Vector2f(event.mouseButton.x, event.mouseButton.y));
                }
                if (event.mouseButton.button == sf::Mouse::Right)
                {
                    cs->currentEntity()->cmdRMB(sf::Vector2f(event.mouseButton.x, event.mouseButton.y));
                }
                break;
            case CentralSystem::MODE_BUILD:
                cs->buildSystem->mouseButtonPressed(event);
                break;
        }
    }

    void EventDispatcher::mouseButtonReleased(sf::Event event) {

    }

    void EventDispatcher::tick() {
        if(!cs->getPlayerEntity())return;
        if(keyStates[sf::Keyboard::W]) {
                cs->getPlayerEntity()->manualMove(0,-1);
                if (cs->viewFollowing){
                    cs->moveView(0,-1);
                }
        }
        if (keyStates[sf::Keyboard::S]) {
                cs->getPlayerEntity()->manualMove(0,1);
                if (cs->viewFollowing){
                    cs->moveView(0,1);
                }
        }
        if (keyStates[sf::Keyboard::A]) {
                cs->getPlayerEntity()->manualMove(-1,0);
                if (cs->viewFollowing){
                    cs->moveView(-1,0);
                }
        }
        if (keyStates[sf::Keyboard::D]) {
                cs->getPlayerEntity()->manualMove(1,0);
                if (cs->viewFollowing){
                    cs->moveView(1,0);
                }
        }
        if (keyStates[sf::Keyboard::Q]) {
            cs->getPlayerEntity()->rotate(-1);
        }
        if (keyStates[sf::Keyboard::E]) {
            cs->getPlayerEntity()->rotate(1);
        }
        if (keyStates[sf::Keyboard::Space]) {
        }
        if(keyStates[sf::Keyboard::Up]) {
            cs->moveView(0,-1);
        }
        if (keyStates[sf::Keyboard::Down]) {
            cs->moveView(0,1);
        }
        if (keyStates[sf::Keyboard::Left]) {
            cs->moveView(-1,0);
        }
        if (keyStates[sf::Keyboard::Right]) {
            cs->moveView(1,0);
        }
    }

<file_sep>

#include "HUD.hpp"
#include "BuildSystem.hpp"

 void HUD::draw() {
    // inside the main loop, between window.clear() and window.display()
    cs->mSFWindow->draw(text);
    if (cs->viewFollowing)
      cs->mSFWindow->draw(viewFollow);

    if (cs->mode == CentralSystem::MODE_BUILD) {
      cs->buildSystem->drawHUD();
    }

}
<file_sep>#pragma once

#include <math.h>

class Geom {

public:
	enum {LEFT,  RIGHT,  BEHIND, BEYOND, BETWEEN};

    static int whichSide(sf::Vector2f p0, sf::Vector2f p1, sf::Vector2f p2)
    {
      sf::Vector2f a = p1 - p0;
      sf::Vector2f b = p2 - p0;
      double sa = a.x * b.y - b.x * a.y;
      if (sa > 0.0)
        return LEFT;
      if (sa < 0.0)
        return RIGHT;
      if ((a.x * b.x < 0.0) || (a.y * b.y < 0.0))
        return BEHIND;
      if ( sqrt(a.x*a.x + a.y*a.y) < sqrt(b.x*b.x + b.y*b.y) )
        return BEYOND;
      return BETWEEN;
    }
};<file_sep>#pragma once

class ViewController {};
<file_sep>

#include  <SFML/Graphics.hpp>

#include "CentralSystem.h"
#include "Entity.hpp"
#include "BaseObjects.hpp"
#include "Ships.h"
#include "Textures.hpp"
#include "BuildSystem.hpp"

#include "Projectile.hpp"
#include "AI.hpp"
#include <iostream>
#include <typeinfo>

using namespace std;

 // TODO singleton
CentralSystem::CentralSystem(): entitiesCounter(0), viewFollowing(0),
    winWidth(500), winHeight(500), mode(MODE_PLAY)
{
    m_player = new Player;
    m_player->setName("Player 1");
    characters.push_back(m_player);
    for (std::list<Character*>::iterator it = characters.begin() ; it != characters.end(); ++it) {
        ((Character*)*it)->setCS(this);
    }
    textureManager = new TextureManager(this);
    buildSystem = new BuildSystem(this);
}

int CentralSystem::getNextEntityId() {
    return ++entitiesCounter;
}

void CentralSystem::launchProjectile(Entity *origin) {
    projectiles.insert(projectiles.begin(),new Projectile(this, origin));
}

void CentralSystem::tick() {
    for (std::list<Projectile*>::iterator it = projectiles.begin() ; it != projectiles.end(); ++it) {
        Projectile* p = (Projectile*)*it;
        p->move();
        if (p->end() || p->hits()) {
            delete p;
            it = projectiles.erase(it);
        }
    }

    for (std::list<Entity*>::iterator it = entities.begin() ; it != entities.end(); ++it) {
      if ((*it)->aiControlled()){
          (*it)->getAI()->act();
      }
      (*it)->tick();
      DestroyableObject* d;
      if (d = dynamic_cast<DestroyableObject*>(*it))
      if (d->isDestroyed()) {
        delete (*it);
        it = entities.erase(it);
      }
    }

    for (std::list<Character*>::iterator it = characters.begin() ; it != characters.end(); ++it) {

    }
}

void CentralSystem::draw() {
    textureManager->draw();
    switch (mode) {
    case MODE_PLAY:
        for (std::list<Projectile*>::iterator it = projectiles.begin() ; it != projectiles.end(); ++it) {
            ((Projectile*)*it)->draw();
        }
        for (std::list<Entity*>::iterator it = entities.begin() ; it != entities.end(); ++it) {
            ((Entity*)*it)->draw();
        }
        for (std::list<Character*>::iterator it = characters.begin() ; it != characters.end(); ++it) {
            ((Character*)*it)->draw();
        }
        break;

    case MODE_BUILD:
        MatrixShip *hs;
        if (hs = dynamic_cast<MatrixShip*>(getPlayerEntity() ) ) {
            hs->draw(MODE_BUILD);
        }
        buildSystem->draw();
        break;
    };
}

Entity *CentralSystem::currentEntity() {
    for (std::list<Entity*>::iterator it = entities.begin() ; it != entities.end(); ++it) {
        if ( ((Entity*)*it)->playerBoarded() ) {
            return ((Entity*)*it);
        }
    }
    return NULL;
}

Entity *CentralSystem::getPlayerEntity() { // TODO caching
    for (std::list<Entity*>::iterator it = entities.begin() ; it != entities.end(); ++it) {
        if ( ((Entity*)*it)->playerBoarded() ) {
            return ((Entity*)*it);
        }
    }
    return NULL;
}

Entity *CentralSystem::projectileProximity(Entity *origin, Projectile *projectile) {
    for (std::list<Entity*>::iterator it = entities.begin() ; it != entities.end(); ++it) {
        if ( ((Entity*)*it)->getEntityId() != origin->getEntityId() ) {
            sf::Vector2f v = projectile->getPosition() - ((Entity*)*it)->getPosition();
            if ( sqrt(v.x*v.x + v.y*v.y) < ((Entity*)*it)->hitRadius() )
                return ((Entity*)*it);
        }
    }
    return NULL;
}

void CentralSystem::dealDamageTo(Entity *target) {
    DestroyableObject* d;
    if (d = dynamic_cast<DestroyableObject*>(target))
        d->destroy();
}

void CentralSystem::toggleViewFollow() {
    viewFollowing = !viewFollowing;
}

void CentralSystem::toggleBuildMode() {
    if (playerBoarded()) {
        mode = mode == MODE_PLAY ? MODE_BUILD : MODE_PLAY;
    }
}

bool CentralSystem::playerBoarded() {
    return m_player->boarded();
}

void CentralSystem::cmdBoard() {
    if (m_player->boarded()) {
        m_player->unboard();
    } else {
        //TODO
        // TODO stop ship movement if player exited
    }
}

void CentralSystem::initTexture(sf::RenderTexture* renderTexture) {
    buildSystem->initTexture(renderTexture);
}

<file_sep>#pragma once

class Projectile;

class CannonShell : public Projectile{};

class Bullet : public Projectile{};

class Missile{};

class GuidedMissile : Missile{};

class Weapon{};

class ContinuousWeapon : public Weapon {
	// state - active/inactive
};

class DescreteWeapon : public Weapon {
	// per shots
};

<file_sep>#pragma once

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

class CentralSystem;
class Tooltip {
public:
    sf::Text text;

    Tooltip (CentralSystem *cs);

    void drawHUD();
private:
    CentralSystem *cs;
};

class ElementIcon {
public:

    ElementIcon(int type, CentralSystem *cs): tooltip(cs) {
        this->cs = cs;
        this->type = type;
    }

    void initTexture(sf::RenderTexture* renderTexture);

    void draw();

    void drawHUD();

    bool hits(float x, float y) {
        if (x > sprite.getPosition().x && x < sprite.getPosition().x + 16
         && y > sprite.getPosition().y && y < sprite.getPosition().y + 16){
            return true;
        }

        return false;
    }

/////////////

    Tooltip tooltip;

    sf::Sprite sprite; // TODO make protected
    int type; // TODO make protected
protected:
    CentralSystem *cs;

};

//==============================================================================
//==============================================================================

class Element {
public:
    enum {POWER, THRUST, HULL, STANDARD_ARMOR, COMPOSITE_ARMOR, MACHINE_GUN, GUN_30, GUN_100,
        MISSILE_TUBE_100, MISSILE_TUBE_500 };

    Element(int type, CentralSystem *cs);

    void draw();

    sf::Sprite sprite; // TODO make private

private:
    int type;
    CentralSystem *cs;
};

//==============================================================================
//==============================================================================

class ElementsPanel {
public:
    CentralSystem *cs;
    std::vector<ElementIcon *> elements;
    std::vector<ElementIcon *>::iterator elements_iterator;
    int selected_element;
    sf::RectangleShape cursor;

    ElementsPanel(CentralSystem *cs): selected_element(0), cursor(sf::Vector2f(16,16))  {
        cursor.setFillColor(sf::Color::Transparent);
        cursor.setOutlineThickness(1);
        cursor.setOutlineColor(sf::Color::White);
        this->cs = cs;
        elements.push_back(new ElementIcon(Element::POWER,cs));
        elements.push_back(new ElementIcon(Element::THRUST,cs));
        elements.push_back(new ElementIcon(Element::HULL,cs));
        elements.push_back(new ElementIcon(Element::STANDARD_ARMOR,cs));
        elements.push_back(new ElementIcon(Element::COMPOSITE_ARMOR,cs));
        elements.push_back(new ElementIcon(Element::MACHINE_GUN,cs));
        elements.push_back(new ElementIcon(Element::GUN_30,cs));
        elements.push_back(new ElementIcon(Element::GUN_100,cs));
        elements.push_back(new ElementIcon(Element::MISSILE_TUBE_100,cs));
        elements.push_back(new ElementIcon(Element::MISSILE_TUBE_500,cs));
    }

    ~ElementsPanel() {
        for(elements_iterator = elements.begin();
            elements_iterator != elements.end();
            elements_iterator++) {
            delete (*elements_iterator);
        }
    }

    void initTexture(sf::RenderTexture* renderTexture) {
        for(elements_iterator = elements.begin();
            elements_iterator != elements.end();
            elements_iterator++) {
            if (ElementIcon* el = dynamic_cast<ElementIcon *>( (*elements_iterator) ) ) {
                el->initTexture(renderTexture);
            }
        }
    }

    void draw() {
        for(elements_iterator = elements.begin();
            elements_iterator != elements.end();
            elements_iterator++) {
            if (ElementIcon* el = dynamic_cast<ElementIcon *>( (*elements_iterator) ) ) {
                el->draw();
            }
        }
    }

    void drawHUD();

    void click(sf::Event event) {
        for(elements_iterator = elements.begin();
            elements_iterator != elements.end();
            elements_iterator++) {
            if (ElementIcon* el = dynamic_cast<ElementIcon *>( (*elements_iterator) ) ) {
                if (el->hits(event.mouseButton.x,event.mouseButton.y)) {
                    selected_element = elements_iterator - elements.begin();
                }
            }
        }
    }

    bool selected() {return selected_element>=0;}

    int getSelectedType() {
        if (elements[selected_element]) {
            return elements[selected_element]->type;
        }
        return -1;
    }
};

<file_sep>#pragma once

#include "ChassisSegments.hpp"
#include "Ships.h"
#include "Chassis.hpp"
#include "util/Matrices.hpp"

class ChassisFactory {
	static  Chassis* build(int type){};
};

class TetragonChassisFactory : public ChassisFactory {};

class HexagonChassisFactory : public ChassisFactory
{
public:

	static Chassis* build(int type) {
		HexagonChassis* c = NULL;
		switch (type) {
		case MatrixShip::PROBE:
			c = new HexagonChassis;
			c->matrix = new CenteredMatrix<ShapeSegment*>(3,3);
			(*c->matrix)(0, -2) = new HexagonSegment();
			(*c->matrix)(0, -1) = new HexagonSegment();
			(*c->matrix)(0,  0) = new HexagonSegment();
			(*c->matrix)(0,  1) = new HexagonSegment();
			(*c->matrix)(0,  2) = new HexagonSegment();
			(*c->matrix)(-1, 0) = new HexagonSegment();
			(*c->matrix)(-1, 1) = new HexagonSegment();
			break;
		}

		return c;
	}
};

<file_sep>#pragma once

class MultipartObject {

};
<file_sep>#pragma once

#include <map>
#include <SFML/Graphics.hpp>
//#include "CentralSystem.h"

class TextureFragment {
public:
    int textureID;
    float u0,v0,u1,v1;
};

class CentralSystem;
class TextureManager {
public:
    enum {PANEL_ELEMENTS};
    TextureManager(CentralSystem *cs):textureCount(0), fragmentCount(0) {
        this->cs = cs;
        sf::RenderTexture *rt = new sf::RenderTexture();
        if (!rt->create(256, 256))
        {
           // error...
        }
        textures[0] = rt;

    }
    std::map<int,sf::RenderTexture*> textures; // TODO private
    std::map<int,sf::RenderTexture*>::iterator textures_iterator;// TODO private
    std::map<int,TextureFragment> fragments; // TODO private
    int getNextTextureID()  { return ++textureCount; }
    int getNextFragmentID() { return ++fragmentCount; }
    void draw() {

        for(textures_iterator = textures.begin();
            textures_iterator != textures.end();
            textures_iterator++) {

            textures_iterator->second->clear();
            textures_iterator->second->setSmooth(false);
            cs->initTexture(textures_iterator->second);
            //textures_iterator->second->draw(s);
            textures_iterator->second->display();
        }

    }
private:
    int textureCount, fragmentCount;
    CentralSystem *cs;
};

<file_sep>#pragma once

// TODO in play mode<file_sep>#pragma once

#include <stdlib.h>
#include <iostream>

template <class T>
class Matrix {
public:
	Matrix(int width, int height):m_width(width), m_height(height)  {
		data = new T*[m_height];
		for (int i = 0; i < m_height; ++i) {
			data[i] = new T[m_width];
			for (int j = 0; j < m_width; ++j) {
				data[i][j] = NULL;
			}
		}
	}

	~Matrix() {
		for (int i = 0; i < m_height; ++i) {
			delete data[i];
		}
		delete data;
	}

	T& operator()(int x, int y)  {
	    if(x >= 0 && x < m_width)
	    if(y >= 0 && y < m_height){
			return data[x][y];
	    } else return data[0][0];
	}

protected:
	int m_width;
	int m_height;

	T **data;
};

template <class T>
class CenteredMatrix : public Matrix<T> {

public:
	CenteredMatrix(int width, int height):
			Matrix<T>(width  * 2 + 1, height * 2 + 1),
			offsetx (width), offsety (height)
	{}

	T& operator()(int x, int y)  {
		x += this->offsetx; y += this->offsety;
	    if(x >= 0 && x < this->m_width)
	    if(y >= 0 && y < this->m_height){
			return this->data[x][y];
	    } else return this->data[0][0];
	}

	int offsetx, offsety;

protected:

};

<file_sep>#pragma once

class PlanetarySystem
{
public:
	PlanetarySystem();
};

class Sector
{
public:
	Sector();
};

class GlobalCoordinates
{
public:
	PlanetarySystem *mSystem;
	Sector *mSector;

	GlobalCoordinates();

};

<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include <vector>
#include "Elements.hpp"

class ChassisSegment {
public:
    Element *element;

    ChassisSegment(): element(0) {}
    ~ChassisSegment() {
        // TODO
        //delete element;
    }

};

class ShapeSegment : public ChassisSegment {
public:
    ShapeSegment() {
    }
    ~ShapeSegment() {
        delete shape;
    }

protected:
    sf::CircleShape *shape; // TODO non-pointer
    friend class MatrixShip;
};

class TetragonSegment : public ShapeSegment {
public:
    TetragonSegment() {
        shape = new sf::CircleShape(8, 4);
        shape->setFillColor(sf::Color::Transparent);
        shape->setOutlineThickness(1);
        shape->setOutlineColor(sf::Color::White);
        shape->setRotation(45);
    }
protected:
};

class HexagonSegment : public ShapeSegment {
public:
    HexagonSegment() {
        shape = new sf::CircleShape(12, 6);
        shape->setFillColor(sf::Color::Transparent);
        shape->setOutlineThickness(1);
        shape->setOutlineColor(sf::Color::White);
        shape->setRotation(90);
    }
protected:
};

// ========================================
// ========================================

class SegmentConnector {};

class ConnectableSegment : public ChassisSegment
{
    vector<SegmentConnector *> connectors;

public:

};

<file_sep>#pragma once

#include <iostream>
#include <map>
#include <SFML/Window.hpp>
#include "CentralSystem.h"
#include "Ships.h"

using namespace std;

class EventDispatcher {
	CentralSystem *cs;
	map<sf::Keyboard::Key,bool> keyStates;

public:
	EventDispatcher(CentralSystem *cs);
	void keyPressed(sf::Event event);
	void keyReleased(sf::Event event);
	void mouseButtonPressed(sf::Event event);
	void mouseButtonReleased(sf::Event event);
	void tick();
};

<file_sep>#pragma once

#include <SFML/Graphics.hpp>

class AI;
class Character;
class Entity {
    int entityId;
public:
    int getEntityId() { return entityId;};
    void setEntityId(int entityId) { this->entityId = entityId; }
    virtual bool playerBoarded() {};
    virtual void mainAction() {};
    virtual void cmdLMB(sf::Vector2f v) {};
    virtual void cmdRMB(sf::Vector2f v) {};
    virtual void tick() {};
    virtual bool move() {};
    virtual void manualMove(float x, float y) {};
    virtual void rotate(float angle) {};
    virtual void draw() {};
    virtual bool aiControlled() {return false;};
    virtual AI* getAI() {return NULL;};
    virtual float spottingRange(){};
    virtual float attackRange(){};
    virtual bool acceptsCommands() { return false; }
    virtual bool acceptsMoveCommands() { return false; }
    virtual sf::Vector2f getPosition() {return sf::Vector2f(0,0);}
    virtual float getRotation() {return 0.f;}
    virtual void cmdFireAt(Entity* target) {}
    virtual void cmdCloseIn(Entity* target) {}
    virtual void cmdSideMove(Entity* target) {}
    virtual float hitRadius() { return 20; }
    //virtual bool isDestroyed() {}
    /// returns position in an entity
    virtual int addCrewMember(Character *character) { /*TODO*/ }
    virtual void mouseButtonPressed(sf::Event event) {}
    virtual void mouseButtonReleased(sf::Event event) {}
};

class NamedEntity : public Entity {
    sf::String name;
public:
    sf::String getName() { return name; }
    void setName(sf::String name) { this->name = name; }
};

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

#include "Elements.hpp"
#include "CentralSystem.h"
#include "Textures.hpp"

Tooltip::Tooltip (CentralSystem *cs) {
    this->cs = cs;
    text.setFont(cs->defaultFont);
    text.setCharacterSize(12);
}

void Tooltip::drawHUD() {
    cs->mSFWindow->draw(text);
}

void ElementIcon::drawHUD() {
    cs->mSFWindow->draw(sprite);
    tooltip.drawHUD();
}

void ElementIcon::initTexture(sf::RenderTexture* renderTexture) {
    if (type == Element::POWER) {
        sf::RectangleShape icon(sf::Vector2f(12,12) );
        icon.move(0,0);
        icon.setFillColor(sf::Color(127, 127, 255));
        renderTexture->draw(icon);
    } else if (type == Element::THRUST) {
        sf::RectangleShape icon(sf::Vector2f(12,12));
        icon.move(16,0);
        icon.setFillColor(sf::Color::Red);
        renderTexture->draw(icon);
    } else if (type == Element::HULL) {
        sf::RectangleShape icon(sf::Vector2f(12,12));
        icon.move(32,0);
        icon.setFillColor(sf::Color(187, 187, 187));
        renderTexture->draw(icon);
    } else if (type == Element::STANDARD_ARMOR) {
        sf::RectangleShape icon(sf::Vector2f(12,12));
        icon.move(48,0);
        icon.setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(icon);
    } else if (type == Element::COMPOSITE_ARMOR) {
        sf::RectangleShape icon(sf::Vector2f(12,12));
        icon.move(64,0);
        icon.setFillColor(sf::Color(77, 77, 77));
        renderTexture->draw(icon);
    } else if (type == Element::MACHINE_GUN) {
        sf::RectangleShape points[3];
        points[0] = sf::RectangleShape(sf::Vector2f(8,2));
        points[0].move(80+2,2);
        points[0].setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(points[0]);
        points[1] = sf::RectangleShape(sf::Vector2f(8,2));
        points[1].move(80+2,5);
        points[1].setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(points[1]);
        points[2] = sf::RectangleShape(sf::Vector2f(8,2));
        points[2].move(80+2,8);
        points[2].setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(points[2]);
    } else if (type == Element::GUN_30) {
        sf::CircleShape icon(3);
        icon.move(96+3,3);
        icon.setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(icon);
    } else if (type == Element::GUN_100) {
        sf::CircleShape icon(5);
        icon.move(112+1,1);
        icon.setFillColor(sf::Color(127, 127, 127));
        renderTexture->draw(icon);
    } else if (type == Element::MISSILE_TUBE_100) {
        sf::CircleShape icon(3);
        icon.move(128+3,3);
        icon.setFillColor(sf::Color::Red);
        renderTexture->draw(icon);
    } else if (type == Element::MISSILE_TUBE_500) {
        sf::CircleShape icon(5);
        icon.move(144+1,1);
        icon.setFillColor(sf::Color::Red);
        renderTexture->draw(icon);
    }

}

void ElementIcon::draw() {
    const sf::Texture& texture = cs->textureManager->textures[0]->getTexture();
    sprite.setTexture(texture);

    switch (type) {
        case Element::POWER:
            sprite.setTextureRect(sf::IntRect(0, 0, 16, 16)); // TODO 16->12 and const
            sprite.setPosition(10,60);
            tooltip.text.setPosition(30,60);
            tooltip.text.setString(sf::String("Power Element"));
            break;
        case Element::THRUST:
            sprite.setTextureRect(sf::IntRect(16, 0, 16, 16));
            sprite.setPosition(10,80);
            tooltip.text.setPosition(30,80);
            tooltip.text.setString(sf::String("Thrust Element"));
            break;
        case Element::HULL:
            sprite.setTextureRect(sf::IntRect(32, 0, 16, 16));
            sprite.setPosition(10,100);
            tooltip.text.setPosition(30,100);
            tooltip.text.setString(sf::String("Hull"));
            break;
        case Element::STANDARD_ARMOR:
            sprite.setTextureRect(sf::IntRect(48, 0, 16, 16));
            sprite.setPosition(10,120);
            tooltip.text.setPosition(30,120);
            tooltip.text.setString(sf::String("Standard Armor"));
            break;
        case Element::COMPOSITE_ARMOR:
            sprite.setTextureRect(sf::IntRect(64, 0, 16, 16));
            sprite.setPosition(10,140);
            tooltip.text.setPosition(30,140);
            tooltip.text.setString(sf::String("Composite Armor"));
            break;
        case Element::MACHINE_GUN:
            sprite.setTextureRect(sf::IntRect(80, 0, 16, 16));
            sprite.setPosition(10,160);
            tooltip.text.setPosition(30,160);
            tooltip.text.setString(sf::String("Machine Gun"));
            break;
        case Element::GUN_30:
            sprite.setTextureRect(sf::IntRect(96, 0, 16, 16));
            sprite.setPosition(10,180);
            tooltip.text.setPosition(30,180);
            tooltip.text.setString(sf::String("Gun Barrel 30mm"));
            break;
        case Element::GUN_100:
            sprite.setTextureRect(sf::IntRect(112, 0, 16, 16));
            sprite.setPosition(10,200);
            tooltip.text.setPosition(30,200);
            tooltip.text.setString(sf::String("Gun Barrel 100mm"));
            break;
        case Element::MISSILE_TUBE_100:
            sprite.setTextureRect(sf::IntRect(128, 0, 16, 16));
            sprite.setPosition(10,220);
            tooltip.text.setPosition(30,220);
            tooltip.text.setString(sf::String("Missile Tube 100mm"));
            break;
        case Element::MISSILE_TUBE_500:
            sprite.setTextureRect(sf::IntRect(144, 0, 16, 16));
            sprite.setPosition(10,240);
            tooltip.text.setPosition(30,240);
            tooltip.text.setString(sf::String("Missile Tube 500mm"));
            break;
    }

}

Element::Element(int type, CentralSystem *cs) {
    this->cs = cs;
    this->type = type;

    const sf::Texture& texture = cs->textureManager->textures[0]->getTexture();
    sprite.setTexture(texture);

    switch (type) {
    case Element::POWER:
        sprite.setTextureRect(sf::IntRect(0, 0, 12, 12));
        break;
    case Element::THRUST:
        sprite.setTextureRect(sf::IntRect(16, 0, 12, 12));
        break;
    case Element::HULL:
        sprite.setTextureRect(sf::IntRect(32, 0, 12, 12));
        break;
    case Element::STANDARD_ARMOR:
        sprite.setTextureRect(sf::IntRect(48, 0, 12, 12));
        break;
    case Element::COMPOSITE_ARMOR:
        sprite.setTextureRect(sf::IntRect(64, 0, 12, 12));
        break;
    case Element::MACHINE_GUN:
        sprite.setTextureRect(sf::IntRect(80, 0, 12, 12));
        break;
    case Element::GUN_30:
        sprite.setTextureRect(sf::IntRect(96, 0, 12, 12));
        break;
    case Element::GUN_100:
        sprite.setTextureRect(sf::IntRect(112, 0, 12, 12));
        break;
    case Element::MISSILE_TUBE_100:
        sprite.setTextureRect(sf::IntRect(128, 0, 12, 12));
        break;
    case Element::MISSILE_TUBE_500:
        sprite.setTextureRect(sf::IntRect(144, 0, 12, 12));
        break;
    }
}

void Element::draw() {

}

void ElementsPanel::drawHUD() {
    for(elements_iterator = elements.begin();
        elements_iterator != elements.end();
        elements_iterator++) {
        if (ElementIcon* el = dynamic_cast<ElementIcon *>( (*elements_iterator) ) ) {
            el->drawHUD();
        }
    }
    // TODO convert to method
    cursor.setPosition(elements[selected_element]->sprite.getPosition().x-2,
        elements[selected_element]->sprite.getPosition().y-2);

    cs->mSFWindow->draw(cursor);
}

<file_sep>#!/bin/bash
echo "== CentralSystem =="
g++ -g -c src/CentralSystem.cpp -o obj/CentralSystem.o
echo "== EventDispatcher =="
g++ -g -c src/EventDispatcher.cpp -o obj/EventDispatcher.o
echo "== HUD =="
g++ -g -c src/HUD.cpp -o obj/HUD.o
echo "== Stations =="
g++ -g -c src/Stations.cpp -o obj/Stations.o
echo "== Ships =="
g++ -g -c src/Ships.cpp -o obj/Ships.o
echo "== BuildSystem =="
g++ -g -c src/BuildSystem.cpp -o obj/BuildSystem.o
echo "== Elements =="
g++ -g -c src/Elements.cpp -o obj/Elements.o
echo "== Character =="
g++ -g -c src/Character.cpp -o obj/Character.o
echo "== main.cpp =="
g++ -g -c src/main.cpp -o obj/main.o
<file_sep>#pragma once

class FactionManager {
public:
	static int getPlayerEntityFaction() {
		return 1;
	}

	static int getNeutralFaction() {
		return 0;
	}

	static int getPirateFaction() {
		return -1;
	}

};
<file_sep>#pragma once

#include "SFML/Graphics.hpp"

#include "Entity.hpp"
#include "Coordinates.hpp"

class SpaceObject
{
    //GlobalCoordinates mGC;
public:
    SpaceObject(){}
};

class StaticSpaceObject : public SpaceObject {

};

class RotatingSpaceObject : public StaticSpaceObject {
protected:
    int lastRotateDir;
public:
    int rotateTolerance;
    RotatingSpaceObject(): rotateTolerance(0), lastRotateDir(0) {}

};

class MovingSpaceObject : public RotatingSpaceObject {
public:
    MovingSpaceObject(): moveInProgress(false), destination(0,0) {}

    bool acceptsMoveCommands() {
        return !moveInProgress;
    };
protected:
    sf::Vector2f destination;
    bool moveInProgress;
private:
    int movePause;
};

class FactionObject {
public:
    FactionObject ():factionId(0) {}

    void setOwnership() {
        this->factionId = factionId;
    }
protected:

private:
    int factionId;
};

class DestroyableObject {
public:
    DestroyableObject ():destroyed(false) {}
    void destroy() {
        destroyed = true;
    }
    bool isDestroyed() {
        return destroyed;
    }

protected:

private:
    bool destroyed;
};

class NamedObject {
    sf::String name;
public:
    sf::String getName() { return name; }
    void setName(sf::String name) { this->name = name; }
};
<file_sep>
#include "Entity.hpp"
#include "Character.hpp"
#include "CentralSystem.h"

 void Character::board(Entity* entity) {
	if (entity->addCrewMember(this)) {
		m_boarded = true;
		this->entity = entity;
	}
}

void Character::draw(){
    if (!m_boarded) {
        cs->mSFWindow->draw(shape);
    }
}

<file_sep>#!/bin/bash
bin/main.bin
<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include <list>
#include "Character.hpp"
#include "Player.hpp"
#include "Entity.hpp"

using namespace std;

//TODO admin mode with TAB

class Character;
class Entity;
class Universe;
class Projectile;
class BuildSystem;
class TextureManager;
class CentralSystem
{
    Universe *universe;

    unsigned int entitiesCounter;

    list<Projectile*> projectiles;
public:
    list<Entity*> entities;// TODO make private
    list<Character*> characters; // TODO make private
    Player* m_player;  // TODO make private

    unsigned int mode; // TODO make private
    enum {MODE_PLAY, MODE_BUILD};
    float winWidth;
    float winHeight;
    void setScreenSize(float w, float h) {winWidth = w; winHeight = h;}
    bool viewFollowing;
    sf::Font defaultFont;

    sf::RenderWindow *mSFWindow;
    sf::View *mSFView, *mSFBuildView;
    TextureManager *textureManager;
    BuildSystem *buildSystem;

    CentralSystem();
    int getNextEntityId();

    void launchProjectile(Entity *origin);
    void tick();
    void draw();
    Entity *projectileProximity(Entity *origin, Projectile *projectile);
    Entity *currentEntity();
    Entity *getPlayerEntity();
    Character *getPlayer() {return m_player;}
    void dealDamageTo(Entity *target);
    void toggleViewFollow();
    void toggleBuildMode();
    bool playerBoarded();
    void cmdBoard();
    void moveView(float x, float y) {
        if (mode == MODE_PLAY) {
            mSFView->move(x,y);
        } else {
            mSFBuildView->move(x,y);
        }
    }
    void initTexture(sf::RenderTexture* renderTexture);
};

<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include "BaseObjects.hpp"
#include "CentralSystemUser.hpp"

class Entity;
class Character : public NamedObject, public CentralSystemUser {
public:
    Character(): m_boarded(false), shape(sf::Vector2f(2,2)) {
        shape.setFillColor(sf::Color::White);
    }

    //TODO init to check if cs is set

    virtual bool boarded() {return m_boarded;}
    virtual void board(Entity* entity);
    virtual void unboard() {
        shape.setPosition(entity->getPosition());
        this->entity = NULL;
        m_boarded = false;
    }

    virtual void draw();

protected:
    sf::RectangleShape shape;
private:
    bool m_boarded;
    Entity* entity;
};
<file_sep>#pragma once

#include <math.h>
#include "Entity.hpp"

#include <iostream>

class AI {
    Entity *controlled;
    CentralSystem *cs;

public:

    AI(CentralSystem *cs, Entity *controlled) {
        this->cs = cs;
        this->controlled = controlled;
    }

    void act() {
        if (cs->getPlayerEntity() == NULL) return;
        sf::Vector2f d = controlled->getPosition() - cs->getPlayerEntity()->getPosition();
        if ( sqrt(d.x*d.x + d.y*d.y) < controlled->spottingRange()) {
            if (controlled->acceptsMoveCommands() ) {
            switch ((int)(rand()%3)){
                case 0:
                    if (sqrt(d.x*d.x + d.y*d.y) > controlled->attackRange()) {
                    controlled->cmdCloseIn(cs->getPlayerEntity());
                    }
                    break;
                case 1:
                    controlled->cmdSideMove(cs->getPlayerEntity());
                    break;
                case 2:
                    break;
            }
            }
            if (controlled->acceptsCommands() ) {
                controlled->cmdFireAt(cs->getPlayerEntity());
            }
        }
    }
};

class DummyAI : public AI {
public:
    DummyAI(CentralSystem *cs,Entity *controlled): AI(cs,controlled) { }
    void act() { cout << "DummyAI" << endl << flush;}
};
<file_sep>#pragma once

#include <math.h>
#include <iostream>

#include "AI.hpp"
#include "util/Geom.hpp"
#include "CentralSystem.h"
#include "BaseObjects.hpp"
#include "MultipartObject.hpp"
#include "Entity.hpp"

using namespace std;

class ShipBase {};

class Ship : public DestroyableObject, public FactionObject, public NamedEntity, public ShipBase, public MovingSpaceObject, public MultipartObject
{
    sf::CircleShape displayObject;
    sf::Vector2f target;
    int shoot;
    const int fireInterval;
    int fireWithin;
    bool boarded;
    AI *ai;
    bool actionInProgress;
    bool moveInProgress;
    int movePause;

    //TODO onBoard array

protected:
    CentralSystem *cs;

public:

    Ship();

    ~Ship() {
        delete ai;
    }

    void init(CentralSystem *cs, sf::String name = sf::String("(none)"));

    void setPosition(sf::Vector2f v) {
        displayObject.setPosition( v );
        destination = v;
        target = v + sf::Vector2f(0,-1);
    }

    void setRotation(float angle) {
        displayObject.setRotation( angle );
    }

    void tick() {
        if (moveInProgress) {
            move();
        }
        if (hasTurret()) {

        } else {
            sf::Vector2f p = displayObject.getPosition();
            float r = displayObject.getRotation();
            sf::Vector2f d = p+(sf::Transform()).rotate(r).transformPoint(0,1);
            if ( rotateTolerance ) {
                if (Geom::LEFT == Geom::whichSide(p, d, target)) {
                    if (lastRotateDir != -1) rotateTolerance--;
                    displayObject.rotate(-1);
                    lastRotateDir = -1;
                } else {
                    if (lastRotateDir != 1) rotateTolerance--;
                    displayObject.rotate(1);
                    lastRotateDir = 1;
                }
            } else {
                if (shoot > 0) {
                    if (fireWithin-- <= 0) {
                        --shoot;
                        mainAction();
                        fireWithin = fireInterval;
                    }
        } else {
            actionInProgress = false;
        }
            }
        }
    }

    bool move() {
        sf::Vector2f v = this->destination - displayObject.getPosition();
        float L = sqrt(v.x*v.x + v.y*v.y);
        if (L > 2) {
            v.x /= L;
            v.y /= L;
            displayObject.move( v );
            target += v;
            return true;
        } else { // finishing moving
            if (0 >= movePause--) {
                moveInProgress = false;
            }
            return false;
        }
    }

    void manualMove(float x, float y) {
        displayObject.move(x,y);
        this->destination = displayObject.getPosition();
    }

    void cmdRMB(sf::Vector2f v) {
        this->destination = v;
    }

    void rotate(float angle) {
        displayObject.rotate(angle);
    }

    void cmdLMB(sf::Vector2f v) {
    actionInProgress = true;
        this->target = v;
        rotateTolerance = 2;
        shoot = 3;
        fireWithin = fireInterval;
    }

    void cmdFireAt(Entity* target) {
    actionInProgress = true;
        this->target = target->getPosition();
        rotateTolerance = 2;
        shoot = 3;
        fireWithin = fireInterval;
    }

    void mainAction() { // TODO rename cmdFireFront
        cs->launchProjectile(this);
    }

    bool hasTurret() {
        return false;
    }

    virtual void draw() {
        cs->mSFWindow->draw(displayObject);
    }

    void setOwnership(int factionId) {
        FactionObject::setOwnership();
        switch (factionId) {
        case -1:
            delete this->ai;
            this->ai = new AI(cs, this);
            displayObject.setFillColor(sf::Color::Red);
            break;
        case 0:
            delete this->ai;
            this->ai = new AI(cs, this);
            displayObject.setFillColor(sf::Color::Blue);
            break;
        case 1:
            displayObject.setFillColor(sf::Color::White);
            break;
        }
    }

    void boardPlayer() {
        boarded = true;
        cs->getPlayer()->board(this);
    }

    bool playerBoarded() {
        return boarded; // TODO manage from onBoard array
    }

    AI *getAI() {
    if (!ai) return new DummyAI(cs,(Entity*)this);
        return ai;
    }

    bool aiControlled() {
        return (ai!=NULL);
    }

    bool acceptsCommands() {
        return !actionInProgress;
    }
    bool acceptsMoveCommands() {
        return !moveInProgress;
    };
    float spottingRange(){ return attackRange()+150.f;}
    float attackRange(){return 250.f;}
    sf::Vector2f getPosition() {
        return displayObject.getPosition();
    }
    float getRotation() {
        return displayObject.getRotation();
    }

    void cmdCloseIn(Entity *target) {
        if (!moveInProgress) {
            sf::Vector2f c = (target->getPosition() - this->getPosition()) / 4.f;
            sf::Vector2f r(rand()%50-25,rand()%50-25);
            this->destination = this->getPosition() + c + r;
            moveInProgress = true;
            movePause = 100;
        }
    }

    void cmdSideMove(Entity* target) {
        if (!moveInProgress) {
            sf::Vector2f r(rand()%200-100,rand()%200-100);
            this->destination = this->getPosition() + r;
            moveInProgress = true;
            movePause = 100;
        }
    }

    virtual void build(int type){}
};

class MatrixChassis;
class MatrixShip : public Ship {
public:
    enum {PROBE, SCOUT};
    const int intv_x, intv_y;

    MatrixShip(): intv_x(20), intv_y(20) {}

    void build(int type);
    void mouseButtonPressed(sf::Event event);
    void draw(int mode);

protected:
    enum {TETRAGON, HEXAGON};
    int type;

private:
    MatrixChassis *chassis;
};

<file_sep>#pragma once

/// dispatch when entity is not busy
class CommandDispatcher {

};

<file_sep>#pragma once

#include <SFML/Graphics.hpp>
#include <math.h>

#include "CentralSystem.h"

using namespace std;

class Projectile
{
    Entity *origin;
    sf::Vector2f direction;
    sf::Vector2f currentPosition;
    float velocity;
    float distance;
    sf::RectangleShape displayObject;
    CentralSystem *cs;
public:
    Projectile (CentralSystem *cs, Entity *origin):
            velocity(5),
            distance(0) {
        this->cs = cs;
        this->origin = origin;
        direction = (sf::Transform()).rotate(origin->getRotation()).transformPoint(sf::Vector2f(0,-1));
        displayObject.setSize(sf::Vector2f(2, 10) );
        displayObject.setRotation(origin->getRotation());
        displayObject.setPosition(origin->getPosition());
    }

    ~Projectile () {
    }

    void move() {
        sf::Vector2f mov = direction*velocity;
        distance += sqrt(mov.x*mov.x + mov.y*mov.y);
        displayObject.move(mov);
    }

    bool end() {
        return distance > 300;
    }

    bool hits() {
        Entity *target;
        if (target = cs->projectileProximity(origin, this) ) {
            cs->dealDamageTo(target);
            //return true;
        }
        return false;
    }

    void draw() {
        cs->mSFWindow->draw(displayObject);
    }

    sf::Vector2f getPosition() {
        return displayObject.getPosition();
    }
};
<file_sep>#pragma once

// to use include Vector3D for ShipHull

#include "ModuleConnectors.h"

class Module
{
public:
	Module()
	{

	}
};

class TechModule : public Module
{
public:
	//vector<ModuleConnectorPoint> mConnectorPoints;

	TechModule()
	{

	}
};

class PowerModule : public TechModule
{
public:
	PowerModule()
	{

	}
};

class TubeThrusterModule : public TechModule
{
public:
	TubeThrusterModule()
	{

	}
};

class SquareCorridorModule : public TechModule
{
public:
	SquareCorridorModule()
	{
	}
};

class ShipRear : public TechModule
{
public:
	ShipRear()
	{
	}
};

class ShipHull : public TechModule
{
public:
	ShipHull()
	{
		connectorPoints.push(new ModuleConnectorPoint(new SquareConnector(2,2),
			new Vector3D(0, 0, 1), new Vector3D(0, 0, 4));
		connectorPoints.push(new ModuleConnectorPoint(new SquareConnector(2,2),
			new Vector3D(0, 0, -1), new Vector3D(0, 0, -4));
			super();
	}
};

class ShipFront : public TechModule
{
protected:

public:
	ShipFront()
	{
		//connectorPoints
		//new ModuleConnectorPoint(new SquareConnector(2,2),
		//	new Vector3D(0, 0, -1), new Vector3D(0, 0, -1.2));
	}
};

class PilotCabinModule : public TechModule
{
public:
	PilotCabinModule()
	{
	}
};

class LongCargoHoldModule : public TechModule
{
public:
	LongCargoHoldModule()
	{
	}
};

class CorridorTube : public TechModule
{
public:
	CorridorTube()
	{
	}
};

class ComputingCentreModule : public TechModule
{
public:
	ComputingCentreModule()
	{
	}
};

class ArmoredCorridorTube : public TechModule
{
public:
	ArmoredCorridorTube()
	{
	}
};

class TurretModule : public TechModule
{
public:
	TurretModule()
	{
	}
};

class WeaponModule : public TechModule
{
private:
	uint caliber;
	uint length;

public:

	WeaponModule()
	{
		super();

		caliber = 1;
		length = 10;
	}
};

class CannonModule : public WeaponModule
{
public:
	CannonModule()
	{
	}
};

class ArmorModule : public TechModule
{
public:
	ArmorModule()
	{
	}
};

class HalfCylinderArmorModule : public ArmorModule
{
public:
	HalfCylinderArmorModule()
	{
	}
};

class FullCylinderArmorModule : public ArmorModule
{
public:
	FullCylinderArmorModule()
	{
	}
};

class BlockArmorModule : public ArmorModule
{
public:
	BlockArmorModule()
	{
	}
};

class ModuleCategoriesManager
{
public:
	ModuleCategoriesManager()
	{
	}

	void prev():void
	{

	}

	void next():void
	{

	}
};

<file_sep>#pragma once

class Turret : public Entity, public RotatingObject {};
<file_sep>#pragma once

class Reactor
{
	//energy gain per second
	//energy max
};

class Consumer
{
	// energy use per second
	//calculate per frame plus time

};

<file_sep>#pragma once

class Unit {};

class GroundUnit : public Unit {};

<file_sep>#pragma once

#include "Matrices.hpp"

class PlanetCoordinates {
	int x,y;
};

class Tile{};

class PlanetLocation {
public:
	Matrix<Tile *> map; // TODO private
	PlanetCoordinates coordiantes;

};

class Planet {
public:
	vector<PlanetLocation *> locations; // TODO private
};

<file_sep>
#include <iostream>
#include <SFML/Graphics.hpp>
#include "CentralSystem.h"
#include "Ships.h"
#include "Chassis.hpp"
#include "ChassisFactories.hpp"
#include "util/Matrices.hpp"
#include "ChassisSegments.hpp"
#include "BuildSystem.hpp"

Ship::Ship(): displayObject(20, 3), target(0,0), shoot(0), fireInterval(15), fireWithin(0),
        boarded(false), ai(NULL), actionInProgress(false), moveInProgress(false)
{}

void Ship::init(CentralSystem *cs, sf::String name ) {
    this->cs = cs;
    setName(name);
    setEntityId(cs->getNextEntityId());
    displayObject.setOrigin(20,20);
}

void MatrixShip::build(int type) {
    chassis = (HexagonChassis*)HexagonChassisFactory::build(type);
}

void MatrixShip::mouseButtonPressed(sf::Event event) {
    switch (cs->mode) {
    case CentralSystem::MODE_PLAY:
        Ship::draw();
        break;
    case CentralSystem::MODE_BUILD:
        sf::Vector2f coords = cs->mSFWindow->mapPixelToCoords(
            sf::Vector2i(event.mouseButton.x, event.mouseButton.y), (*cs->mSFBuildView) );
        coords.y -= intv_y;
        if (coords.x>=0) coords.x += intv_x; // coordinates adjustment
        if (coords.y>=0) coords.y += intv_y;
        int x = (coords.x) / intv_x,
            y = (coords.y) / intv_y;
        CenteredMatrix<ShapeSegment*>* m = chassis->matrix;
        ShapeSegment *p;
        if ( x >= -m->offsetx && x <= m->offsetx &&
             y >= -m->offsety && y <= m->offsety )
        if (p = dynamic_cast<ShapeSegment*>( (*m)(x,y) ) ) {
            if (cs->buildSystem->elementsPanel->selected()) {
                if (p->element) {
                    delete p->element;
                    p->element = NULL;
                } else {
                    p->element = new Element(cs->buildSystem->elementsPanel->getSelectedType(), cs);
                }
            }
        }
        break;
    }
}

void MatrixShip::draw(int mode) {
    switch (mode) {
    case CentralSystem::MODE_PLAY:
        Ship::draw();
        break;
    case CentralSystem::MODE_BUILD:
        CenteredMatrix<ShapeSegment*>* m = chassis->matrix;
        for (int y = -m->offsety; y < m->offsety; ++y) {
            for (int x = -m->offsetx; x < m->offsetx; ++x) {
                ShapeSegment *p;
                if (p = dynamic_cast<ShapeSegment*>( (*m)(x,y) ) ) {
                    p->shape->setPosition(x*intv_x, y*intv_y+(x%2*(int)(intv_x/2) )); // TODO move to class
                    cs->mSFWindow->draw(*(p->shape));
                    //TODO move to class
                    if (p->element) {
                        p->element->sprite.setPosition(x*intv_x-18, y*intv_y+(x%2*(int)(intv_x/2)+7 ));
                        cs->mSFWindow->draw(p->element->sprite);
                    }
                }
            }
        }
        break;
    }
}
<file_sep>#pragma once

//#include "CentralSystem.h"

// TODO implement everywhere
class CentralSystem;
class CentralSystemUser {
public:
    void setCS(CentralSystem *cs) { this->cs = cs; }
protected:
    CentralSystem *cs;
};

<file_sep>#pragma once

class MessageStack() {

};<file_sep>#pragma once

#include "Elements.hpp"
#include <SFML/Graphics.hpp>

class ElementsPanel;
class CentralSystem;
class BuildSystem {
public:
    BuildSystem(CentralSystem *cs)  {
        this->cs = cs;
        elementsPanel = new ElementsPanel(cs);
    }

    void initTexture(sf::RenderTexture* renderTexture) {
        elementsPanel->initTexture(renderTexture);
    }

    void draw() {
        elementsPanel->draw();
    }

    void drawHUD() {
        elementsPanel->drawHUD();
    }

    void mouseButtonPressed(sf::Event event);

    void mouseButtonReleased(sf::Event event);

    ElementsPanel *elementsPanel; // TODO private
private:
    CentralSystem *cs;
};

<file_sep>#pragma once

#include <vector>
#include "ChassisSegments.hpp"

// TODO multi-level chassis

// TODO [High Priority] build mode - click = place module

class Chassis
{
public:

};

template <class T>
class CenteredMatrix;

class MatrixChassis :  public Chassis {
public:
	CenteredMatrix<ShapeSegment*> *matrix;

};

class TetragonChassis : public MatrixChassis {
public:
	TetragonChassis() {
	}
};

class HexagonChassis : public MatrixChassis {
public:
	HexagonChassis() {
	}
};

class ConnectedChassis : public Chassis {
	vector<ChassisSegment*> segments;
};

branch_name: refs/heads/master

languages: C++ Shell

repo_name: xeddos/xds


text:
<repo_name>scalekent/Screenshot_py<file_sep>/PokeMOO.py
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
# from PIL import Image
from PIL import ImageQt

import win32gui
import sys
import time
# import cv2
import numpy as np
import matplotlib.pyplot as plt         # show image
# import matplotlib.image as mpimg        # read image
import pyautogui

def timer_start():
    start_time = time.time()
    return start_time
def timer_end(start_time):
    end_time = time.time()
    time_spent = end_time - start_time
    return time_spent

def HwndList():
    # hwnd list
    # ref: https://blog.csdn.net/weixin_39662578/article/details/112836211?utm_term=python%E8%8E%B7%E5%8F%96%E8%BF%9B%E7%A8%8B%E6%88%AA%E5%9B%BE&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-3-112836211&spm=3001.4430
    hwnd_title = dict()
    def get_all_hwnd(hwnd,mouse):
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})

    win32gui.EnumWindows(get_all_hwnd, 0)
    print('--------------- hwnd list start ---------------')
    for h,t in hwnd_title.items():
        if t != "":
            print(h, t)
    print('---------------- hwnd list end ----------------')

def ScreenshotQT(title):
    # Screenshot for hwnd
    hwnd = win32gui.FindWindow(None, title)
    app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    img = screen.grabWindow(hwnd).toImage()
    return img

def qtimage2numpy(img):
    # ImageQt 2 PILimage 2 Numpy
    # Convert Template: https://ithelp.ithome.com.tw/articles/10230274
    img = ImageQt.fromqimage(img)   # qimage2pil
    img = np.array(img)             # pil2numpy
    return img

def showbyplt(img):
    # img = mpimg.imread(img)     # is already a numpy object
    h,w,c = img.shape
    print('height:', h, ' width:', w, ' channel:', c)
    plt.imshow(img)
    plt.axis('on')
    plt.show()

def CheckBlock(img, check_area):
    # imput: img, numpyarray[[x1,y1,r,g,b],[x2,y2,r,g,b]...]
    # y↓ x→ c.
    check_flag = False
    for i in range(len(check_area)):
        # print('rgb:', img[check_area[i,0], check_area[i,1], 0], img[check_area[i,0], check_area[i,1], 1], img[check_area[i,0], check_area[i,1], 2],)

        if img[check_area[i,0], check_area[i,1], 0] > (check_area[i,2]-10) & img[check_area[i,0], check_area[i,1], 0] < (check_area[i,2]+10):
            check_flag = True
        else:
            check_flag = False
            break
        if img[check_area[i,0], check_area[i,1], 1] > (check_area[i,3]-10) & img[check_area[i,0], check_area[i,1], 1] < (check_area[i,3]+10):
            check_flag = True
        else:
            check_flag = False
            break
        if img[check_area[i,0], check_area[i,1], 2] > (check_area[i,4]-10) & img[check_area[i,0], check_area[i,1], 2] < (check_area[i,4]+10):
            check_flag = True
        else:
            check_flag = False
            break

    if (check_flag == False):
        return False
    elif (check_flag == True):
        return True
    else:
        pass

def MoveMouseClick():
    # ref: https://yanwei-liu.medium.com/pyautogui-%E4%BD%BF%E7%94%A8python%E6%93%8D%E6%8E%A7%E9%9B%BB%E8%85%A6-662cc3b18b80
    # ref: https://ithelp.ithome.com.tw/articles/10232225
    # pyautogui.moveTo(-1503, 713, duration=0.1)
    pyautogui.leftClick()
    pyautogui.keyDown('a')
    time.sleep(0.5)
    pyautogui.keyUp('a')
    pyautogui.keyDown('d')
    time.sleep(0.5)
    pyautogui.keyUp('d')

def test():
    check_area = np.array([[441,41,51,51,51],
                            [451,41,51,51,51],
                            [461,41,51,51,51],
                            [471,41,51,51,51],
                            [481,41,51,51,51]],
                            dtype = int)
    return check_area

if __name__ == '__main__':

    HwndList()

    check_area = np.array([[190,295,245,245,245],       # white
                            [190,305,245,245,245],
                            [190,315,245,245,245],
                            [190,325,245,245,245],
                            [190,335,245,245,245],
                            [190,345,245,245,245],
                            [190,627,245,245,245],
                            [190,637,245,245,245],
                            [190,647,245,245,245],
                            [190,656,245,245,245],
                            [203,300,48,48,48],         # black
                            [203,400,48,48,48],
                            [203,500,48,48,48],
                            [203,600,48,48,48],
                            [537,1300,48,48,48],        # black
                            [537,1390,48,48,48],
                            [537,1600,48,48,48],
                            ],
                            dtype = int)

    # check_area = test()
    # for i in range(2):
    while True:
        start_time = timer_start()

        img = ScreenshotQT('РokeMMO.py')
        img = qtimage2numpy(img)        # numpy.ndarray
        # showbyplt(img)

        InBattle = CheckBlock(img, check_area)
        print(InBattle)

        time.sleep(0.1)
        time_spent = timer_end(start_time)
        print('processing cost ', time_spent, 's')

<file_sep>/README.md
# Screenshot_py
 this is a sample code for Screenshot in python

branch_name: refs/heads/main

languages: Markdown Python

repo_language: Markdown


text:
<repo_name>JasonParra/electron-react-boilerplate<file_sep>/README.md
# Electron + React Boilerplate

## Getting Started

Boilerplate using eletron and react.

### Prerequisites

```
nodejs
```

### Installing

```
npn install
```

### Running

```
npm start
```

### Compile

```
npm run build
```

repo_name: JasonParra/electron-react-boilerplate


text:
<repo_name>cogn/grabit_demo_app<file_sep>/grabit_web.rb
#http://grabz.it/api/ruby/grabzitclient.aspx#savepicture
#To install the gem - "gem install grabzit"
#Generate the API key from "http://grabz.it/register.aspx" by registering your account
#Get the documentatio fromt he following url http://grabz.it/api/ruby/grabzitclient.aspx
require 'grabzitclient'
class GrabitWeb

 def initialize
  @filepath = Dir.pwd + "/test.png"
  @api_key = "<KEY>
  @application_secret = "<KEY>
 end

 #Use case : TO generate the thumbnail image
 def generate_screen_shot
  grabzItClient = GrabzItClient.new(@api_key, @application_secret)
  grabzItClient.save_picture("http://www.google.com", @filepath)
 end
end

GrabitWeb.new.generate_screen_shot

repo_language: Ruby


text:
<file_sep># naiveBayes.py
# -------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# <NAME> (<EMAIL>) and <NAME> (<EMAIL>).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html

import util
import classificationMethod
import math

class NaiveBayesClassifier(classificationMethod.ClassificationMethod):
  """
  See the project description for the specifications of the Naive Bayes classifier.

  Note that the variable 'datum' in this code refers to a counter of features
  (not to a raw samples.Datum).
  """
  def __init__(self, legalLabels):
    self.legalLabels = legalLabels
    self.type = "naivebayes"
    self.k = 1 # this is the smoothing parameter, ** use it in your train method **
    self.automaticTuning = False # Look at this flag to decide whether to choose k automatically ** use this in your train method **

  def setSmoothing(self, k):
    """
    This is used by the main method to change the smoothing parameter before training.
    Do not modify this method.
    """
    self.k = k

  def train(self, trainingData, trainingLabels, validationData, validationLabels):
    """
    Outside shell to call your method. Do not modify this method.
    """
    #WHAT IS KGRID#

    # might be useful in your code later...
    # this is a list of all features in the training set.
    self.features = list(set([ f for datum in trainingData for f in datum.keys() ]));

    if (self.automaticTuning):
        kgrid = [0.001, 0.01, 0.05, 0.1, 0.5, 1, 5, 10, 20, 50]
    else:
        kgrid = [self.k]

    self.trainAndTune(trainingData, trainingLabels, validationData, validationLabels, kgrid)

  def trainAndTune(self, trainingData, trainingLabels, validationData, validationLabels, kgrid):
    """
    Trains the classifier by collecting counts over the training data, and
    stores the Laplace smoothed estimates so that they can be used to classify.
    Evaluate each value of k in kgrid to choose the smoothing parameter
    that gives the best accuracy on the held-out validationData.

    trainingData and validationData are lists of feature Counters.  The corresponding
    label lists contain the correct label for each datum.

    To get the list of all possible features or labels, use self.features and
    self.legalLabels.

    """
    self.classProb={}
    self.classOccurence={}
    occur=0
    for digit in range(10):
      for x in range(len(trainingLabels)):
        if(trainingLabels[x]==digit):
          occur+=1
      self.classOccurence[digit]=occur
      self.classProb[digit]=float(occur)/float(len(trainingLabels))
      occur=0

    self.allFeaturesProb={}

    occurOfOne=0
    for digit in range(10):#for each class
      self.allFeaturesProb[digit] = {}
      for x in range(28): #each (x,y) is a feature
        for y in range(28):
          for z in range(len(trainingLabels)):#check to see if image we are on is in the class
            if(trainingLabels[z]==digit):
              image=trainingData[z]#get that specific image
              if(image.get((x,y))==1):#check to see if pixel for this image is a 1
                 occurOfOne+=1

          self.allFeaturesProb[digit][(x,y)] =float(occurOfOne)/float(self.classOccurence[digit])# idk if i need these denomineters of if this is right denom
          occurOfOne=0

    return

  def classify(self, testData):
    """
    Classify the data based on the posterior distribution over labels.

    You shouldn't modify this method.
    """
    guesses = []
    self.posteriors = [] # Log posteriors are stored for later data analysis (autograder).
    for datum in testData:
      posterior = self.calculateLogJointProbabilities(datum)
      guesses.append(posterior.argMax())
      self.posteriors.append(posterior)
    return guesses

  def calculateLogJointProbabilities(self, datum):
    """
    Returns the log-joint distribution over legal labels and the datum.
    Each log-probability should be stored in the log-joint counter, e.g.
    logJoint[3] = <Estimate of log( P(Label = 3, datum) )>

    To get the list of all possible features or labels, use self.features and
    self.legalLabels.
    """
    #CANT HAVE LOGS OF ZERO

    self.k=.01 #this is so far best choice for k idk why
    logJoint = util.Counter()
    #NEED HELP WITH THIS NEED TO SET K correctly and confirm math
    for digit in range(10):
      probOfClassAndFeature=math.log(self.classProb[digit]+self.k)
      for x in range(28):
        for y in range(28):
          if(datum.get((x,y))==1):
            probOfClassAndFeature+=math.log(self.allFeaturesProb[digit][(x,y)]+self.k)
          else:
            probOfClassAndFeature+=math.log(1-(self.allFeaturesProb[digit][(x, y)])+self.k)
      logJoint[digit]=probOfClassAndFeature
      probOfClassAndFeature=0

    return logJoint

  def findHighOddsFeatures(self, label1, label2):
    """
    Returns the 100 best features for the odds ratio:
            P(feature=1 | label1)/P(feature=1 | label2)

    Note: you may find 'self.features' a useful way to loop through all possible features
    """
    featuresOdds = []

    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()

    return featuresOdds

repo_language: Python

repo_name: rchertara/classification


text:
<repo_name>Meursau1T/Progress<file_sep>/README.md
# Progress
记录各项任务的进度，详细操作可见
```
Progress -h
```
<file_sep>/Program.cs
using System;
using System.Collections;
using System.IO;

namespace Progress
{
    class Task{
        int Finished;
        int Total;
        String Description;
        public Task(int Total,String Description){
            Finished = 0;
            this.Total = Total;
            this.Description = Description;
        }
        public void PrintDescription(){
            Console.WriteLine(Description);
        }
        public String GetDescription(){
            return Description;
        }
        public (int,int) GetProgress(){
            return (Finished, Total);
        }
        public void DrawProgress(){
            int ConsoleWidth = Console.BufferWidth;
            String start = "[";
            String end = "]" + Finished.ToString() + "/" + Total.ToString();
            int ProgressBarLength = ConsoleWidth - start.Length - end.Length;
            double rate = (double)Finished / (double)Total;
            int Black = (int)(ProgressBarLength * rate);
            int White = ProgressBarLength - Black;
            Console.WriteLine("{0}:", Description);
            Console.Write(start);
            for (int i = 0; i < Black; i++){
                Console.Write("#");
            }
            for (int i = 0; i < White; i++){
                Console.Write("-");
            }
            Console.WriteLine(end);
        }
        public void SetProgress(String Operation){
            if(Operation[0] == '+'){
                int tmp = Int32.Parse(Operation.Substring(1));
                Finished += tmp;
            }else{
                Finished = Int32.Parse(Operation);
            }
        }
    }
    class Tasks{
        ArrayList TaskList;
        public Tasks(){
            TaskList = new ArrayList();
        }
        public void Add(int Total,String Description){
            TaskList.Add(new Task(Total, Description));
        }
        public void DrawAll(){
            int cnt = 0;
            foreach(Task t in TaskList){
                Console.Write("[{0}]",cnt);
                cnt += 1;
                t.DrawProgress();
            }
        }
        public void Print(int Index){
            ((Task)TaskList[Index]).DrawProgress();
        }
        public void SetProgress(int Index,String Operation){
            ((Task)TaskList[Index]).SetProgress(Operation);
        }
        public void PrintList(){
            for (int i = 0; i < TaskList.Count; i++){
                Console.Write("[{0}]", i);
                ((Task)TaskList[i]).PrintDescription();
            }
        }
        public void Remove(int Index){
            TaskList.RemoveAt(Index);
        }
        public void Write(String URI){
            StreamWriter sw = new StreamWriter(URI);
            for (int i = 0; i < TaskList.Count; i++){
                Task task = (Task)TaskList[i];
                String Description;
                int Total, Finished;
                Description = task.GetDescription();
                (Finished, Total) = task.GetProgress();
                sw.Write("{0} {1} {2}\n", Finished, Total, Description);
            }
            sw.Close();
        }
        public void Read(String URI){
            StreamReader sr = new StreamReader(URI);
            string line;
            int cnt = 0;
            while((line = sr.ReadLine()) != null){
                string[] strs = line.Split(' ');
                int Total;
                String Description,Finished;
                Finished = strs[0];
                Total = Int32.Parse(strs[1]);
                Description = strs[2];
                TaskList.Add(new Task(Total, Description));
                ((Task)TaskList[cnt]).SetProgress(Finished);
                cnt++;
            }
            sr.Close();
        }

    }
    class Program
    {
        static String URI = System.AppDomain.CurrentDomain.BaseDirectory + "/users.data";
        static void PrintHelp(){
            Console.WriteLine("Save file:{0}",URI);
            Console.WriteLine("-a [TOTAL] [DESCRIPTION]: 添加一项任务，参数为总进度和名称，不能包含空格");
            Console.WriteLine("-h: 输出帮助信息");
            Console.WriteLine("-u [Index]: 更新某个任务的进度");
            Console.WriteLine("-l: 获取任务列表");
            Console.WriteLine("-rm [Index]: 删除某个任务");
            Console.WriteLine("-p： 输出所有任务的进度，如果跟参数，则输出单个任务的进度");
        }
        static void AddTask(string[] args){
            Tasks list = new Tasks();
            list.Read(URI);
            list.Add(Int32.Parse(args[1]), args[2]);
            list.Write(URI);
        }
        static void UpdateTask(string[] args){
            Tasks list = new Tasks();
            list.Read(URI);
            list.SetProgress(Int32.Parse(args[1]), args[2]);
            list.Write(URI);
        }
        static void PrintTask(string[] args){
            Tasks list = new Tasks();
            list.Read(URI);
            if(args.Length == 1){
                list.DrawAll();
            }else{
                list.Print(Int32.Parse(args[1]));
            }
        }
        static void PrintList(){
            Tasks list = new Tasks();
            list.Read(URI);
            list.PrintList();
        }
        static void Remove(int index){
            Tasks list = new Tasks();
            list.Read(URI);
            list.Remove(index);
            list.Write(URI);
        }
        static void Main(string[] args)
        {
            if(args.Length == 0){
                return;
            }

            switch(args[0]){
                case "-h":
                    PrintHelp();
                    break;
                case "-a":
                    AddTask(args);
                    break;
                case "-u":
                    UpdateTask(args);
                    break;
                case "-l":
                    PrintList();
                    break;
                case "-rm":
                    Remove(Int32.Parse(args[1]));
                    break;
                case "-p":
                    PrintTask(args);
                    break;
                default:
                    PrintHelp();
                    break;
            }
        }
    }
}

languages: C# Markdown