[text] P

Viewer

  1. #include <SFML/Graphics.hpp>
  2. #include <iostream>
  3.  
  4. const int TILE_SIZE = 40;
  5. const int MAP_WIDTH = 15;
  6. const int MAP_HEIGHT = 15;
  7. const int WINDOW_WIDTH = TILE_SIZE * MAP_WIDTH;
  8. const int WINDOW_HEIGHT = TILE_SIZE * MAP_HEIGHT;
  9. const int PACMAN_SPEED = 4;
  10.  
  11. enum class Direction { Up, Down, Left, Right };
  12.  
  13. class Pacman {
  14. public:
  15.     Pacman();
  16.     void move(Direction dir);
  17.     void draw(sf::RenderWindow& window);
  18.     sf::FloatRect getBounds() const;
  19.  
  20. private:
  21.     sf::Texture texture;
  22.     sf::Sprite sprite;
  23.     Direction currentDirection;
  24. };
  25.  
  26. Pacman::Pacman() {
  27.     texture.loadFromFile("pacman.png");
  28.     sprite.setTexture(texture);
  29.     sprite.setPosition(100, 100);
  30.     currentDirection = Direction::Right; // Pacman starts moving right by default
  31. }
  32.  
  33. void Pacman::move(Direction dir) {
  34.     currentDirection = dir;
  35.     switch (dir) {
  36.         case Direction::Up:
  37.             sprite.move(0, -PACMAN_SPEED);
  38.             break;
  39.         case Direction::Down:
  40.             sprite.move(0, PACMAN_SPEED);
  41.             break;
  42.         case Direction::Left:
  43.             sprite.move(-PACMAN_SPEED, 0);
  44.             break;
  45.         case Direction::Right:
  46.             sprite.move(PACMAN_SPEED, 0);
  47.             break;
  48.     }
  49. }
  50.  
  51. void Pacman::draw(sf::RenderWindow& window) {
  52.     window.draw(sprite);
  53. }
  54.  
  55. sf::FloatRect Pacman::getBounds() const {
  56.     return sprite.getGlobalBounds();
  57. }
  58.  
  59. int main() {
  60.     sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Pacman");
  61.  
  62.     Pacman pacman;
  63.  
  64.     while (window.isOpen()) {
  65.         sf::Event event;
  66.         while (window.pollEvent(event)) {
  67.             if (event.type == sf::Event::Closed) {
  68.                 window.close();
  69.             }
  70.             if (event.type == sf::Event::KeyPressed) {
  71.                 if (event.key.code == sf::Keyboard::Up)
  72.                     pacman.move(Direction::Up);
  73.                 else if (event.key.code == sf::Keyboard::Down)
  74.                     pacman.move(Direction::Down);
  75.                 else if (event.key.code == sf::Keyboard::Left)
  76.                     pacman.move(Direction::Left);
  77.                 else if (event.key.code == sf::Keyboard::Right)
  78.                     pacman.move(Direction::Right);
  79.             }
  80.         }
  81.  
  82.         window.clear();
  83.         pacman.draw(window);
  84.         window.display();
  85.     }
  86.  
  87.     return 0;
  88. }
  89.  

Editor

You can edit this paste and save as new:


File Description
  • P
  • Paste Code
  • 19 Apr-2024
  • 2.34 Kb
You can Share it: