Creating a simple Snake game with touchscreen button controls in C++ requires a GUI framework to handle graphics and touch input. Since you want a touchscreen interface, I'll use SFML (Simple and Fast Multimedia Library) as it supports touchscreen/mouse events and graphics rendering quite straightforwardly and works cross-platform.
cpp Copy code
#include <SFML/Graphics.hpp>
#include <deque>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <set>
using namespace sf;
const int CELL_SIZE = 20;
const int WIDTH = 30; // grid width in cells
const int HEIGHT = 20; // grid height in cells
const int WINDOW_WIDTH = CELL_SIZE * WIDTH;
const int WINDOW_HEIGHT = CELL_SIZE * HEIGHT + 100; // extra space for buttons
enum Direction { UP, DOWN, LEFT, RIGHT };
struct Point {
int x, y;
bool operator==(const Point& other) const { return x == other.x && y == other.y; }
bool operator<(const Point& other) const { return x < other.x || (x == other.x && y < other.y);}
};
class SnakeGame {
std::deque<Point> snake;
std::set<Point> apples;
Direction dir = RIGHT;
bool gameOver = false;
int score = 0;
public:
SnakeGame() {
snake.push_back({WIDTH / 2, HEIGHT / 2});
spawnApples(3);
}
void spawnApples(int count) {
int tries = 0;
while ((int)apples.size() < count && tries < 1000) {
Point p = {rand() % WIDTH, rand() % HEIGHT};
if (!occupied(p)) {
apples.insert(p);
}
tries++;
}
}
bool occupied(Point p) {
for (auto& s : snake) if (s == p) return true;
if (apples.find(p) != apples.end()) return true;
return false;
}
void changeDirection(Direction newDir) {
// Avoid moving in the opposite direction instantly
if ((dir == UP && newDir == DOWN) || (dir == DOWN && newDir == UP) ||
(dir == LEFT && newDir == RIGHT) || (dir == RIGHT && newDir == LEFT))
return;
dir = newDir;
}
void update() {
if (gameOver) return;
Point head = snake.front();
switch (dir) {
case UP: head.y -= 1; break;
case DOWN: head.y += 1; break;
case LEFT: head.x -= 1; break;
case RIGHT: head.x += 1; break;
}
// Wrap around screen edges
if (head.x < 0) head.x = WIDTH - 1;
if (head.x >= WIDTH) head.x = 0;
if (head.y < 0) head.y = HEIGHT - 1;
if (head.y >= HEIGHT) head.y = 0;
// Check self collision
for (auto& s : snake) {
if (s == head) {
gameOver = true;
return;
}
}
snake.push_front(head);
// Check if apple eaten
if (apples.find(head) != apples.end()) {
apples.erase(head);
score++;
// Spawn new apple if less than 3
if ((int)apples.size() < 3)
spawnApples(3);
}
else {
snake.pop_back();
}
}
void draw(RenderWindow& window) {
window.clear(Color::Black);
// Draw snake
RectangleShape rect(Vector2f(CELL_SIZE - 2, CELL_SIZE - 2));
rect.setFillColor(Color::Green);
for (auto p : snake) {
rect.setPosition(p.x * CELL_SIZE + 1, p.y * CELL_SIZE + 1);
window.draw(rect);
}
// Draw apples
CircleShape circle(CELL_SIZE / 2 - 2);
circle.setFillColor(Color::Red);
for (auto &a : apples) {
circle.setPosition(a.x * CELL_SIZE + 2, a.y * CELL_SIZE + 2);
window.draw(circle);
}
}
bool isGameOver() { return gameOver; }
int getScore() { return score; }
};
// Button helper class
class Button {
public:
RectangleShape shape;
Text label;
Button(Font &font, const std::string &text, Vector2f pos, Vector2f size) {
shape.setSize(size);
shape.setFillColor(Color(50, 50, 50));
shape.setPosition(pos);
label.setFont(font);
label.setString(text);
label.setCharacterSize(24);
label.setFillColor(Color::White);
FloatRect textBounds = label.getLocalBounds();
label.setOrigin(textBounds.left + textBounds.width / 2.0f,
textBounds.top + textBounds.height / 2.0f);
label.setPosition(pos.x + size.x / 2, pos.y + size.y / 2);
}
void draw(RenderWindow &window) {
window.draw(shape);
window.draw(label);
}
bool isPressed(Vector2f point) {
return shape.getGlobalBounds().contains(point);
}
void setHover(bool hover) {
if (hover)
shape.setFillColor(Color(100, 100, 100));
else
shape.setFillColor(Color(50, 50, 50));
}
};
int main() {
srand((unsigned)time(NULL));
RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Snake with Touchscreen Buttons");
window.setFramerateLimit(10); // Control game speed
Font font;
if (!font.loadFromFile("arial.ttf")) {
// Provide your own font path here or use any .ttf font available on your system
return -1;
}
SnakeGame game;
// Create buttons
Vector2f btnSize(80, 80);
float btnY = WINDOW_HEIGHT - 90;
Button btnUp(font, "↑", Vector2f(WINDOW_WIDTH / 2 - btnSize.x / 2, btnY), btnSize);
Button btnLeft(font, "←", Vector2f(WINDOW_WIDTH / 2 - btnSize.x*1.5f - 10, btnY + btnSize.y + 10), btnSize);
Button btnDown(font, "↓", Vector2f(WINDOW_WIDTH / 2 - btnSize.x / 2, btnY + btnSize.y + 10), btnSize);
Button btnRight(font, "→", Vector2f(WINDOW_WIDTH / 2 + btnSize.x / 2 + 10, btnY + btnSize.y + 10), btnSize);
while (window.isOpen()) {
Event event;
while (window.pollEvent(event)) {
if (event.type == Event::Closed)
window.close();
if (event.type == Event::TouchBegan || event.type == Event::MouseButtonPressed) {
Vector2f pos;
if (event.type == Event::TouchBegan) {
pos = Vector2f(event.touch.x, event.touch.y);
}
else if (event.type == Event::MouseButtonPressed) {
pos = Vector2f(event.mouseButton.x, event.mouseButton.y);
}
if (btnUp.isPressed(pos)) game.changeDirection(UP);
else if (btnDown.isPressed(pos)) game.changeDirection(DOWN);
else if (btnLeft.isPressed(pos)) game.changeDirection(LEFT);
else if (btnRight.isPressed(pos)) game.changeDirection(RIGHT);
}
}
game.update();
game.draw(window);
// Draw buttons
btnUp.draw(window);
btnDown.draw(window);
btnLeft.draw(window);
btnRight.draw(window);
// Draw score & Game Over text
Text scoreText;
scoreText.setFont(font);
scoreText.setCharacterSize(20);
scoreText.setFillColor(Color::White);
scoreText.setPosition(10, WINDOW_HEIGHT - 40);
scoreText.setString("Score: " + std::to_string(game.getScore()));
window.draw(scoreText);
if (game.isGameOver()) {
Text overText;
overText.setFont(font);
overText.setCharacterSize(48);
overText.setFillColor(Color::Red);
overText.setString("GAME OVER");
FloatRect bounds = overText.getLocalBounds();
overText.setOrigin(bounds.left + bounds.width / 2.0f,
bounds.top + bounds.height / 2.0f);
overText.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
window.draw(overText);
}
window.display();
}
return 0;
}
If you want me to help with build instructions or further improvements (e.g., swipe gesture controls or better touchscreen support), just ask!