A-level Computing/AQA/The Computing Practical Project/Advanced VB.NET
All the programming you have done so far has been with the command line. This is great if all you want is text on a screen, but you probably want to display some graphics. There are several places you can get started:
Here we are going to look how we can very quickly display graphics in VB.NET and make some simple games. To display graphics we are going to use the GDI+ library of tools. DirectX is much more powerful, but for our needs GDI+ is a simple way to get started. GDI+ allows you to draw both vector and bitmap graphics to the screen. There are a couple of functions that you need to be familiar with:
This code runs when the form is first loaded
This code runs on the event of clicking a key on your keyboard
You need to have added a timer to your project and named it tmrBall. This code runs on each tick of the timer.
This code draws the items on to the screen
Public Class frmGame Dim x1, y1, w1, h1 As Integer Dim x2, y2, w2, h2 As Integer Dim bx, by, bw, bh, bdirx, bdiry As Integer 'As soon as the game starts the paddles are set up and the ball started Private Sub frmGame_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load x1 = 5 y1 = Me.Height / 2 w1 = 5 h1 = 20 x2 = Me.Width - 15 y2 = Me.Height / 2 w2 = 5 h2 = 20 bx = Me.Width / 2 by = Me.Height / 2 bw = 10 bh = 10 bdirx = 2 bdiry = -2 End Sub 'On the event of pressing a key, this code finds which key has been pressed and moves the paddles Private Sub frmGame_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown If e.KeyCode = Keys.Up Then If y2 - 3 > 12 Then y2 = y2 - 3 End If End If If e.KeyCode = Keys.Down Then If y2 + 3 < Me.Height - 40 Then y2 = y2 + 3 End If End If Invalidate() End Sub 'On each tick of the timer, the ball moves around the screen Private Sub tmrBall_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrBall.Tick bx = bx + bdirx by = by + bdiry If by + bdiry < 12 Then bdiry = bdiry * -1 End If If by + bdiry > Me.Height - 40 Then bdiry = bdiry * -1 End If 'collides with paddle 1 If bx < x1 And by > y1 And by < y1 + h1 Then bdirx = bdirx * -1 End If If bx > x2 And by > y2 And by < y2 + h2 Then bdirx = bdirx * -1 End If Invalidate() End Sub 'This code runs each time the invalidate() procedure is called Private Sub frmGame_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint Dim pallete As Drawing.Graphics = Me.CreateGraphics Dim brush_black As New SolidBrush(Color.Black) pallete.FillRectangle(brush_black, New Rectangle(bx, by, bw, bh)) pallete.FillRectangle(brush_black, New Rectangle(x1, y1, w1, h1)) pallete.FillRectangle(brush_black, New Rectangle(x2, y2, w2, h2)) pallete.FillRectangle(Brushes.DarkGreen, New Rectangle(2, 2, Me.Width - 2, 10)) pallete.FillRectangle(Brushes.DarkGreen, New Rectangle(2, Me.Height - 40, Me.Width - 2, 10)) End Sub End Class