OVERLOADING METHODS AND CONSTRUCTORS: The Ball Class

Similar documents
DRAWING AND MOVING IMAGES

PROGRAMMING ASSIGNMENT: MOVIE QUIZ

C4.3, 4 Lab: Conditionals - Select Statement and Additional Input Controls Solutions

Objectives. After completing this topic, the students will: Understand of the concept of polymorphism Know on How to implement 2 types of polymorphism

ICS 4U. Introduction to Programming in Java. Chapter 10 Notes

Revision for Final Examination (Second Semester) Grade 9

11. Persistence. The use of files, streams and serialization for storing object model data

Chapter 13. Graphics, Animation, Sound, and Drag-and-Drop. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

To enter the number in decimals Label 1 To show total. Text:...

Learning VB.Net. Tutorial 19 Classes and Inheritance

Mr.Khaled Anwar ( )

Else. End If End Sub End Class. PDF created with pdffactory trial version

Lab 8. An Introduction to Objects

Herefordshire College of Technology Centre Edexcel BTEC Level 3 Extended Diploma in Information Technology (Assignment 1 of 3)

Name CMPS 5J Final March 17, 2009 This is a closed notes, closed book exam.

Form Adapter Example. DRAFT Document ID : Form_Adapter.PDF Author : Michele Harris Version : 1.1 Date :

In this tutorial we will create a simple calculator to Add/Subtract/Multiply and Divide two numbers and show a simple message box result.

My first game. 'function which adds objects with bug tag to bugarray array. Saturday, November 23, :06 AM

A Second Visual BASIC Application : Greetings

(0,0) (600, 400) CS109. PictureBox and Timer Controls

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Public Class ClassName (naming: CPoint)

Recall that creating or declaring a variable can be done as follows:

CALIFORNIA STATE UNIVERSITY, SACRAMENTO College of Business Administration. MIS 15 Introduction to Business Programming. Programming Assignment 3 (P3)

UNIT 1: PROGRAMMING ENVIRONMENT

1. Create your First VB.Net Program Hello World

Name CMPS 5J Final March 17, 2010 This is a closed notes, closed book exam. Each problem is worth 1 point unless indicated otherwise.

IMS1906: Business Software Fundamentals Tutorial exercises Week 5: Variables and Constants

PyGame Sprites. an excellent turorial exists for PyGame sprites here kai.vm.bytemark.co.uk/ piman/writing/spritetutorial.shtml.

INTRODUCTION TO MATLAB INTERACTIVE GRAPHICS EXERCISES

Tutorial 03 understanding controls : buttons, text boxes

Visual C# Program: Simple Game 3

Section 7 The BASIC Language II

FOR 240 Homework Assignment 4 Using DBGridView and Other VB Controls to Manipulate Database Introduction to Computing in Natural Resources

Create a memory DC for double buffering

Learning VB.Net. Tutorial 10 Collections

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics.

Using C# for Graphics and GUIs Handout #2

Making use of other Applications

What is a variable? a named location in the computer s memory. mousex mousey. width height. fontcolor. username

System Analysis and Design

SketchUp Starting Up The first thing you must do is select a template.

AN INTRODUCTION TO SCRATCH (2) PROGRAMMING

Package: java.util It generates random numbers An instance is created by using one of the two constructors:

Unit 3. Lesson Designing User Interface-2. TreeView Control. TreeView Contol

Santiago Canyon College Computer Science

INTRODUCTION TO THE MATLAB APPLICATION DESIGNER EXERCISES

Class Test 5. Create a simple paint program that conforms to the following requirements.

Form Properties Window

VISUAL BASIC PROGRAMMING (44) Technical Task KEY. Regional 2013 TOTAL POINTS (485)

BSc. (Hons.) Software Engineering. Examinations for / Semester 2

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom

CompSci 230 Software Construction

Final Exam Winter 2013

Chapter 8. Classes and Objects

Assignment 5: Part 1 (COMPLETE) Sprites on a Plane

Bits and Bytes. How do computers compute?

REVIEW OF CHAPTER 1 1

Connection Example. Document ID : Connection_Example.PDF Author : Michele Harris Version : 1.1 Date :

ICS3C/4C/3U/4U Unit 2 Workbook Selection: If Statement

BLM Answers. BLM 4-1 Prerequisite Skills. BLM 4-3 Section 4.1 Modelling With Quadratic Relations. 10. a)

How to Validate DataGridView Input

Interaction Design A.A. 2017/2018

Instructor s Notes Programming Logic Printing Reports. Programming Logic. Printing Custom Reports

Load your files from the end of Lab A, since these will be your starting point.

MATFOR In Visual Basic

10 Object oriented programming

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

slide 1 gaius Python Classes you can use theclass keyword to create your own classes here is a tiny example of a class

Object-Oriented Programming in Processing

Object-Oriented Language Development Company

Model Solutions. COMP 102: Test 1. 6 April, 2016

EXAMGOOD QUESTION & ANSWER. Accurate study guides High passing rate! Exam Good provides update free of charge in one year!

Lecture 10 OOP and VB.Net

CSS Selectors. element selectors. .class selectors. #id selectors

Chapter 5. Condi.onals

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

BSc (Hons) Computer Science with. Network Security. BSc (Hons) Business Information Systems. Examinations for 2018 / Semester 1

CISC 1600, Lab 2.3: Processing animation, objects, and arrays

Programming: You will have 6 files all need to be located in the dir. named PA4:

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Learning VB.Net. Tutorial 17 Classes

Disclaimer. Trademarks. Liability

HO-1: INTRODUCTION TO FIREWORKS

1. Complete these exercises to practice creating user functions in small sketches.

Introduction. Create a New Project. Create the Main Form. Assignment 1 Lights Out! in C# GUI Programming 10 points

DEVELOPING OBJECT ORIENTED APPLICATIONS

Iteration in Programming

Efficiency of Bubble and Shell Sorts

Chapter 13. Graphics, Animation, Sound and Drag-and-Drop The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill


FrontCounter BC Discovery Tool Instructions. NOTE: You must have Google Earth installed to use this tool.

Programming Project 1

Interactive Tourist Map

1 Dept: CE.NET Programming ( ) Prof. Akash N. Siddhpura. Working with Form: properties, methods and events

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Firstly, I would like to thank ProFantasy for hosting this tutorial on the RPGMaps Blog. Thank you!

โปรแกรมช วยทดสอบหม อแปลงกระแส

learning outcomes 10 min.

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Transcription:

OVERLOADING METHODS AND CONSTRUCTORS: The Ball Class Create a Ball Demo program that uses a Ball class. Use the following UML diagram to create the Ball class: Ball - ballcolor: Color - ballwidth, ballheight: Integer - mybrush: SolidBrush - xpos, ypos: Integer New() New(xPos: Integer, ypos: Integer) New(xPos: Integer, ypos: Integer, width: Integer, height: Integer) + Color(col: Color): Color + DrawBall(g: Graphics) + Height(bHeight: Integer): Integer + Move() + Move(xPixels: Integer, ypixels: Integer) + Width(bWidth: Integer): Integer + X(ballX: Integer): Integer + Y(ballY: Integer): Integer The Ball class will be responsible for knowing its own location (i.e. x- and y-position), its dimensions, and its colour. We are going to implement this responsibility by providing the Ball class with variables that will store each of these values. We are going to declare the variables as follows: Public Class Ball Private mybrush As SolidBrush Private col As Color Private xpos, ypos As Integer Private ballwidth, ballheight As Integer End Class IMPLEMENTING CONSTRUCTORS We are going to create a constructor that does not take any parameters and initializes our class fields or variables with default values. It s going to look something like this: The Ball Class Page 1 of 9

Public Sub New() col = Color.Blue mybrush = New SolidBrush(col) xpos = 0 ypos = 0 ballwidth = 30 ballheight = 30 Since we are using a no-arg constructor for the Ball class and no parameters are being passed to the constructor, we need to assign default values for the Ball object that will be created. In the above example, we are going to set the x- and y-position of the ball at 0, 0, set the dimension to 30 x 30, and set the colour to blue. Now we can create our Ball object in our program by writing the following lines of code in our Ball Demo program: Public Class BallDemo Private g As Graphics Private myball As Ball Private Sub BallDemo_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load g = Me.CreateGraphics() myball = New Ball Private Sub BallDemo_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint myball.drawball(g) End Class Before we can run the program, we need to create a method called DrawBall() because this is where we will be writing the code to draw our Ball object onto the form. In order to draw the ball, however, we need the Graphics object that is being used in the program. So our DrawBall() method in the Ball class would look like this: The Ball Class Page 2 of 9

Public Sub DrawBall(ByVal g As Graphics) g.fillellipse(mybrush, xpos, ypos, ballwidth, ballheight) The responsibility of drawing the Ball object should fall on the Ball class because we the information required to draw the ball is in the class itself, not the program. However, in order to draw the Ball object, the class needs the Graphics object that is being used in the program. This is why the Graphics object needs to be passed to the DrawBall() method. When you run the program, you should see a Ball object at the top-left corner of the form: OVERLOADING CONSTRUCTORS One way to overload the constructor and provide more flexibility to the Ball class is to allow the user the ability to indicate where to position the ball when it s created. So we can create a second constructor that allows the user to pass two integers representing the x- and y-positions where they may want the ball to initially be positioned: Public Sub New(ByVal x As Integer, ByVal y As Integer) xpos = x ypos = y ballwidth = 30 ballheight = 30 col = Color.Blue mybrush = New SolidBrush(col) The Ball Class Page 3 of 9

When you initialize a Ball object using this constructor, you will need to pass the x-position and the y- position of the ball. So now we can create a Ball object in our program as follows: Public Class BallDemo Private myball As Ball Private Sub BallDemo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load myball = New Ball(100, 200) End Class Let s create a third constructor that allows the user to specify the location of the Ball object and its dimensions. The constructor would look something like this: Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) xpos = x ypos = y ballwidth = width ballheight = height col = Color.Blue mybrush = New SolidBrush(col) IMPLEMENTING PROPERTIES Now that we have our class variables and constructors in place, it s time to create properties for our Ball class. Public Property X As Integer 'This property will set and return the x-position of the Ball Public Property Y As Integer The Ball Class Page 4 of 9

'This property will set and return the y-position of the Ball Public Property Color As Color 'This property will set and return the color of the Ball Public Property Width As Integer 'This property will set and return the width of the Ball Public Property Height As Integer 'This property will set and return the height of the Ball IMPLEMENTING METHODS Now let s add a method that will make the ball move. We will simply call the method Move(). Public Sub Move() xpos += 5 ypos += 3 The purpose of the Move() method is to move the x- and y-position of the ball object a specific number of pixels. In our example, we are going to increase the x-position of the ball by 5 pixels and increase the y-position of the ball by 3 pixels. OVERLOADING METHODS Let s create a second Move() method that allows programmers to specify how many pixels along the x- and y-axis to move the ball. The Ball Class Page 5 of 9

Public Shadows Sub Move(ByVal xpixels As Integer, ByVal ypixels As Integer) xpos += xpixels ypos += ypixels USING THE Ball CLASS IN A PROGRAM Now that we have factored all of the responsibility for the Ball out of the program itself, we can use the Ball class within our Ball Demo program. We will start by declaring an instance of the Ball as a member of our program: Public Class BallDemo Private g As Graphics Private myball As Ball Private Sub BallDemo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load g = Me.CreateGraphics() myball = New Ball(0, 0, 50, 50) Private Sub DrawingImages_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint myball.drawball(g) Private Sub tmrball_tick(byval sender As System.Object, ByVal e As System.EventArgs) Handles tmrball.tick myball.move() Me.Refresh() The Ball Class Page 6 of 9

Private Sub btnstart_click(byval sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.click If btnstart.text = "START" Then btnstart.text = "STOP" tmrball.start() Else btnstart.text = "START" tmrball.stop() End If End Class When the program launches and you click the START button, the ball will start moving horizontally to the right and vertically to the bottom of the screen. The problem, of course, is that the ball is going to eventually disappear from the screen. To solve this problem, we will need to first create two variables that will keep track of the direction along the x-axis and the direction along the y-axis that the ball will be travelling. Create two variables in your program that will keep track of the direction the ball will be traveling: Private xdir, ydir As Integer Set the variables to a default value of your choice. I will set the x-direction and y-direction to 4 and 3 respectively when the program loads: Private Sub BallDemo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load myball = New Ball(0, 0, 50, 50) The Ball Class Page 7 of 9

xdir = 5 ydir = 3 Next, we will need to add code that will check if the ball has banged into any of the walls (top, bottom, left or right). In order to do this, we will need to write the code inside the timer s Tick procedure as follows: Private Sub tmrball_tick(byval sender As System.Object, ByVal e As System.EventArgs) Handles tmrball.tick myball.move(xdir, ydir) 'Check if the ball hits the left or right wall If myball.x + myball.width >= Me.Width - 20 Or myball.x <= 0 Then xdir = -xdir End If 'Check if the ball hits the top or bottom wall If myball.y <= 0 Or myball.y + myball.height >= Me.Height - 40 Then ydir = -ydir End If Now when you run the program, the ball will check if it hits any of the four walls and reverse its position accordingly. When checking if the ball reaches the right wall, we need to get the x-position of the ball and add the width because we want to check if the right side of the ball hits the wall. If we didn t add the width, we would be checking if the left side of the ball hits the wall. xpos xpos + width When checking if the ball reaches the bottom wall, we need to do the same thing we did when checking if the ball hits the right wall with the only difference being that we need to use the y-position of the ball and the height of the panel. The Ball Class Page 8 of 9

ypos ypos + height The Ball Class Page 9 of 9