arrays - Is there a way to avoid writing duplicate code in C#? -
i insert more balls form. however, in order allow bounce have code same algorithm on , on again different ball. may know there way can without writing on , on again? codes have below.
int bba1; //the x axis upper left corner int bba2; //the y axis upper left corner int spdbba1; //the change of x int spdbba2; //the change of y public startgame() { initializecomponent(); } private void startgame_load(object sender, eventargs e) { //loads ball on screen @ bottom of window bba1 = this.clientsize.width / 5; //the x axis ball loaded @ bba2 = this.clientsize.height - 10; //the y axis ball loaded @ spdbba1 = 1; //the speed of ball of y spdbba2 = 1; //the speed of ball of x } private void startgame_paint_1(object sender, painteventargs e) { //this inner paint color of circle 10 10 e.graphics.fillellipse(brushes.blue, bba1, bba2, 10, 10); //this outline paint color of circle 10 10 e.graphics.drawellipse(pens.blue, bba1, bba2, 10, 10); } private void timer1_tick(object sender, eventargs e) { bba2 = bba2 + spdbba2; bba1 = bba1 + spdbba1; if (bba2 < 0) { spdbba2 = -spdbba2; //if y less 0 changes direction } else if (bba1 < -5) { spdbba1 = -spdbba1; } else if (bba2 + 10 > this.clientsize.height) { // if y + 10, radius of circle greater // form width change direction spdbba2 = -spdbba2; } else if (bba1 + 10 > this.clientsize.width) { spdbba1 = -spdbba1; } this.invalidate(); } thank you.
yes can! 1 of many cool features of object oriented programming.
create ball class. when start game create balls need , store them in list. there can use foreach loops modify properties of each of ball objects.
public class ball { public int speedx { get; private set; } public int speedy { get; private set; } public int positionx { get; private set; } public int positiony { get; private set; } public ball(int speedx, int speedy, int positionx, int positiony) { this.speedx = speedx; this.speedy = speedy; this.positionx = positionx; this.positiony = positiony; } public int setspeedx(int newspeed) { this.speedx = newspeed; } //add other setters need. } now have blueprint balls need create. in game can this:
public class startgame { public list<ball> balllist { get; private set; } public startgame() { this.balllist = new list<ball>(); initializecomponent(); } private void startgame_load(object sender, eventargs e) { //add balls need here. balllist.add(new ball(5, 10, 1, 1)); balllist.add(new ball(2, 17, 2, 9)); balllist.add(new ball(4, 12, 7, 5)); } private void startgame_paint_1(object sender, painteventargs e) { //this foreach loop run through balls in balllist foreach(ball ball in balllist) { e.graphics.fillellipse(brushes.blue, ball.positionx, ball.positiony, 10, 10); e.graphics.drawellipse(pens.blue, ball.positionx, ball.positiony, 10, 10); } } } i wasn't 100% sure how game worked made guesses variables hope idea.
Comments
Post a Comment