No Description
Rafael Arce Nazario 00bb92cc14 CPP ahora no contiene soluciones 8 years ago
images initial commit 9 years ago
README.md Rafa aNadio preguntas diagnosticas 8 years ago
basket01.pro initial commit 9 years ago
classesBasket.html initial commit 9 years ago
classesBasket.md initial commit 9 years ago
main.cpp CPP ahora no contiene soluciones 8 years ago

README.md

English | Español

Clases - Baloncesto

main1.png main2.png main3.png

[Versión 2016-05-02]

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 contiene metodos, i.e. acciones que puede realizar sobre sus propiedades o sobre otros objetos. 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 la implementación de una clase y 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.



El juego

El esqueleto de programa que te proveemos simula un partido de baloncesto entre dos jugadores. El programa utiliza OOP y simula el partido creando un objeto de clase BBPlayer para cada jugador e invocando sus métodos. El objeto que representa cada jugador contiene atributos tales como el nombre del jugador y estádisticas de juego, e.g. tiros intentados y anotados. Durante el juego, cada tiro anotado vale dos puntos. 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.

El algoritmo que simula el juego es el siguiente:

1.  inicializar jugadores
2.  asignar jugadorEnOfensiva aleatoriamente
2.  while (ninguno ha ganado):
3.    simular tiro al canasto
4.    if (anotó):
5.      actualizar estadisticas de quien tiró al canasto
6.      if (puntuación >= 32):
7.        informar que jugadorEnOfensiva ganó
8.      else:
9.        intercambiar jugadorEnOfensiva
10.   else:
11.     actualizar estadisticas de quien tiró al canasto
11.     determinar quien atrapa rebote
12.     actualizar estadisticas de quien atrapó rebote
13.     asignar jugadorEnOfensiva
14. mostrar estadísticas de los jugadores

La clase BBPlayer

Para esta experiencia de laboratorio, definirás una clase BBPlayer que contenga los atributos y métodos que se describen a continuación. 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 el orden y tipo de sus parámetros.

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 asigna 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; durante el juego 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 atrapados por juego; durante el juego se usa para determinar cuál de los jugadores atrapa un rebote. (método incluido en main.cpp)
  • shotMade(): método que registra que se anotó un tiro, i.e. incrementa _shotsMade, _shotsTaken y el _score del jugador.
  • shotMissed(): método que registra tiro fallado, i.e. incrementa solo _shotsTaken del jugador.
  • reboundMade(): método que registra un rebote atrapado.
  • 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)


!INCLUDE “../../eip-diagnostic/basket/es/diag-basket-01.html” !INCLUDE “../../eip-diagnostic/basket/es/diag-basket-02.html”



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 la definición de algunos métodos. Tu debes completar el resto.

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, debes irlas descomentando, probando y modificando la función hasta que pase la prueba. Una vez todas las funciones estén listas y hayan pasado las pruebas, probarás 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. Descarga la carpeta classes-basket de Bitbucket usando un terminal, moviéndote al directorio Documents/eip, y escribiendo el comando git clone http://bitbucket.org/eip-uprrp/classes-basket.

  2. Carga a Qt creator el proyecto basket01 haciendo doble “click” en el archivo basket01.pro que se encuentra en la carpeta Documents/eip/classes-basket de tu computadora.

  3. El ejecutable 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.

  4. Estudia 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 proveen en la sección La clase BBPlayer. Para cada uno de los métodos que se especifican en esa sección:

    a. Incluye su prototipo en la definición de la clase

    b. Si el método ya ha sido implementado, remueve los comentarios de las secciones correspondientes a esa función en test_BBPlayer.

    c. Si el método no ha sido implementado, hazlo 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, i.e. debe contener el mensaje All unit tests passed!!! . Si no pasa las pruebas, revisa tu código. Repite hasta que tu código haya pasado todas 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 los métodos definidos y probados, 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)


!INCLUDE “../../eip-diagnostic/basket/en/diag-basket-01.html” !INCLUDE “../../eip-diagnostic/basket/en/diag-basket-02.html”



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