Browse Source

Lab initial commit

Jose Ortiz 8 years ago
commit
2f1fb8abc1

+ 33
- 0
CarScrollingGame.pro View File

@@ -0,0 +1,33 @@
1
+#-------------------------------------------------
2
+#
3
+# Project created by QtCreator 2014-06-18T23:35:47
4
+#
5
+#-------------------------------------------------
6
+
7
+QT       += core gui
8
+
9
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
10
+
11
+TARGET = GenericScrollingGame5
12
+TEMPLATE = app
13
+
14
+
15
+SOURCES += main.cpp\
16
+        mainwindow.cpp \
17
+    obstacle.cpp \
18
+    flag.cpp \
19
+    play.cpp \
20
+    car.cpp \
21
+    work.cpp
22
+
23
+HEADERS  += mainwindow.h \
24
+    obstacle.h \
25
+    flag.h \
26
+    play.h \
27
+    car.h
28
+
29
+FORMS    += mainwindow.ui
30
+
31
+RESOURCES += \
32
+    images.qrc
33
+

+ 140
- 0
README.md View File

@@ -0,0 +1,140 @@
1
+[English](#markdown-header-selection-structures-car-scrolling-game) | [Español](#markdown-header-estructuras-de-seleccion-juego-de-desplazamiento-de-coche)
2
+
3
+# Estructuras de Selección - Juego de Desplazamiento de coche
4
+
5
+En casi todas las instancias en que queremos resolver un problema hay una o más opciones que dependen de si se cumplen o no ciertas condiciones. Los programas de computadoras se construyen para resolver problemas y, por lo tanto, deben tener una estructura que permita tomar decisiones. En C++ las instrucciones de decisión (o condicionales) se estructuran utilizando if, else, else if o switch. Muchas veces el uso de estas estructuras también envuelve el uso de expresiones de relación y operadores lógicos. En la experiencia de laboratorio de hoy practicarás el uso de algunas estructuras de decisión completando el diseño de una aplicación de juego de colisiones de carros con obstáculos en una pista.
6
+
7
+![](images/csg01.png)
8
+
9
+## Objetivos:
10
+
11
+1. Utilizar expresiones relacionales y seleccionar operadores lógicos adecuados para la toma de decisiones.
12
+2. Aplicar estructuras de decisión.
13
+
14
+## Pre-Lab:
15
+
16
+Antes de llegar al laboratorio debes:
17
+
18
+1. Haber repasado los siguientes conceptos:
19
+    a. operadores lógicos
20
+    b. if, else, else if, switch
21
+
22
+2. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
23
+
24
+3. Haber tomado el quiz Pre-Lab que se encuentra en Moodle.
25
+
26
+## Juego de Desplazamiento de coche.
27
+
28
+Los juegos de colisiones consisten en un objeto esquivando la posible colisión contra otros objetos que puede descontar puntos o hacer perder el juego, y/o provocar la colisión con otros objetos que acumulan puntos.  En el juego de esta experiencia el objeto es un carrito, los objetos que causan que el juego pare son pinos, agujeros, entre otros y los otros objetos que suman puntos son las banderas.
29
+
30
+Los controles del juego son bien sencillos, la tecla hacia arriba desplaza el carro hacia arriba y la tecla hacia abajo desplaza el carro hacia abajo.  El carro es desplazado hacia arriba y hacia abajo para esquivar los obstáculos y para capturar las banderas.  De haber una colisión con un obstáculo el juego se detiene.  El jugador puede continuar marcando el botón de `Retry`.
31
+
32
+## Sesión de laboratorio:
33
+
34
+En esta experiencia de laboratorio practicarás el uso de expresiones matemáticas y estructuras condicionales para implementar la detección de colisiones del carrito contra los obstáculos y contra las banderas.  
35
+
36
+Tu tarea es completar el diseño de la aplicación del juego. 
37
+
38
+
39
+### Ejercicio 1: Familiarizate con las funciones pre-definidas 
40
+
41
+El primer paso en esta experiencia de laboratorio es familiarizarte con las funciones pre-definidas en el código.  Pon enfazis en las funciones:
42
+
43
+* `Car::getYCar()` - Devuelve la posición Y del carro en la pista.
44
+* `Flag::getXFlag()` - Devuelve la posición X de la bandera en la pista.
45
+* `Flag::getYFlag()` - Devuelve la posición Y del bandera en la pista.
46
+* `Obstacle::getXObstacle()` - Devuelve la posición X del obstáculo en la pista.
47
+* `Obstacle::getYObstacle()` - Devuelve la posición Y del obstáculo en la pista.
48
+* `Play::setScore(n)` - Recibe un número entero y lo suma a la puntuación del juego.
49
+* `Flag::hide()` - Esconde la bandera.  Desaparece de la pista.
50
+
51
+Invocarás estas funciones en el código que completarás para detectar las colisiones.  Note que no hay función getXCar() porque el carro nunca se mueve del eje de X.  
52
+
53
+**Instrucciones**
54
+
55
+1. Carga a Qt creator el proyecto `CarScrollingGame`  haciendo doble "click" en el archivo `CarScrollingGame.pro` en el directorio `Documents/eip/Conditionals-CarScrollingGame` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/conditionals-carscrollinggame` para descargar la carpeta `Conditionals-CarScrollingGame` a tu computadora.
56
+
57
+2. Configura el proyecto. El proyecto consiste de varios archivos. **Solo escribirás código en el archivo** `work.cpp` **. No debes cambiar nada en los demás archivos.** Sin embargo, debes familiarizarte con las funciones que ya están definidas en ellos, ya que usarás algunas de ellas para crear tu código.
58
+
59
+    * `obtstacle.cpp` y `obstacle.h`: contienen las funciones del objeto Obstacle
60
+    * `flag.cpp` y `flag.h`: contienen las funciones del objeto Flag
61
+    * `car.cpp` y `flag.h`: contienen las funciones del objeto Car
62
+
63
+### Ejercicio 2: Completar la función para cambiar la pista del juego.
64
+
65
+La función `setTrack(Track track_type)` recibe un variable de tipo `Track` que puede contener los valores:
66
+    
67
+    * play::DAY - para la pista de día
68
+    * play::NIGHT - para la pista de la noche
69
+    * play::BEACH - para la pista de la playa
70
+    * play::CANDYLAND - para la pista de dulces
71
+
72
+Esta función cambia el ambiente de la pista del juego dependiendo del tipo de track que se recibe.  En este ejercicio el estudiante utilizará la estructura de condición de C++ **switch** para cambiar los atributos de la pista.
73
+
74
+Los atributos que se pueden cambiar de la pista son: 
75
+
76
+    * la imagen de la pista usando la función `setTrackPixmap()`
77
+    * la imagen de los obstáculos usando la función `setObstaclesPixmap()`
78
+
79
+La función `setTrackPixmap(Track )` recibe una variable de tipo Track que puede ser un valor entre (**play::DAY**, **play::NIGHT**, **play::BEACH**, **play::CANDYLAND**)
80
+
81
+La función setObstaclePixmap(string) recibe una variable de tipo string que puede ser un valor entre (**"hole"**, **"cone"**, **"it"**, **"zombie"**, **"spongebob"**, **"patric"**, **"monster"**).
82
+
83
+En este ejercicio debes completar la función `setTrack()` de tal manera que utilizando la estructura de selección **switch**  se cambie la pista con el valor de tipo Track que la función `setTrack()` recibe y si el tipo de pista que se recibe es:
84
+
85
+* play::DAY - los obstáculos sean de tipo "hole" o "cone", si el  
86
+* play::NIGHT - los obstáculos sean de tipo "it" o "zombie"
87
+* play::BEACH - los obstáculos sean de tipo "spongebob" o "patric"
88
+* play::CANDYLAND - los obstáculos sean de tipo "monster"
89
+
90
+En las opciones que tengan dos posibles obstáculos utilze la función rand() para escoger aleatoriamente entre un obstáculo u otro.
91
+
92
+
93
+### Ejercicio 2: Completar la función para colisiones con obstáculos. 
94
+
95
+En este ejercicio completaras la función `obstacleCollision(Obstacle obs, Car car)` que recibe un objeto de tipo `Obstacle` y otro objeto de tipo `Car` utilizando la estructura de selección `if/else` para detectar una colisión entre el obstáculo y el carro.  La función devuelve cierto si hay colisión y falso si no hay colisión.
96
+
97
+Para detectar la colisión debe solicitar las coordenadas del obstáculo y la coordenada Y del carro.  Recuerde que el carro no se desplaza en la coordenada **X**.  Por ende para que ocurra una colisión con el carro, el obstáculo debe estar en la misma coordenada **X** del carro y a una distancia del centro del carro hacia los lados en la coordenada **Y**.  La coordenada **X** del carro se encuentra guardada en la variable constante `CARX`.  El rango de distancia del centro del carro hacia los lados se encuentra guardada en la variable constante `OBSTACLERANGE`.
98
+
99
+Si se detecta una colisión la función debe devolver `true` y si no debe devolver `false`.
100
+
101
+### Ejercicio 3: Completar la función para colisiones con banderas.
102
+
103
+En este ejercicio completarás la función `flagCollision(Obstacle obs, Car car)` que recibe un objeto de tipo `Obstacle` y otro objeto de tipo `Flag` utilizando la estructura de selección `if/else` para detectar una colisión entre la bandera y el carro.  Esta función es bien similar a la del ejericio 2, excepto que esta función no devuelve nada.  Las acciones que se toman cuando se detecta la colisión se van a tomar dentro de la función.
104
+
105
+En este caso si se detecta una colisión, se debe aumentar la puntuación del juego 30 puntos utilizando la función `setScore()` y esconder la bandera para que cree la ilusión de que se recogió la bandera en la colisión utilizando la función `flag.hide()`.
106
+
107
+
108
+
109
+
110
+    
111
+
112
+---
113
+
114
+[English](#markdown-header-selection-structures-car-scrolling-game) | [Español](#markdown-header-estructuras-de-seleccion-juego-de-desplazamiento-de-carro)
115
+
116
+# Selection Structures - Car Scrolling Game
117
+
118
+
119
+# Objectives
120
+
121
+Throughout this exercise the students will practice:
122
+
123
+* if/else
124
+* do/while
125
+* setter/getters
126
+
127
+## Concepts
128
+
129
+This laboratory consist on a simple side scrolling game. The user controls a car on the left edge of the screen, that can be moved up and down. Obstacles and checkpoints are created on the right edge of the screen, and these scroll toward the user on the left edge. The user earns a score, shown at the bottom, and the game ends when the user hits an obstacle. This laboratory is an adaptation of the assigment presented by Dave Feinberg [1].
130
+
131
+## Exercise 1
132
+
133
+
134
+### Deliverables
135
+
136
+In the following text box, copy the code that you developed for the program. Remember to properly comment the code and use good indentation and variable naming practices.
137
+
138
+### References
139
+[1] Dave Feinberg, http://nifty.stanford.edu/2011/feinberg-generic-scrolling-game/
140
+

+ 57
- 0
car.cpp View File

@@ -0,0 +1,57 @@
1
+#include "car.h"
2
+
3
+
4
+///
5
+/// Default Constructor for the racer class. Properties are set as follow:
6
+/// * y_car: The starting Y coordinate of the racecar
7
+///
8
+Car::Car(QWidget *parent) :
9
+    QWidget(parent)
10
+{
11
+    y_car=80;
12
+    name = ":/resources/racer.png" ;
13
+}
14
+
15
+///
16
+/// Setter for the racecar
17
+///
18
+void Car::setCar(string arg){
19
+    
20
+    if (arg == "red") name = ":/resources/racer.png";
21
+    
22
+    else if(arg== "pink") name = ":/resources/racer2.png";
23
+    
24
+    else if(arg== "green") name = ":/resources/racer3.png";
25
+    
26
+    else if(arg == "orange") name = ":/resources/racer4.png";
27
+    
28
+    else if(arg == "candy") name = ":/resources/sweetcar.png";
29
+    
30
+    else if(arg == "batman") name = ":/resources/batman.png";
31
+    
32
+    else name = ":/resources/racer5.png";
33
+    
34
+
35
+    repaint();
36
+}
37
+
38
+///
39
+/// Getter for the racecar
40
+///
41
+string Car::getCar(){
42
+    return name;
43
+}
44
+
45
+///
46
+/// Setter for the Y coordinate of the racecar
47
+///
48
+void Car::setYCar(int arg){
49
+    y_car = arg;
50
+}
51
+
52
+///
53
+/// Getter for the Y coordinate of the racecar
54
+///
55
+int Car::getYCar(){
56
+    return y_car;
57
+}

+ 33
- 0
car.h View File

@@ -0,0 +1,33 @@
1
+#ifndef RACER_H
2
+#define RACER_H
3
+
4
+#include <QWidget>
5
+#include <string>
6
+
7
+using namespace std;
8
+
9
+///
10
+/// Class that has the attributes of the racecar such as:
11
+/// * Y Coordinate
12
+/// * Name
13
+/// * Setters and Getters 
14
+///
15
+class Car : public QWidget
16
+{
17
+    Q_OBJECT
18
+public:
19
+    explicit Car(QWidget *parent = 0);
20
+    int y_car;
21
+    string name;
22
+    void setCar(string);
23
+    string getCar();
24
+    void setYCar(int);
25
+    int getYCar();
26
+
27
+signals:
28
+
29
+public slots:
30
+
31
+};
32
+
33
+#endif // RACER_H

+ 61
- 0
flag.cpp View File

@@ -0,0 +1,61 @@
1
+#include "flag.h"
2
+
3
+///
4
+/// Default constructor. The properties for the checkpoints are set as follows:
5
+/// * x_flag: x coordinates where the checkpoint will be placed
6
+/// * y_flag: y coordinates where the checkpoint will be placed
7
+/// * name:   Sets the image that will be used for the checkpoint
8
+///
9
+Flag::Flag(QWidget *parent) :
10
+    QWidget(parent)
11
+{
12
+    x_flag = 250;
13
+    y_flag = 140;
14
+    name = ":/resources/flag.png";
15
+}
16
+
17
+///
18
+/// Setter for the image of the checkpoint that will be used
19
+///
20
+void Flag::setFlag(string arg){
21
+    name = arg;
22
+}
23
+
24
+///
25
+/// Getter for the image of the checkpoint
26
+///
27
+string Flag::getFlag(){
28
+    return name;
29
+}
30
+
31
+///
32
+/// Setter for the X coordinates of the checkpoint
33
+///
34
+void Flag::setXFlag(int arg){
35
+    x_flag = arg;
36
+}
37
+
38
+///
39
+/// Setter for the Y coordinates of the checkpoint
40
+///
41
+void Flag::setYFlag(int arg){
42
+    y_flag = arg;
43
+}
44
+
45
+///
46
+/// Getter for the X coordinates of the checkpoint
47
+///
48
+int Flag::getXFlag(){
49
+    return x_flag;
50
+}
51
+
52
+///
53
+/// Getter for the Y coordinates of the checkpoint
54
+///
55
+int Flag::getYFlag(){
56
+    return y_flag;
57
+}
58
+
59
+void Flag::hide(){
60
+    setXFlag(630);
61
+}

+ 33
- 0
flag.h View File

@@ -0,0 +1,33 @@
1
+#ifndef CHECKPOINT_H
2
+#define CHECKPOINT_H
3
+
4
+#include <QWidget>
5
+#include <string>
6
+
7
+using namespace std;
8
+
9
+///
10
+/// Class that has the attributes of the flags, such as:
11
+/// * X, y coordinates
12
+/// * Name
13
+/// * Setters and Getters
14
+///
15
+class Flag : public QWidget
16
+{
17
+    Q_OBJECT
18
+public:
19
+    explicit Flag(QWidget *parent = 0);
20
+    int y_flag;
21
+    int x_flag;
22
+    string name;
23
+    int getXFlag();
24
+    int getYFlag();
25
+    void setXFlag(int);
26
+    void setYFlag(int);
27
+    void setFlag(string);
28
+    string getFlag();
29
+    void hide() ;
30
+    
31
+};
32
+
33
+#endif // CHECKPOINT_H

+ 27
- 0
images.qrc View File

@@ -0,0 +1,27 @@
1
+<RCC>
2
+    <qresource prefix="/">
3
+        <file>resources/batman.png</file>
4
+        <file>resources/candyroad.png</file>
5
+        <file>resources/cone.png</file>
6
+        <file>resources/coolroad.png</file>
7
+        <file>resources/cupcake.png</file>
8
+        <file>resources/flag.png</file>
9
+        <file>resources/hoyo.png</file>
10
+        <file>resources/it.png</file>
11
+        <file>resources/monster.png</file>
12
+        <file>resources/patrick.png</file>
13
+        <file>resources/racer.png</file>
14
+        <file>resources/racer2.png</file>
15
+        <file>resources/racer3.png</file>
16
+        <file>resources/racer4.png</file>
17
+        <file>resources/racer5.png</file>
18
+        <file>resources/road.png</file>
19
+        <file>resources/road2.png</file>
20
+        <file>resources/roadnight.png</file>
21
+        <file>resources/roadsand.png</file>
22
+        <file>resources/spongebob.png</file>
23
+        <file>resources/sweetcar.png</file>
24
+        <file>resources/zombie.png</file>
25
+        <file>resources/logo.png</file>
26
+    </qresource>
27
+</RCC>

BIN
images/csg01.png View File


+ 27
- 0
images/images.qrc View File

@@ -0,0 +1,27 @@
1
+<RCC>
2
+    <qresource prefix="/">
3
+        <file>resources/batman.png</file>
4
+        <file>resources/candyroad.png</file>
5
+        <file>resources/cone.png</file>
6
+        <file>resources/coolroad.png</file>
7
+        <file>resources/cupcake.png</file>
8
+        <file>resources/flag.png</file>
9
+        <file>resources/hoyo.png</file>
10
+        <file>resources/it.png</file>
11
+        <file>resources/monster.png</file>
12
+        <file>resources/patrick.png</file>
13
+        <file>resources/racer.png</file>
14
+        <file>resources/racer2.png</file>
15
+        <file>resources/racer3.png</file>
16
+        <file>resources/racer4.png</file>
17
+        <file>resources/racer5.png</file>
18
+        <file>resources/road.png</file>
19
+        <file>resources/road2.png</file>
20
+        <file>resources/roadnight.png</file>
21
+        <file>resources/roadsand.png</file>
22
+        <file>resources/spongebob.png</file>
23
+        <file>resources/sweetcar.png</file>
24
+        <file>resources/zombie.png</file>
25
+        <file>resources/logo.png</file>
26
+    </qresource>
27
+</RCC>

+ 14
- 0
main.cpp View File

@@ -0,0 +1,14 @@
1
+#include "mainwindow.h"
2
+#include <QApplication>
3
+#include <ctime>
4
+#include <cstdlib>
5
+
6
+int main(int argc, char *argv[])
7
+{
8
+    srand(time(NULL));
9
+    QApplication a(argc, argv);
10
+    MainWindow w;
11
+    w.show();
12
+
13
+    return a.exec();
14
+}

+ 167
- 0
mainwindow.cpp View File

@@ -0,0 +1,167 @@
1
+#include "mainwindow.h"
2
+#include "ui_mainwindow.h"
3
+#include <QDebug>
4
+
5
+///
6
+/// Default Constructor for the MainWindow. Some properties:
7
+/// * ui: Allows the user to access members of the ui
8
+/// * scene: Creates a new scene where the game will be "painted"
9
+/// * game:  Creates a new game
10
+/// * globalTimer: Creates a new timer
11
+/// * score: Getes the number of the score in a string for future use
12
+///
13
+MainWindow::MainWindow(QWidget *parent) :
14
+    QMainWindow(parent),
15
+    ui(new Ui::MainWindow)
16
+{
17
+    /*
18
+     * Sets the ui and the scene for future use.
19
+     */
20
+    ui->setupUi(this);
21
+    scene= new QGraphicsScene(this);
22
+    scene->setSceneRect(QRectF(QPointF(0,0), QPointF(0,0)));
23
+
24
+    /*
25
+     * Places the scene in the main view and then we move mainView
26
+     * so that it is centralized
27
+     */
28
+    ui->mainView->setScene(scene);
29
+    ui->mainView->setAlignment((Qt::AlignLeft | Qt::AlignTop));
30
+    ui->mainView->resize(550,345);
31
+
32
+    /*
33
+     * Here we create a new game and set the racer to red, also
34
+     * we create a timer and add the game to the scene
35
+     */
36
+    game = new play;
37
+    game->setCar("red");
38
+    globalTimer = new QTimer;
39
+    scene->addWidget(game);
40
+
41
+    /*
42
+     * Get the score and store it as a string, then we just
43
+     * move around the buttons and the labels to make the
44
+     * ui more aesthetically pleasing
45
+     */
46
+
47
+    QString score = QString::number(game->getScore());
48
+
49
+    ui->scoreLabel->setText("<h3><b>Score: </b></h3>");
50
+    ui->label->setText(score);
51
+
52
+    ui->racerLabel->setText("Racer: ");
53
+    ui->trackLabel->setText("Track: ");
54
+    ui->difficultyLabel->setText("Difficulty: ");
55
+    ui->retryButton->setEnabled(false);
56
+    setWindowTitle("Scrolling Racing Game");
57
+}
58
+
59
+///
60
+/// Default destructor
61
+///
62
+MainWindow::~MainWindow()
63
+{
64
+    delete ui;
65
+    delete scene;
66
+}
67
+
68
+///
69
+/// Starts the timer for the score and plays the game
70
+/// using the run function from the game class
71
+///
72
+void MainWindow::on_playButton_clicked()
73
+{
74
+    game->run();
75
+    connect(globalTimer,SIGNAL(timeout()),this,SLOT(score()));
76
+    globalTimer->start(120);
77
+    ui->playButton->setEnabled(false);
78
+}
79
+
80
+///
81
+/// Sets the score of the game which is based on the timer
82
+///
83
+void MainWindow::score()
84
+{
85
+    if(game->playing == false) ui->retryButton->setEnabled(true);
86
+    
87
+    else ui->retryButton->setEnabled(false);
88
+    
89
+    QString num = QString::number(game->getScore());
90
+    ui->label->setText(num);
91
+}
92
+
93
+///
94
+/// When the retry button is pressed, the timer is
95
+/// deleted and a new one is created also runs the
96
+/// new game function from the class game.
97
+///
98
+void MainWindow::on_retryButton_clicked()
99
+{
100
+    game->newGame();
101
+    delete globalTimer;
102
+    globalTimer = new QTimer;
103
+    connect(globalTimer,SIGNAL(timeout()),this,SLOT(score()));
104
+    globalTimer->start(120);
105
+}
106
+
107
+///
108
+/// Moves the racer up and down when the up, down arrows
109
+/// are pressed
110
+///
111
+void MainWindow::keyPressEvent(QKeyEvent *event){
112
+    game->keyPressEvent(event);
113
+}
114
+
115
+///
116
+/// Sets which race car the player is using
117
+///
118
+void MainWindow::on_comboBox_activated(const QString &arg1)
119
+{
120
+
121
+    game->setCar(arg1.toStdString());
122
+    repaint();
123
+}
124
+
125
+///
126
+/// Sets which track the player is racing on
127
+///
128
+void MainWindow::on_trackBox_activated(const QString &arg1)
129
+{
130
+
131
+    play::Track track_type ;
132
+
133
+    if(arg1 == "Day"){
134
+       track_type = play::DAY ;
135
+    }
136
+    else if(arg1 == "Night"){
137
+        track_type = play::NIGHT ;
138
+    }
139
+    else if(arg1 == "Beach"){
140
+        track_type = play::BEACH ;
141
+    }
142
+    else{
143
+        track_type = play::CANDYLAND ;
144
+    }
145
+    game->setTrack(track_type);
146
+    repaint();
147
+}
148
+
149
+///
150
+/// Sets the difficulty of the game and changes some
151
+/// boolean variables acoordingly
152
+///
153
+void MainWindow::on_difficultyBox_activated(const QString &arg1)
154
+{
155
+
156
+    game->level = play::EASY ;
157
+    if(arg1 == "Easy"){
158
+        game->level = play::EASY;
159
+    }
160
+    else if(arg1 == "Medium"){
161
+        game->level = play::MEDIUM;
162
+    }
163
+
164
+    else if(arg1 == "Hard"){
165
+        game->level = play::HARD;
166
+    }
167
+}

+ 46
- 0
mainwindow.h View File

@@ -0,0 +1,46 @@
1
+#ifndef MAINWINDOW_H
2
+#define MAINWINDOW_H
3
+
4
+#include <QMainWindow>
5
+#include <QGraphicsScene>
6
+#include <QTimer>
7
+#include "play.h"
8
+
9
+namespace Ui {
10
+class MainWindow;
11
+}
12
+
13
+class MainWindow : public QMainWindow
14
+{
15
+    Q_OBJECT
16
+
17
+public:
18
+    explicit MainWindow(QWidget *parent = 0);
19
+
20
+    ~MainWindow();
21
+
22
+protected:
23
+    void keyPressEvent(QKeyEvent *event);
24
+
25
+private slots:
26
+    void on_playButton_clicked();
27
+
28
+    void on_retryButton_clicked();
29
+
30
+    void on_comboBox_activated(const QString &arg1);
31
+
32
+    void on_trackBox_activated(const QString &arg1);
33
+
34
+    void on_difficultyBox_activated(const QString &arg1);
35
+
36
+public slots:
37
+    void score();
38
+
39
+private:
40
+    play *game;
41
+    Ui::MainWindow *ui;
42
+    QTimer *globalTimer;
43
+    QGraphicsScene*scene;
44
+};
45
+
46
+#endif // MAINWINDOW_H

+ 429
- 0
mainwindow.ui View File

@@ -0,0 +1,429 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<ui version="4.0">
3
+ <class>MainWindow</class>
4
+ <widget class="QMainWindow" name="MainWindow">
5
+  <property name="geometry">
6
+   <rect>
7
+    <x>0</x>
8
+    <y>0</y>
9
+    <width>550</width>
10
+    <height>574</height>
11
+   </rect>
12
+  </property>
13
+  <property name="windowTitle">
14
+   <string>MainWindow</string>
15
+  </property>
16
+  <property name="styleSheet">
17
+   <string notr="true"/>
18
+  </property>
19
+  <widget class="QWidget" name="centralWidget">
20
+   <widget class="QGraphicsView" name="mainView">
21
+    <property name="enabled">
22
+     <bool>false</bool>
23
+    </property>
24
+    <property name="geometry">
25
+     <rect>
26
+      <x>0</x>
27
+      <y>50</y>
28
+      <width>256</width>
29
+      <height>61</height>
30
+     </rect>
31
+    </property>
32
+    <property name="focusPolicy">
33
+     <enum>Qt::NoFocus</enum>
34
+    </property>
35
+    <property name="verticalScrollBarPolicy">
36
+     <enum>Qt::ScrollBarAlwaysOff</enum>
37
+    </property>
38
+    <property name="horizontalScrollBarPolicy">
39
+     <enum>Qt::ScrollBarAlwaysOff</enum>
40
+    </property>
41
+   </widget>
42
+   <widget class="QPushButton" name="playButton">
43
+    <property name="geometry">
44
+     <rect>
45
+      <x>60</x>
46
+      <y>410</y>
47
+      <width>75</width>
48
+      <height>41</height>
49
+     </rect>
50
+    </property>
51
+    <property name="font">
52
+     <font>
53
+      <weight>75</weight>
54
+      <bold>true</bold>
55
+     </font>
56
+    </property>
57
+    <property name="focusPolicy">
58
+     <enum>Qt::NoFocus</enum>
59
+    </property>
60
+    <property name="styleSheet">
61
+     <string notr="true">  background-color: #ed1c24;
62
+     border-style: outset;
63
+     border-width: 2px;
64
+     border-color:#b51218;
65
+	color:#f8f8f8;</string>
66
+    </property>
67
+    <property name="text">
68
+     <string>Play!</string>
69
+    </property>
70
+   </widget>
71
+   <widget class="QPushButton" name="retryButton">
72
+    <property name="enabled">
73
+     <bool>true</bool>
74
+    </property>
75
+    <property name="geometry">
76
+     <rect>
77
+      <x>270</x>
78
+      <y>410</y>
79
+      <width>75</width>
80
+      <height>41</height>
81
+     </rect>
82
+    </property>
83
+    <property name="font">
84
+     <font>
85
+      <weight>75</weight>
86
+      <bold>true</bold>
87
+     </font>
88
+    </property>
89
+    <property name="focusPolicy">
90
+     <enum>Qt::NoFocus</enum>
91
+    </property>
92
+    <property name="styleSheet">
93
+     <string notr="true">  background-color: #ed1c24;
94
+     border-style: outset;
95
+     border-width: 2px;
96
+     border-color:#b51218;
97
+	color:#f8f8f8;</string>
98
+    </property>
99
+    <property name="text">
100
+     <string>Retry</string>
101
+    </property>
102
+   </widget>
103
+   <widget class="QLabel" name="scoreLabel">
104
+    <property name="geometry">
105
+     <rect>
106
+      <x>170</x>
107
+      <y>420</y>
108
+      <width>51</width>
109
+      <height>21</height>
110
+     </rect>
111
+    </property>
112
+    <property name="text">
113
+     <string>Score:</string>
114
+    </property>
115
+   </widget>
116
+   <widget class="QLabel" name="label">
117
+    <property name="geometry">
118
+     <rect>
119
+      <x>230</x>
120
+      <y>420</y>
121
+      <width>46</width>
122
+      <height>21</height>
123
+     </rect>
124
+    </property>
125
+    <property name="text">
126
+     <string>0</string>
127
+    </property>
128
+   </widget>
129
+   <widget class="QLabel" name="racerLabel">
130
+    <property name="geometry">
131
+     <rect>
132
+      <x>10</x>
133
+      <y>470</y>
134
+      <width>46</width>
135
+      <height>21</height>
136
+     </rect>
137
+    </property>
138
+    <property name="text">
139
+     <string>Racer:</string>
140
+    </property>
141
+   </widget>
142
+   <widget class="QLabel" name="trackLabel">
143
+    <property name="geometry">
144
+     <rect>
145
+      <x>160</x>
146
+      <y>470</y>
147
+      <width>46</width>
148
+      <height>20</height>
149
+     </rect>
150
+    </property>
151
+    <property name="text">
152
+     <string>Track:</string>
153
+    </property>
154
+   </widget>
155
+   <widget class="QLabel" name="difficultyLabel">
156
+    <property name="geometry">
157
+     <rect>
158
+      <x>320</x>
159
+      <y>470</y>
160
+      <width>81</width>
161
+      <height>21</height>
162
+     </rect>
163
+    </property>
164
+    <property name="text">
165
+     <string>Difficulty:</string>
166
+    </property>
167
+   </widget>
168
+   <widget class="QComboBox" name="comboBox">
169
+    <property name="geometry">
170
+     <rect>
171
+      <x>60</x>
172
+      <y>470</y>
173
+      <width>91</width>
174
+      <height>22</height>
175
+     </rect>
176
+    </property>
177
+    <property name="font">
178
+     <font>
179
+      <weight>75</weight>
180
+      <bold>true</bold>
181
+     </font>
182
+    </property>
183
+    <property name="focusPolicy">
184
+     <enum>Qt::NoFocus</enum>
185
+    </property>
186
+    <property name="styleSheet">
187
+     <string notr="true">  background-color: #ed1c24;
188
+     border-style: outset;
189
+     border-width: 2px;
190
+     border-color:#b51218;
191
+	color:#f8f8f8;</string>
192
+    </property>
193
+    <item>
194
+     <property name="text">
195
+      <string>red</string>
196
+     </property>
197
+    </item>
198
+    <item>
199
+     <property name="text">
200
+      <string>pink</string>
201
+     </property>
202
+    </item>
203
+    <item>
204
+     <property name="text">
205
+      <string>green</string>
206
+     </property>
207
+    </item>
208
+    <item>
209
+     <property name="text">
210
+      <string>orange</string>
211
+     </property>
212
+    </item>
213
+    <item>
214
+     <property name="text">
215
+      <string>candy</string>
216
+     </property>
217
+    </item>
218
+    <item>
219
+     <property name="text">
220
+      <string>rarce</string>
221
+     </property>
222
+    </item>
223
+    <item>
224
+     <property name="text">
225
+      <string>batman</string>
226
+     </property>
227
+    </item>
228
+   </widget>
229
+   <widget class="QComboBox" name="trackBox">
230
+    <property name="geometry">
231
+     <rect>
232
+      <x>210</x>
233
+      <y>470</y>
234
+      <width>101</width>
235
+      <height>22</height>
236
+     </rect>
237
+    </property>
238
+    <property name="font">
239
+     <font>
240
+      <weight>75</weight>
241
+      <bold>true</bold>
242
+     </font>
243
+    </property>
244
+    <property name="focusPolicy">
245
+     <enum>Qt::NoFocus</enum>
246
+    </property>
247
+    <property name="styleSheet">
248
+     <string notr="true">  background-color: #ed1c24;
249
+     border-style: outset;
250
+     border-width: 2px;
251
+     border-color:#b51218;
252
+	color:#f8f8f8;</string>
253
+    </property>
254
+    <item>
255
+     <property name="text">
256
+      <string>Day</string>
257
+     </property>
258
+    </item>
259
+    <item>
260
+     <property name="text">
261
+      <string>Night</string>
262
+     </property>
263
+    </item>
264
+    <item>
265
+     <property name="text">
266
+      <string>Candyland</string>
267
+     </property>
268
+    </item>
269
+    <item>
270
+     <property name="text">
271
+      <string>Beach</string>
272
+     </property>
273
+    </item>
274
+   </widget>
275
+   <widget class="QComboBox" name="difficultyBox">
276
+    <property name="geometry">
277
+     <rect>
278
+      <x>390</x>
279
+      <y>470</y>
280
+      <width>111</width>
281
+      <height>22</height>
282
+     </rect>
283
+    </property>
284
+    <property name="font">
285
+     <font>
286
+      <weight>75</weight>
287
+      <bold>true</bold>
288
+     </font>
289
+    </property>
290
+    <property name="focusPolicy">
291
+     <enum>Qt::NoFocus</enum>
292
+    </property>
293
+    <property name="styleSheet">
294
+     <string notr="true">  background-color: #ed1c24;
295
+     border-style: outset;
296
+     border-width: 2px;
297
+     border-color:#b51218;
298
+	color:#ffffff;</string>
299
+    </property>
300
+    <item>
301
+     <property name="text">
302
+      <string>Easy</string>
303
+     </property>
304
+    </item>
305
+    <item>
306
+     <property name="text">
307
+      <string>Medium</string>
308
+     </property>
309
+    </item>
310
+    <item>
311
+     <property name="text">
312
+      <string>Hard</string>
313
+     </property>
314
+    </item>
315
+   </widget>
316
+   <widget class="QFrame" name="frame_2">
317
+    <property name="geometry">
318
+     <rect>
319
+      <x>-60</x>
320
+      <y>-10</y>
321
+      <width>661</width>
322
+      <height>61</height>
323
+     </rect>
324
+    </property>
325
+    <property name="styleSheet">
326
+     <string notr="true"> background-color: #ed1c24;</string>
327
+    </property>
328
+    <property name="frameShape">
329
+     <enum>QFrame::StyledPanel</enum>
330
+    </property>
331
+    <property name="frameShadow">
332
+     <enum>QFrame::Raised</enum>
333
+    </property>
334
+    <widget class="QFrame" name="frame">
335
+     <property name="geometry">
336
+      <rect>
337
+       <x>60</x>
338
+       <y>10</y>
339
+       <width>571</width>
340
+       <height>41</height>
341
+      </rect>
342
+     </property>
343
+     <property name="styleSheet">
344
+      <string notr="true">background-color:#666;</string>
345
+     </property>
346
+     <property name="frameShape">
347
+      <enum>QFrame::StyledPanel</enum>
348
+     </property>
349
+     <property name="frameShadow">
350
+      <enum>QFrame::Raised</enum>
351
+     </property>
352
+     <widget class="QLabel" name="label_2">
353
+      <property name="geometry">
354
+       <rect>
355
+        <x>190</x>
356
+        <y>10</y>
357
+        <width>241</width>
358
+        <height>21</height>
359
+       </rect>
360
+      </property>
361
+      <property name="font">
362
+       <font>
363
+        <family>Adobe Heiti Std R</family>
364
+        <pointsize>15</pointsize>
365
+        <weight>75</weight>
366
+        <bold>true</bold>
367
+       </font>
368
+      </property>
369
+      <property name="styleSheet">
370
+       <string notr="true">text-align:center;
371
+border-width: 0px;
372
+color:white
373
+;</string>
374
+      </property>
375
+      <property name="text">
376
+       <string>Scrolling Game</string>
377
+      </property>
378
+     </widget>
379
+    </widget>
380
+   </widget>
381
+   <widget class="QFrame" name="frame_3">
382
+    <property name="geometry">
383
+     <rect>
384
+      <x>350</x>
385
+      <y>400</y>
386
+      <width>201</width>
387
+      <height>61</height>
388
+     </rect>
389
+    </property>
390
+    <property name="styleSheet">
391
+     <string notr="true">background-image:url(:/resources/logo.png);</string>
392
+    </property>
393
+    <property name="frameShape">
394
+     <enum>QFrame::NoFrame</enum>
395
+    </property>
396
+    <property name="frameShadow">
397
+     <enum>QFrame::Raised</enum>
398
+    </property>
399
+   </widget>
400
+   <zorder>frame_2</zorder>
401
+   <zorder>mainView</zorder>
402
+   <zorder>playButton</zorder>
403
+   <zorder>retryButton</zorder>
404
+   <zorder>scoreLabel</zorder>
405
+   <zorder>label</zorder>
406
+   <zorder>racerLabel</zorder>
407
+   <zorder>trackLabel</zorder>
408
+   <zorder>difficultyLabel</zorder>
409
+   <zorder>comboBox</zorder>
410
+   <zorder>trackBox</zorder>
411
+   <zorder>difficultyBox</zorder>
412
+   <zorder>frame_3</zorder>
413
+  </widget>
414
+  <widget class="QMenuBar" name="menuBar">
415
+   <property name="geometry">
416
+    <rect>
417
+     <x>0</x>
418
+     <y>0</y>
419
+     <width>550</width>
420
+     <height>22</height>
421
+    </rect>
422
+   </property>
423
+  </widget>
424
+  <widget class="QStatusBar" name="statusBar"/>
425
+ </widget>
426
+ <layoutdefault spacing="6" margin="11"/>
427
+ <resources/>
428
+ <connections/>
429
+</ui>

+ 72
- 0
obstacle.cpp View File

@@ -0,0 +1,72 @@
1
+#include "obstacle.h"
2
+
3
+///
4
+/// Default constructor. The properties of the obstacles are set as follows:
5
+/// * x_cone: x coordinates where the obstacle will be placed
6
+/// * y_cone: y coordinates where the obstacle will be placed
7
+///
8
+Obstacle::Obstacle(QWidget *parent) :
9
+    QWidget(parent)
10
+{
11
+    x_obstacle=300;
12
+    y_obstacle=250;
13
+    name = ":/resources/cone.png" ;
14
+}
15
+
16
+///
17
+/// Setter for the obstacle picture
18
+///
19
+void Obstacle::setObs(string arg){
20
+    
21
+    if(arg == "cone") name = ":/resources/cone.png";
22
+    
23
+    else if (arg == "hole") name = ":/resources/hoyo.png";
24
+    
25
+    else if(arg == "monster") name = ":/resources/monster.png";
26
+    
27
+    else if(arg == "zombie") name = ":/resources/zombie.png";
28
+    
29
+    else if(arg == "it") name = ":/resources/it.png";
30
+    
31
+    else if(arg == "spongebob") name = ":/resources/spongebob.png";
32
+    
33
+    else if(arg == "patrick") name = ":/resources/patrick.png";
34
+    
35
+}
36
+
37
+///
38
+/// Getter for the obstacle picture
39
+///
40
+string Obstacle::getObs(){
41
+    return name;
42
+}
43
+
44
+///
45
+/// Setter for the X coordinate
46
+///
47
+void Obstacle::setXObstacle(int arg){
48
+    x_obstacle = arg;
49
+}
50
+
51
+///
52
+/// Setter for the Y coordinate
53
+///
54
+void Obstacle::setYObstacle(int arg){
55
+    y_obstacle = arg;
56
+}
57
+
58
+///
59
+/// Getter for the X coordinate
60
+///
61
+int Obstacle::getXObstacle(){
62
+    return x_obstacle;
63
+}
64
+
65
+///
66
+/// Getter for the Y coordinate
67
+///
68
+int Obstacle::getYObstacle(){
69
+    return y_obstacle;
70
+}
71
+
72
+

+ 32
- 0
obstacle.h View File

@@ -0,0 +1,32 @@
1
+#ifndef AVOID_H
2
+#define AVOID_H
3
+
4
+#include <QWidget>
5
+#include <string>
6
+
7
+using namespace std;
8
+
9
+/// 
10
+/// Class that has the attributes of the obstacles such as:
11
+/// * X, Y coordinates
12
+/// * Name
13
+/// * Setters and Getters
14
+///
15
+class Obstacle : public QWidget
16
+{
17
+    Q_OBJECT
18
+public:
19
+    explicit Obstacle(QWidget *parent = 0);
20
+    int x_obstacle;
21
+    int y_obstacle;
22
+    string name;
23
+    string getObs();
24
+    void setObs(string);
25
+    int getXObstacle();
26
+    int getYObstacle();
27
+    void setXObstacle(int);
28
+    void setYObstacle(int);
29
+
30
+};
31
+
32
+#endif // AVOID_H

+ 280
- 0
play.cpp View File

@@ -0,0 +1,280 @@
1
+#include "play.h"
2
+#include <QDebug>
3
+
4
+
5
+play::play(QWidget *parent) :
6
+    QWidget(parent)
7
+{
8
+    // Set the background (track) variables and coords.
9
+    x1=0;
10
+    x2=600;
11
+    setTrack(play::DAY);
12
+    repaint();
13
+
14
+    // set player score to 0
15
+    score=0;
16
+
17
+    // Set the obstacles to cones
18
+    for(int i = 0; i < 3; i++){
19
+        obs[i].setObs("cone") ;
20
+    }
21
+
22
+    // Set Car to red car by default.
23
+    car.setCar("red");
24
+
25
+    // Set level to EASY
26
+    level = EASY;
27
+
28
+    // Obstacles that will be displayed if level is changed.
29
+    obs[MEDIUM].setYObstacle(145);
30
+    obs[HARD].setYObstacle(100);
31
+
32
+    playing = false;
33
+
34
+    // Set timer event to move the background
35
+    myTimer= new QTimer(this);
36
+}
37
+
38
+play::~play(){
39
+    delete myTimer;
40
+}
41
+
42
+void play::setCar(string arg){
43
+    car.setCar(arg);
44
+}
45
+
46
+play::Track play::getTrack(){
47
+    return tt;
48
+}
49
+
50
+void play::paintEvent(QPaintEvent *){
51
+    QPainter p(this);
52
+    QString scar = QString::fromStdString(car.getCar());
53
+    QString check = QString::fromStdString(flag.name);
54
+    QString road = QString::fromStdString(track);
55
+    QString cone = QString::fromStdString(obs[0].getObs());
56
+
57
+    // Check if there is a collision every time the car is moved
58
+    collision();
59
+
60
+    // Check if there is a collision with the flag
61
+    flagCollision(flag, car);
62
+
63
+    // Draws the track
64
+    p.drawPixmap(x1,0,600,400,QPixmap(road));
65
+    p.drawPixmap(x2,0,610,400,QPixmap(road));
66
+
67
+    // Draws the obstacles.
68
+    for(int i = 0; i <= level; i++){
69
+        p.drawPixmap(obs[i].getXObstacle(),obs[i].getYObstacle() + i,35,35,QPixmap(cone));
70
+    }
71
+
72
+    //Draws the flag
73
+    p.drawPixmap(flag.getXFlag(),flag.getYFlag(),50,50,QPixmap(check));
74
+    // Draws the Car
75
+    p.drawPixmap(10,car.getYCar(),80,50,QPixmap(scar));
76
+
77
+    //Updates the obstacles always that there is a new scene
78
+        if (x1 < -600){
79
+            updateObs();
80
+            x1 = 599;
81
+        }
82
+    // Same as above but with new background.
83
+        if(x2 < -600){
84
+            updateObs();
85
+            x2 = 599;
86
+        }
87
+
88
+    // increase player score.
89
+    setScore();
90
+}
91
+
92
+int play::randInt(int min, int max){
93
+    return qrand() % ((max +1 )- min) +  min ;
94
+}
95
+
96
+// Whenever there is collision with an obstacle the game
97
+// is stoped.
98
+void play::stopGame(){
99
+    myTimer->stop();
100
+}
101
+
102
+// Function to increase the player score.
103
+void play::setScore(int n){
104
+    score += n ;
105
+}
106
+
107
+// Returns the score.
108
+int play::getScore(){
109
+    return score;
110
+}
111
+
112
+
113
+// Function called everytime a timer event ocurrs.
114
+// It repaints the graphics of the game.
115
+void play::mySlot(){
116
+
117
+    //moves road, obstacles, flags
118
+    x1 = x1-STEPS;
119
+    x2 = x2-STEPS;
120
+
121
+    for(int i = 0; i <= level; i++){
122
+        obs[i].setXObstacle(obs[i].getXObstacle() - STEPS);
123
+    }
124
+    flag.setXFlag(flag.getXFlag()-STEPS);
125
+
126
+    repaint();
127
+}
128
+
129
+// Restart the timer
130
+void play::run(){
131
+    playing = true;
132
+    connect(myTimer, SIGNAL(timeout()), this, SLOT(mySlot()));
133
+    myTimer->start(16);
134
+}
135
+
136
+// Resets the game to its initial state if the game is reset.
137
+void play::newGame(){
138
+    x1 = 0;
139
+    x2 = 600;
140
+    score=0;
141
+    myTimer = new QTimer(this);
142
+    setTrack(getTrack());
143
+
144
+    //moves road, obstacles, flags
145
+    x1 = x1-STEPS;
146
+    x2 = x2-STEPS;
147
+
148
+    for(int i = 0; i <= level; i++){
149
+        obs[i].setXObstacle(obs[i].getXObstacle() - STEPS);
150
+    }
151
+    flag.setXFlag(flag.getXFlag()-STEPS);
152
+
153
+    repaint();
154
+    run();
155
+}
156
+
157
+// Sets the images of the obstacles.
158
+void play::setObstaclesPixmap(string pixmap){
159
+
160
+    for (int i = 0; i < 3; i++){
161
+        obs[i].setObs(pixmap) ;
162
+    }
163
+}
164
+
165
+// Event for the controls of the car.
166
+void play::keyPressEvent(QKeyEvent *event){
167
+
168
+    if((event->key() == Qt::Key_Up) && car.getYCar() > 80){
169
+        car.setYCar(car.getYCar()-30);
170
+    }
171
+
172
+    if((event->key() == Qt::Key_Down) && car.getYCar() < 280){
173
+        car.setYCar(car.getYCar()+30);
174
+    }
175
+
176
+}
177
+
178
+
179
+// Updates the obstacles position. Called from the Paint function when
180
+// the trac is finished.
181
+void play::updateObs(){
182
+
183
+int obstacles[4] ;
184
+int shuffle_start ;
185
+int xflag = x1 ;
186
+int xobs = x1;
187
+
188
+    updateObstacleYCoordinate(obstacles[0], obstacles[1], obstacles[2], obstacles[3]);
189
+
190
+    if (x1 < 600){
191
+        xflag = 600;
192
+        xobs = 550;
193
+    }
194
+
195
+    if( x1 < 600 || x2 < 600){
196
+        shuffle_start = randInt(0,3) ;
197
+        flag.setYFlag(obstacles[shuffle_start]);
198
+        flag.setXFlag(xflag);
199
+        for(int i = 0; i < 3; i++){
200
+            obs[i].setYObstacle(obstacles[(shuffle_start + i + 1) % 4]);
201
+            obs[i].setXObstacle(xobs);
202
+        }
203
+    }
204
+
205
+}
206
+
207
+
208
+// Function to detect collisions with the obstacles.
209
+void play::collision(){
210
+    // There will be at least obstacle no matter the
211
+    // game level, check collision with first obstacle
212
+    if(obstacleCollision(obs[0], car)){
213
+        //qDebug() << "Collision!!" ;
214
+        stopGame();
215
+        playing = false ;
216
+    }
217
+    // If there is no collision with first obstacle, but
218
+    // there is a second obstacle, check collision
219
+    else if(level > EASY && obstacleCollision(obs[1], car)){
220
+          //qDebug() << "Collision!!" ;
221
+          stopGame();
222
+          playing = false ;
223
+    }
224
+    //If there is no collision with the previous 2 obstacles,
225
+    //but there is a third obstacle, check collision
226
+    else if(level == HARD && obstacleCollision(obs[2], car)){
227
+          //qDebug() << "Collision!!" ;
228
+          stopGame();
229
+          playing = false ;
230
+    }
231
+
232
+}
233
+
234
+
235
+void play::updateObstacleYCoordinate(int &obj1, int &obj2, int &obj3, int &obj4){
236
+    // The game presents 3 bad obstacle and one safe obstacle every x distance.
237
+    // In this function you will compute the Y coordinate of such obstacles.
238
+    // You need make sure that no two obstacle overlap each other.
239
+    // Each obstacle is 40px of height, the top coordinate of the racetrack is
240
+    // 80px and the bottom coordinate of the racetrack is 280.
241
+    // Hint randInt(min, max)
242
+
243
+    obj1 = randInt(80, 245 - 40*4) ;
244
+
245
+    obj2 = randInt(obj1 + 40, 245 - 40 * 3) ;
246
+
247
+    obj3 = randInt(obj2 + 40, 245 - 40 * 2) ;
248
+
249
+    obj4 =  randInt(obj3 + 40, 245) ;
250
+
251
+    //qDebug() << obj1 << obj2 << obj3 << obj4 ;
252
+
253
+}
254
+
255
+void play::setTrackPixmap(Track track_type){
256
+
257
+    tt  = track_type ;
258
+
259
+    switch(track_type){
260
+        case play::DAY:
261
+            //All background picture follow the same path but with different names e.g. ":/resources/blahblah.png"
262
+            track = ":/resources/coolroad.png" ;
263
+        break ;
264
+        case play::NIGHT:
265
+            track = ":/resources/roadnight.png";
266
+        break ;
267
+        case play::BEACH:
268
+            track = ":/resources/roadsand.png";
269
+        break ;
270
+        case play::CANDYLAND:
271
+            track = ":/resources/candyroad.png";
272
+        break ;
273
+    } ;
274
+
275
+}
276
+
277
+string play::getTrackPixmap(){
278
+
279
+    return track ;
280
+}

+ 77
- 0
play.h View File

@@ -0,0 +1,77 @@
1
+#ifndef PLAY_H
2
+#define PLAY_H
3
+
4
+#include <QTimer>
5
+#include <QtGui>
6
+#include <QtCore>
7
+#include <QWidget>
8
+#include <QPainter>
9
+#include <string>
10
+#include <vector>
11
+#include "obstacle.h"
12
+#include "flag.h"
13
+#include "car.h"
14
+
15
+using namespace std;
16
+
17
+const int STEPS = 10 ;
18
+const int CARX = 70 ;
19
+const int FLAGRANGE = 20;
20
+const int OBSTACLERANGE = 30 ;
21
+
22
+class play : public QWidget
23
+{
24
+    Q_OBJECT
25
+public:
26
+    enum Difficulty {EASY, MEDIUM, HARD} ;
27
+    enum Track {DAY, NIGHT, BEACH, CANDYLAND} ;
28
+
29
+    explicit play(QWidget *parent = 0);
30
+
31
+    int x1;
32
+    int x2;
33
+
34
+    int y_car;
35
+    int score;
36
+    Difficulty level ;
37
+    bool playing;
38
+    void collision();
39
+    void keyPressEvent(QKeyEvent *event);
40
+    void setScore(int = 1);
41
+    void setCar(string);
42
+    int getScore();
43
+    void updateObs();
44
+    void updateObstacleYCoordinate(int &, int &, int &, int &) ;
45
+    string track;
46
+    Track tt ;
47
+    void setTrack(Track);
48
+    void setTrackPixmap(Track) ;
49
+    string getTrackPixmap() ;
50
+    Track getTrack();
51
+    void stopGame();
52
+
53
+
54
+    ~play();
55
+
56
+public slots:
57
+    void mySlot();
58
+    void run();
59
+    void newGame();
60
+
61
+protected:
62
+    void paintEvent(QPaintEvent *);
63
+    int randInt(int min, int max) ;
64
+    void setObstaclesPixmap(string) ;
65
+    bool obstacleCollision(Obstacle &, Car &) ;
66
+    void flagCollision(Flag &, Car &);
67
+
68
+    QTimer *myTimer;
69
+
70
+    Obstacle obs[3];
71
+    Flag flag;
72
+    Car car;
73
+
74
+
75
+};
76
+
77
+#endif // PLAY_H

BIN
resources/Thumbs.db View File


BIN
resources/batman.png View File


BIN
resources/candyroad.png View File


BIN
resources/cone.png View File


BIN
resources/coolroad.png View File


BIN
resources/cupcake.png View File


BIN
resources/flag.png View File


BIN
resources/hoyo.png View File


BIN
resources/it.png View File


BIN
resources/logo.png View File


BIN
resources/monster.png View File


BIN
resources/patrick.png View File


BIN
resources/racer.png View File


BIN
resources/racer2.png View File


BIN
resources/racer3.png View File


BIN
resources/racer4.png View File


BIN
resources/racer5.png View File


BIN
resources/road.png View File


BIN
resources/road2.png View File


BIN
resources/roadnight.png View File


BIN
resources/roadsand.png View File


BIN
resources/spongebob.png View File


BIN
resources/sweetcar.png View File


BIN
resources/zombie.png View File


+ 49
- 0
work.cpp View File

@@ -0,0 +1,49 @@
1
+#include "play.h"
2
+#include <ctime>
3
+
4
+
5
+void play::setTrack(Track track_type){
6
+    // This function is used to set the type of track allowed for
7
+    // this game. The types of tracks are (play::DAY, play::NIGHT, play::BEACH,
8
+    // play::CANDYLAND).
9
+    // You will define a switch to select the track of the game, and
10
+    // the obstacles according to the track_type received.
11
+    // The tracks background and obstacles are:
12
+    // For track type Day
13
+    //      the obstacles are hole and cone.
14
+    // For track type Night
15
+    //      the obstacles are it or zombie
16
+    // For track type Beach
17
+    //      the obstacles are spongebob or patrick
18
+    // For track type Candyland
19
+    //      the obstacles is monster
20
+    // To set the track background simply set the variable (track) to the path of
21
+    // the background.
22
+    // To set the obstacles, use the function setObstaclesPixmap()
23
+    // For instance:   setObstaclesPixmap("cone") ;
24
+}
25
+
26
+bool play::obstacleCollision(Obstacle &obs, Car &car){
27
+    // Complete the function using the selection structure if/else
28
+    // to detect a collision between the obstacle and the car.
29
+    // Recall from the instructions that the car does not move in the
30
+    // X axis and that the fix X asix is stored in CARX.
31
+    // OBSTACLERANGE contains the range from the obstacle center to
32
+    // each side.
33
+
34
+
35
+}
36
+
37
+
38
+void play::flagCollision(Flag &flag, Car &car){
39
+    // Complete the function using the selection structure if/else
40
+    // to detect a collision between the flag and the car.
41
+    // Recall from the instructions that the car does not move in the
42
+    // X axis and that the fix X asix is stored in CARX.
43
+    // FLAGRANGE contains the range from the flag center to
44
+    // each side.
45
+    // If there is a collision set the score to 30 more points
46
+    // and hide the flag.
47
+
48
+
49
+}