No Description

classesBasket.md 17KB

English | Español

Clases - Baloncesto

main1.png main2.png main3.png

La programación orientada a objetos (object oriented programming, OOP) es un paradigma de programación que promueve el diseño de programas en el que distintos objetos interactúan entre sí para resolver un problema. C++ es uno de los lenguajes de programación que promueve la programación orientada a objetos, permitiendo que los programadores creen sus propias clases desde cero o derivadas de otras clases existentes. Algunos otros lenguajes que promueven OOP son Java, Python, javascript y PHP.

En OOP, cada objeto encapsula dentro de él ciertas propiedades sobre el ente que está modelando (por ejemplo, un objeto que modela un punto encapsula dentro de sí las coordenadas x y y del punto que representa). Además, cada objeto permite realizar ciertas acciones sobre sí, i.e. contiene sus métodos. Por ejemplo, un objeto de clase punto puede realizar la acción de cambiar el valor de su coordenada x.

Cuando la clase de objetos que necesitamos utilizar en nuestro programa no ha sido predefinida en el alguna librería, necesitamos declarar e implementar nuestra propia clase. Para esto definimos clases que contengan datos con ciertas propiedades o atributos y acciones que queremos hacer con esos datos por medio de métodos o funciones miembro. De esta manera, podremos organizar la información y procesos en objetos que tienen las propiedades y métodos de una clase. En la experiencia de laboratorio de hoy practicarás el definir una clase e implementar algunos de sus métodos completando un programa que simula un partido de baloncesto entre dos jugadores, mantiene la puntuación del juego y las estadísticas globales de los dos jugadores.

Objetivos:

  1. Diseñar y definir una clase.

  2. Implementar métodos de una clase.

Pre-Lab:

Antes de llegar al laboratorio debes haber:

  1. Repasado los conceptos relacionados a clases y objetos.

  2. Estudiado el esqueleto del programa en main.cpp.

  3. Estudiado los conceptos e instrucciones para la sesión de laboratorio.

  4. Tomado el quiz Pre-Lab que se encuentra en Moodle.



El juego

El esqueleto de programa que te proveemos simula un partido de baloncesto entre dos jugadores. Todos los tiros anotados reciben dos puntos. Se inicializan los datos con el nombre de cada jugador y sus estadísticas globales en el “torneo”: total de juegos jugados, tiros intentados, tiros anotados y rebotes. El programa incluye funciones aleatorias y fórmulas para determinar el jugador que intenta el tiro, si anota el tiro y el jugador que coge el rebote. Durante el partido simulado se mantiene la puntuación de cada jugador y se actualizan los datos para cada jugador. Al final del partido se despliega una tabla con las estadísticas.


La clase BBPlayer

Para esta experiencia de laboratorio, definirás una clase BBPlayer que contenga los atributos y métodos que se describen abajo. Como algunas de las funciones que ya están definidas en el código provisto utilizan atributos y métodos de esta clase, es importante que utilices los mismos nombres que te indicamos. El código comentado en la función main y en test_BBPlayer también te ayudará a determinar el tipo de dato que debe devolver el método y los tipos que deben tener los parámetros y el orden en que se incluyen en la declaración de la función.

Atributos

  • _name: guardará el nombre del jugador
  • _shotsTaken: guardará el número de tiros al canasto intentados durante el torneo
  • _shotsMade: guardará el número de tiros al canasto anotados durante el torneo
  • _gamesPlayed: guardará el número de juegos jugados durante el torneo
  • _rebounds: guardará el número de rebotes durante el torneo
  • _score: guardará la puntuación del jugador durante el partido

Métodos

  • constructor por defecto (default). (método incluido en main.cpp)
  • setAll(): método que asignará valor inicial a todos los atributos de un objeto. Nota que este método está invocado al comienzo de main para asignarle valores iniciales al arreglo P que es un arreglo de dos objetos de la clase BBPlayer.
  • name(): método para adquirir el nombre del jugador.
  • shotPercentage(): método para calcular el porciento de tiros anotados; se usa para “determinar” si el tiro intentado por un jugador se anota. (método incluido en main.cpp)
  • reboundsPerGame(): método para calcular el promedio de rebotes cogidos por juego; se usa para “determinar” si un jugador coge un rebote. (método incluido en main.cpp)
  • shotMade(): método que registra que se anotó un tiro, que se intentó un tiro, y actualiza la puntuación del jugador.
  • shotMissed(): método que registra tiro intentado (pero fallado).
  • reboundMade(): método que registra un rebote cogido.
  • addGame(): método que registra que se jugó un partido.
  • score(): método para adquirir la puntuación del jugador.
  • printStats(): método para desplegar las estádisticas del jugador. (método incluido en main.cpp)


Sesión de laboratorio:

Tu tarea durante la sesión de laboratorio será el definir la clase BBPlayer con los atributos y prototipos de los métodos que se listan arriba. El esqueleto del programa incluye el código para definir algunos de los métodos; otros tendrán que ser definidos.

El esqueleto del programa también incluye la función test_BBPlayer que hace pruebas unitarias a cada una de las funciones del programa. Las pruebas están comentadas y, según vayas definiendo las funciones, las vas descomentando, probando y modificando la función hasta que la prueba para esa función se pase. Una vez todas las funciones estén listas y hayan pasado las pruebas, se prueba el programa completo removiendo los comentarios que sean necesarios en el código de la función main.

Ejercicio 0: Bajar y entender el código provisto

Instrucciones

  1. Carga a QtCreator el proyecto basket01 haciendo doble “click” en el archivo basket01.pro en el directorio Documents/eip/Classes-Basket de tu computadora. También puedes ir a http://bitbucket.org/eip-uprrp/classes-basket para descargar la carpeta Classes-Basket a tu computadora.

  2. Este programa correrá en el terminal y debes seleccionar esa opción desde la ventana de “Projects”. Para acceder a esta ventana, seleccionas “Projects” en el menú vertical de la izquierda. Luego en Build & Run seleccionas Run y luego marcas la caja que dice Run in terminal.

  3. Estudia y entiende el código en el archivo main.cpp, incluyendo el código que está comentado.

Ejercicio 1: Definir la clase BBPlayer

  1. Define la clase BBPlayer con las especificaciones que se incluyen arriba. Para cada uno de los métodos que se especifican arriba:

    a. Incluye el prototipo del método en la definición de la clase

    b. Si la función correspondiente a ese método ya está codificada en el programa, remueve los comentarios de las secciones correspondientes a esa función en test_BBPlayer.

    c. Si la función correspondiente a ese método no está codificada, define la función y luego remueve los comentarios de las secciones correspondientes a esa función en test_BBPlayer.

    d. Corre el programa y verifica que haya pasado las pruebas. Debes obtener una ventana similar a la de la Figura 1. Si no pasa las pruebas, revisa tu código. Repite hasta que tu código haya pasado las pruebas.


    figure1.png

    Figura 1. Ejemplo de la pantalla que debes obtener si el código pasa las pruebas unitarias.


  2. Una vez tengas todas las funciones definidas y probadas, descomenta el código de la función main para probar el programa completo. Si el programa funciona correctamente, debes obtener una ventana que comienza de manera similar a la Figura 2 y termina como en la Figura 3.


    figure2.png

    Figura 2. Ejemplo del comienzo de la pantalla que debes obtener si el programa funciona correctamente.


    figure3.png

    Figura 3. Ejemplo de la pantalla que debes obtener al final del programa si éste funciona correctamente.


IMPORTANTE: NO debes hacer ningún cambio en las funciones main y test_BBPlayer, aparte de quitar los comentarios.



Entrega

Utiliza “Entrega” en Moodle para entregar el archivo main.cpp. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.



Referencias

[1] http://www.telegraph.co.uk/sport/olympics/basketball/9348826/London-2012-Olympics-Temi-Fagbenle-in-Team-GB-womens-basketball-squad.html

[2] http://www.musthavemenus.com/category/bar-clipart.html

[3] http://basketball.isport.com/basketball-guides/finding-your-niche-in-basketball




English | Español

Classes - Basketball

main1.png main2.png main3.png

Object Oriented Programming (OOP) is a programming paradigm that promotes the design of programs by having different objects interacting together to solve a problem. C++ is one of the programming languages that promotes object oriented programming, allowing programmers to create their own classes from scratch or derive them from other existing classes. Other languages that promote OOP are Java, Python, Javascript and PHP.

In OOP, each object encapsulates within itself certain properties about the entity being modeled (for example, an object that models a point encapsulates the coordinates x and y of the point being represented). Furthermore, each object allows certain actions to be carried out on itself with the methods that the object contains. For example, an object of class point could carry out the action of changing the value of the x coordinate.

When an object class we need to use in our program has not been predefined in a library, we need to declare and implement our own class. To do this, we define classes that contain data with certain properties or attributes and actions that we want to carry out with this data through the use of methods or member functions. This way, we can organize the information and processes in objects that have the properties and methods of a class. In today’s laboratory experience you will practice defining a class and implementing some of its methods by completing a program that simulates a basketball game between two players, maintaining the score for the game and the global statistics for the two players.

Objectives:

  1. Design and define a class.

  2. Implement methods for a class.

Pre-Lab:

Before coming to the laboratory you should have:

  1. Reviewed the concepts related to classes and objects.

  2. Studied the skeleton for the program in main.cpp.

  3. Studied the concepts and instructions for the laboratory session.

  4. Taken the Pre-Lab quiz that can be found in Moodle.



The Game

The skeleton for the program that we provide simulates a basketball game between two players. The successful throws into the basket receive two points. The data is initiated with the name of each player and the global statistics in the “tournament”: total of games played, attempted throws, successful throws and rebounds. The program includes random functions and formulas to determine the player that attempts a throw, if the player scores, and the player that takes the rebound. During the simulated game the score for each player is kept and each player’s data is updated. At the end of the game, a table with the statistics is displayed.


The BBPlayer Class

For this laboratory experience, you will define the BBPlayer class that contains the attributes and methods that are described below. Since some of the functions that are already defined in the provided code use attributes and methods of this class, it is important that you use the same names that we indicate. The commented code in the main function and in test_BBPlayer will help you determine the type of data the method should return, the types the parameters should have, and the order in which they are included in the function declaration.

Attributes

  • _name: stores the name of the player
  • _shotsTaken: stores the number of attempted throws during the tournament
  • _showsMade: stores the number of throws scored during the tournament
  • _gamesPlayed: stores the number of games played during the tournament
  • _rebounds: stores the number of rebounds during the tournament
  • _score: stores the player’s score during the game

Methods

  • default constructor. (method included in main.cpp)
  • setAll(): methods that assigns an initial value to all of the attributes of the object. Notice that this method is invoked at the beginning of main to assign initial values to the array P that is an array of two objects of the BBPlayer class.
  • name(): method to acquire the name of the player.
  • shotPercentage(): method to compute the percent of throws scored; is used to determine if the attempted throw is scored by a player. (method included in main.cpp)
  • reboundsPerGame(): method to compute the average number of rebounds caught by a player; is used to determine if the player successfully catches the rebound. (method included in main.cpp)
  • ‘shotMade()’: method that registers that a shot was scored, that a shot was attempted, and updates the score for the player.
  • shotMissed(): method that registers an attempted throw (but unsuccessful).
  • reboundMade(): method that registers that a rebound was caught.
  • addGame(): method that registers that a game was played.
  • score(): method to acquire the score of a player.
  • printStats(): method that displays a player’s statistics. (method included in main.cpp)


Laboratory Session:

During this laboratory session, your task will be to define the BBPlayer class with the attributes and method prototypes listed above. The skeleton for the program includes the code to define some of the methods; others will have to be defined.

The skeleton for the program also includes the test_BBPlayer function that does unit tests to each of the functions in the program. The tests are commented and, as you define each function, you will remove the comment, test and modify the function, until the test for that function is passed. Once all of the functions are ready and have passed the tests, the whole program is tested by removing the necessary comments in the main function.

Exercise 0: Download and understand the provided code

Instructions

  1. Load the basket01 project onto Qt by double clicking on the basket01.pro filein the directory Documents/eip/Classes-Basket of your computer. You may also go to http://bitbucket.org/eip-uprrp/classes-basket to download the Classes-Basket folder to your computer.

  2. This program will run on the terminal and you should select this option from the “Projects” window. To access this window, you select “Projects” in the vertical menu to the left. Afterwards, in Build & Run you select Run and then mark the box that says Run in terminal.

  3. Study and understand the code in the main.cpp file, including the code that is commented.

Exercise 1: Define the BBPlayer class

  1. Define the BBPlayer class with the specifications included above. For each one of the methods that are specified above:

    a. Include a prototype for the method in the class definition.

    b. If the corresponding member function is already coded in the program, remove the comments from the corresponding sections for this function in test_BBPlayer.

    c. If the corresponding member function is not coded, define the function and then remove the comments from the corresponding sections for this function in test_BBPlayer.

    d. Run the program and verify that it passed all of the tests. You should obtain a window similar to the one in Figure 1. If your code does not pass all the tests, revise your code. Repeat until your code has passed all of the tests.


    figure1.png

    Figure 1. Example of the window you should obtain if the code passes the unit tests.


  2. Once you have all of the functions defined and tested, uncomment the code in the main function to test the whole program. If the program functions correctly, you should obtain a window that starts similarly to the one in Figure 2 and finishes like the one in Figure 3.


    figure2.png

    Figure 2. Example of the start of the window you should obtain if the program functions correctly.


    figure3.png

    Figure 3. Example of the window you should obtain at the end of the program if it is working correctly.


IMPORTANT: You SHOULD NOT make any changes in the main and test_BBPlayer functions, aside from removing the comments.



Deliverables

Use “Deliverables” in Moodle to hand in the main.cpp file. Remember to use good programming techniques, include the name of the programmers involved, and document your program.



References

[1] http://www.telegraph.co.uk/sport/olympics/basketball/9348826/London-2012-Olympics-Temi-Fagbenle-in-Team-GB-womens-basketball-squad.html

[2] http://www.musthavemenus.com/category/bar-clipart.html

[3] http://basketball.isport.com/basketball-guides/finding-your-niche-in-basketball