This is a first part tutorial about Linux game using C++ and OpenGL libs.
Writing a C++ game can be difficult.
You will need to focus on program structure and then to know how to create the necessary classes.
Let’s see the files I used:
1 2 3 4 5 | display.cpp display.hpp game.cpp game.hpp main.cpp |
The main.cpp file is the main program.
This file will make the window program and will deal with the user.
Also, this file uses OpenGL libs.
Let’s see the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include "display.hpp" #include "game.hpp" #include <GL/glut.h> Game game; void display() { glClear(GL_COLOR_BUFFER_BIT); Display d; game.draw(d); glutSwapBuffers(); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(640 , 480); glutInitWindowPosition(100, 780); glutCreateWindow("simplegame"); glClearColor(0, 0, 0, 1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 640 , 480, 0,-1.0, 1.0); glutDisplayFunc(display); glutMainLoop(); } |
The next two files: display.cpp and display.hpp is used to display the game objects.
I use just one class: Display.
Let’s see the header file display.hpp
1 2 3 4 5 6 7 8 | #pragma once class Display { public: void bar(int x1, int y1, int x2, int y2); }; |
… and display.cpp.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include "display.hpp" #include <GL/gl.h> void Display::bar(int x1, int y1, int x2, int y2) { glColor3f(1, 1, 1); glBegin(GL_QUADS); glVertex2f(x1, y1); glVertex2f(x2, y1); glVertex2f(x2, y2); glVertex2f(x1, y2); glEnd(); } |
You can see the OpenGL source code to make a rectangle.
The next files game.cpp and game.hpp is used to make all game engine working.
The header file game.hpp is:
1 2 3 4 5 6 7 8 9 | #pragma once class Display; class Game { public: void draw(Display &) const; }; |
… and also game.cpp.
1 2 3 4 5 6 7 8 | #include "game.hpp" #include "display.hpp" void Game::draw(Display &d) const { // d.bar(100,10,20,20); } |
Let’s make the Makefile.
This can do well if you know how working g++ compiler.
1 2 3 4 5 6 7 8 9 10 | CPPFLAGS=-Wall -g OBJECTS=main.o display.o game.o TARGET=simplegame %.o: %.cpp g++ -c $(CPPFLAGS) -o $@ $< $(TARGET): $(OBJECTS) g++ $(OBJECTS) -o $(TARGET) -g -lglut main.o: main.cpp display.hpp display.o: display.cpp display.hpp game.o: game.cpp game.hpp display.hpp |
Use the command to make the binary file:
1 2 3 | $ make g++ -c -Wall -g -o main.o main.cpp g++ main.o display.o game.o -o simplegame -g -lglut |
The result is this: