Post your sample source code here and get featured on our blogs!
- You can post your interesting sample source code (and an optional screenshot of the program) here. If it is interesting enough we'll feature you and your source code on our blogs (http://blogs.msdn.com/smallbasic). Here's something to get started.
GraphicsWindow.Show() pic = Flickr.GetRandomPicture("lightning") gw = GraphicsWindow.Width gh = GraphicsWindow.Height GraphicsWindow.DrawResizedImage(pic, 0, 0, gw, gh) distance = 50 Turtle.Speed = 9 For sides = 3 To 20 DrawPolygon() EndFor Sub DrawPolygon angle = 360 / sides For i = 1 To sides GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() Turtle.Move(distance) Turtle.Turn(angle) EndFor EndSub
所有回覆
- A Blackboard application that allows you to draw on a window
GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "White" GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.MouseMove = OnMouseMove Sub OnMouseDown prevX = GraphicsWindow.MouseX prevY = GraphicsWindow.MouseY EndSub Sub OnMouseMove x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY If (Mouse.IsLeftButtonDown) then GraphicsWindow.DrawLine(prevX, prevY, x, y) endif prevX = x prevY = y EndSub - Here's a program to create a collage of World Series photos from Flickr
tag = "World Series" For i = 1 To 10 x = Math.GetRandomNumber(250) y = Math.GetRandomNumber(250) picName = Flickr.GetRandomPicture(tag) GraphicsWindow.DrawResizedImage(picName, x, y, 200, 200) EndFor
I wanted to actually scale the images instead of a fixed height and width but unfortunately the call the ImageList.GetWidthOfImage() keeps crashing (GetHeightOfImage works
fine). Anybody have any clues?
tag = "World Series" pic = "MyPic" For i = 1 To 10 x = Math.GetRandomNumber(300) y = Math.GetRandomNumber(300) picName = pic + i ImageList.LoadImage(picName, Flickr.GetRandomPicture(tag)) height = ImageList.GetHeightOfImage(picName) 'This line crashes every time for me (running Vista 32bit). 'width = ImageList.GetWidthOfImage(picName) GraphicsWindow.DrawResizedImage(picName, x, y, 300, height / 3) EndFor
Thanks!
Program Manager, Visual Studio Community http://msdn.com/vbasic http://msdn.com/vsto http://blogs.msdn.com/bethmassi - When copy-pasting your Blackboard sample to SmallBasic it came as a new line. This should fix it (I copied from the SmallBasic editor to IE8 browser). BTW, the "line numbers" feature of the code block on this forum isn't good, since you can't copy-paste the source (you get the line numbers in the selection). It should use a table instead with the lines at the left column and the code at the right column so that you don't select and copy the line numbers and ruin the sample
GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "White" GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.MouseMove = OnMouseMove Sub OnMouseDown prevX = GraphicsWindow.MouseX prevY = GraphicsWindow.MouseY EndSub Sub OnMouseMove x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY If (Mouse.IsLeftButtonDown) then GraphicsWindow.DrawLine(prevX, prevY, x, y) endif prevX = x prevY = y EndSub - 已編輯George BirbilisMVPFriday, 24 October, 2008 21:31removed line numbers
- Here's the classic Logo "Squiral". However having "Sub" without params isn't very useful for learning programming, plus it's counter-intuitive, since you allow one to call methods WITH parameters, but their own Subroutines can't have parameters. Isn't that unfair?
GraphicsWindow.Show() Turtle.Speed = 5 angle = 91 Squiral() Sub Squiral side = 0 For i = 1 to 180 Turtle.Move(side) Turtle.Turn(angle) side = side + 1 EndFor EndSub
(screenshot - added by Vijaye Raji)
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001- 已編輯Vijaye RajiMSFT, 擁有者Saturday, 1 November, 2008 19:49added screenshot
- I've created a cute little stock price simulator using the empirical distribution of (assumed normally distrubuted) stock price returns back to 1801.
Ten x pixels are 1 year.
GraphicsWindow.Show()
pic = Flickr.GetRandomPicture("stock price")
gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
GraphicsWindow.DrawResizedImage(pic, 0, 0, gw/2, gh/2)
distance = 10
numyears = 80
numstocks = 100
pixelstep = 10
Price = 10
oldprice = price
mu = 0.1
sigma = 0.18
Sub Normal
part0=math.GetRandomNumber(10000)/10000
part1 = 2*Math.Pi*Math.GetRandomNumber(10000)/10000
part2 = Math.Cos(part1)
part3 = -2*Math.NaturalLog(Math.GetRandomNumber(10000)/10000)
nrml = mu + sigma*Math.SquareRoot(part3)*part2
EndSub
Sub stockprice
For i = pixelstep To numyears*pixelstep Step pixelstep
Normal()
Price= Price*(1+nrml)
GraphicsWindow.DrawLine(i-pixelstep, gh-oldprice, i, gh-Price)
oldprice = Price
EndFor
EndSub
Sub stocks
For j = 1 To numstocks
GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor()
Price = 10
oldprice = Price
stockprice()
EndFor
EndSub
stocks()
- 已編輯danteembermage Saturday, 25 October, 2008 14:19forgot code
- I wrote a small app (cmd line only) that converts C to F and F to C. I added a little menu with input error handling for fun. :)
Goto mainLabel mainLabel: TextWindow.WriteLine("Ready to calculate? Enter your selection: ") TextWindow.WriteLine("") TextWindow.WriteLine("1. Convert C to F") TextWindow.WriteLine("2. Convert F to C") TextWindow.WriteLine("3. Exit") For i = 1 To 3 TextWindow.Write(".") Program.Delay(500) EndFor input = TextWindow.ReadNumber() If (input = 1) Then Goto ctofLabel EndIf If (input = 2) Then Goto ftocLabel EndIf If (input = 3) Then Goto exitLabel Else TextWindow.WriteLine("INVALID ENTRY!") Goto mainLabel EndIf ctofLabel: TextWindow.WriteLine("Enter degrees Celcius: ") cel = TextWindow.ReadNumber() fahr = (cel * 1.8) + 32 TextWindow.WriteLine(cel + " degrees C = " + fahr + " degrees F") Goto mainLabel ftocLabel: TextWindow.WriteLine("Enter degrees Fahrenheit: ") fahr = TextWindow.ReadNumber() cel = 5/9*(fahr-32) TextWindow.WriteLine(fahr + " degrees F = " + cel + " degrees C") Goto mainLabel exitLabel: Program.End()
- 已編輯carolingian Sunday, 26 October, 2008 1:10
' -------------------------------------------------------------------------------- ' Filename: gol.sb ' Author: Christian Jacob <cjacob@hotmail.de> ' -------------------------------------------------------------------------------- ' Width of the life grid maxX = 100 ' Height of the life grid maxY = 100 ' Size of the life pixels lifeSize = 5 max = maxX * maxY currentPos = 0 neighbourPos = 0 start = 0 initialize = 1 GraphicsWindow.BackgroundColor = "SteelBlue" GraphicsWindow.BrushColor = "Black" GraphicsWindow.Title = "Game of Life" GraphicsWindow.Width = maxX * lifeSize + 100 GraphicsWindow.Height = maxY * lifeSize GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.Show() RunLoop: If (quit = 1 ) Then Goto End EndIf If (initialize = 1) Then Initialize() EndIf If (start = 0 ) Then Goto RunLoop EndIf GraphicsWindow.Clear() DrawUI() DrawSimulation() CalculateNextGeneration() Goto RunLoop End: Program.End() Sub Initialize GraphicsWindow.Clear() ' Initialize life grid For y = 0 To maxY - 1 For x = 0 To maxX - 1 currentPos = y * maxX + x Array.SetValue ("lifegrid", currentPos, 0) Array.SetValue ("lifegridcopy", currentPos, 0) EndFor EndFor ' Initialize f-Pentomino Array.SetValue ("lifegridcopy", 50*maxX+50, 1) Array.SetValue ("lifegridcopy", 51*maxX+50, 1) Array.SetValue ("lifegridcopy", 52*maxX+50, 1) Array.SetValue ("lifegridcopy", 51*maxX+49, 1) Array.SetValue ("lifegridcopy", 50*maxX+51, 1) DrawUI() DrawSimulation() initialize = 0 EndSub Sub DrawSimulation For y = 0 To maxY - 1 For x = 0 To maxX - 1 currentPos = y * maxX + x life = Array.GetValue ("lifegridcopy", currentPos) Array.SetValue ("lifegrid", currentPos, life) if (life = 1) Then GraphicsWindow.FillRectangle (x*lifeSize, y*lifeSize, lifeSize-1, lifeSize-1) EndIf EndFor EndFor EndSub Sub CalculateNextGeneration For y = 0 To maxY-1 For x = 0 To maxX - 1 currentPos = y * maxX + x GetNeighbourCount() life = Array.GetValue("lifegrid", currentPos) If( life = 0 And neighbourCount = 3 ) Then ' Get alife Array.SetValue ("lifegridcopy", currentPos, 1) EndIf If ( life = 1 ) Then if( neighbourCount = 2 Or neighbourCount = 3 ) Then ' Stay alive Array.SetValue ("lifegridcopy", currentPos, 1) Else ' Die Array.SetValue ("lifegridcopy", currentPos, 0) EndIf EndIf EndFor EndFor EndSub Sub DrawUI GraphicsWindow.DrawLine( maxX*lifeSize, 0, maxX*lifeSize, maxY*lifeSize) ' Start button GraphicsWindow.DrawRectangle( maxX * lifeSize + 5, 5, 90, 30 ) GraphicsWindow.DrawText( maxX * lifeSize + 10, 12, "Start" ) ' Stop button GraphicsWindow.DrawRectangle( maxX * lifeSize + 5, 35, 90, 30 ) GraphicsWindow.DrawText( maxX * lifeSize + 10, 42, "Stop" ) ' Init button GraphicsWindow.DrawRectangle( maxX * lifeSize + 5, 70, 90, 30 ) GraphicsWindow.DrawText( maxX * lifeSize + 10, 77, "Init" ) ' Quit button GraphicsWindow.DrawRectangle( maxX * lifeSize + 5, 105, 90, 30 ) GraphicsWindow.DrawText( maxX * lifeSize + 10, 107, "Quit" ) EndSub Sub OnMouseDown x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY ' Draw or remove life pixel If( x > 0 And x < maxX * lifeSize And y > 0 And y < maxX * lifeSize ) Then lifeY = Math.Round(y / lifeSize) lifeX = Math.Round(x / lifeSize) newLife = ( lifeY * maxX ) + lifeX life = Array.GetValue ("lifegridcopy", newLife) If( life = 1 ) Then Array.SetValue ("lifegridcopy", newLife, 0) GraphicsWindow.BrushColor = "SteelBlue" GraphicsWindow.FillRectangle (lifeX*lifeSize, lifeY*lifeSize, lifeSize-1, lifeSize-1) Else Array.SetValue ("lifegridcopy", newLife, 1) GraphicsWindow.BrushColor = "Black" GraphicsWindow.FillRectangle (lifeX*lifeSize, lifeY*lifeSize, lifeSize-1, lifeSize-1) EndIf GraphicsWindow.BrushColor = "Black" EndIf ' Start button If ( x > maxX * lifeSize + 5 And x < maxX * lifeSize + 95 And y > 5 And y < 30 ) Then start = 1 EndIf ' Stop button If ( x > maxX * lifeSize + 5 And x < maxX * lifeSize + 95 And y > 35 And y < 65 ) Then start = 0 EndIf ' Init button If ( x > maxX * lifeSize + 5 And x < maxX * lifeSize + 95 And y > 70 And y < 100 ) Then initialize = 1 EndIf ' Quit button If ( x > maxX * lifeSize + 5 And x < maxX * lifeSize + 95 And y > 105 And y < 135 ) Then quit = 1 EndIf EndSub Sub GetNeighbourCount neighbourCount = 0 ' Left neighbourPos = currentPos - 1 GetNeighbour() ' Right neighbourPos = currentPos + 1 GetNeighbour() ' Above neighbourPos = currentPos - maxX GetNeighbour() ' Beneath neighbourPos = currentPos + maxX GetNeighbour() ' Above left neighbourPos = currentPos - maxX - 1 GetNeighbour() ' Above right neighbourPos = currentPos - maxX + 1 GetNeighbour() ' Beneath left neighbourPos = currentPos + maxX - 1 GetNeighbour() ' Beneath right neighbourPos = currentPos + maxX + 1 GetNeighbour() EndSub Sub GetNeighbour If (neighbourPos >= 0 And neighbourPos < max-1) Then If( Array.GetValue("lifegrid", neighbourPos) = 1 ) Then neighbourCount = neighbourCount + 1 EndIf EndIf EndSub This code might not meet best performance strategies, but it works and gives a simple introduction of how to get something like Conway's Game of Life working with Small Basic.When started, it is initialized with a pattern that sort of explodes at first. When clicking "Start", the simulation starts, "Stop" stops the simulation, "Init" resets the view and with "Quit" you end the program. Also, you can click on the grid to add life pixel or remove them.I believe this is a good learning example for the intermediate programmer. If I included this code within a tutorial, manual or any other type of documentation, I would encourage the reader to try extend the program by adding a generation-counter to the screen, mabye add code for handling the borders correctly and the advanced programmer add the possibility of choosing preset pattern to start the simulation with.Have fun!
- 已編輯Christian Jacob Sunday, 26 October, 2008 15:39Added suggestions
- 已編輯Christian Jacob Sunday, 26 October, 2008 15:08Added screenshot
- 已編輯Christian Jacob Sunday, 26 October, 2008 15:27Minor spelling mistakes ;-)
- Hi,
I wrote a library to work with MySQL databases in Small Basic.
Download: smalldatabase.zipDataBase.Connect("localhost", "root", "", "test") ' Execute a query and store the results in a datatable DataBase.QueryAndFill("SELECT * FROM testtable") ' Go through the results of the latest query For i=0 To DataBase.NumberOfRows - 1 TextWindow.WriteLine(DataBase.GetResults(i, 1)) EndFor ' Show a form with a datagrid component which contains the results of the latest query DataBase.ShowGridWindow() ' Execute a query without storing the results DataBase.Query("UPDATE testtable SET title='hi' WHERE id=2") - Here is a sample to draw Koch Square graphics. Currently the iteration times is 5, which might be very slow, you can change it to 4 or 3.
Here is a screenshot' file: koch_square.sb ' Mr.Turtle will draw a Koch Square for us ' l-system rules: ' variables : F ' constants : + - ' start : F ' rules : F = F + F - F - F + F ' set some default values angle = 90 length = 3 iteration = 5 ' set the graphic panel color GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "LightGreen" ' move Mr.Turtle to the left-down corner for start Turtle.Speed = 9 Turtle.Turn(-90) Turtle.PenUp() Turtle.Move(300) Turtle.Turn(-90) Turtle.Move(200) Turtle.Turn(-90) Turtle.PenDown() ' let's do it! DrawStart() ' draw one rule ' if iteration is 0, stop further recursion ' otherwise, do recursion Sub DrawRule iteration = iteration - 1 If (iteration = 0) Then Turtle.Move(length) Turtle.Turn(-angle) Turtle.Move(length) Turtle.Turn(angle) Turtle.Move(length) Turtle.Turn(angle) Turtle.Move(length) Turtle.Turn(-angle) Turtle.Move(length) Else DrawRule() Turtle.Turn(-angle) DrawRule() Turtle.Turn(angle) DrawRule() Turtle.Turn(angle) DrawRule() Turtle.Turn(-angle) DrawRule() EndIf iteration = iteration + 1 EndSub ' draw the start shape Sub DrawStart DrawRule() EndSub
- 已編輯soloman817 Wednesday, 29 October, 2008 20:31
- 已編輯soloman817 Wednesday, 29 October, 2008 20:32
- Another sample to draw Koch Curve. You can ajust the times of iteration, 4 might be slow.
Here is a screenshotfile: koch_curve.sb ' Mr.Turtle will draw a Koch Square for us ' l-system rules: ' variables : F ' angle : 60 ' constants : + - ' start : F - - F - - F ' rules : F = F + F - - F + F ' set some default values angle = 60 length = 5 iteration = 4 ' set the graphic panel color GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "LightGreen" ' move Mr.Turtle to the left-down corner for start Turtle.Speed = 9 Turtle.PenUp() Turtle.Turn(90) Turtle.Move(150) Turtle.Turn(90) Turtle.Move(150) Turtle.Turn(90) Turtle.PenDown() ' let's do it! DrawStart() ' hide Mr.Turtle Turtle.Hide() ' draw one rule ' if iteration is 0, stop further recursion ' otherwise, do recursion Sub DrawRule iteration = iteration - 1 If (iteration = 0) Then Turtle.Move(length) Turtle.Turn(-angle) Turtle.Move(length) Turtle.Turn(angle) Turtle.Turn(angle) Turtle.Move(length) Turtle.Turn(-angle) Turtle.Move(length) Else DrawRule() Turtle.Turn(-angle) DrawRule() Turtle.Turn(angle) Turtle.Turn(angle) DrawRule() Turtle.Turn(-angle) DrawRule() EndIf iteration = iteration + 1 EndSub ' draw the start shape Sub DrawStart DrawRule() Turtle.Turn(angle) Turtle.Turn(angle) DrawRule() Turtle.Turn(angle) Turtle.Turn(angle) DrawRule() EndSub Here's a point-and-shoot game. It's a remake of the same thing I wrote using LOGO eons ago!
'Point-and-shoot '(C)1989 McLeod/IdeaFix. http://www.zxprojects.com 'Target size TargetSize=30 winner=0 wanttoplay=1 'A vector-screen style window GraphicsWindow.BackgroundColor="Black" GraphicsWindow.PenColor="Green" GraphicsWindow.Clear() Game() Sub Game While (wanttoplay=1) GetRnd() DrawTarget() Turtle.PenUp() 'Game loop While (winner=0) Shoot() EndWhile winner=0 TextWindow.Write("Another game? (y/n) ") answ = TextWindow.Read() If (Text.StartsWith(Text.ConvertToLowerCase(answ),"n")) Then wanttoplay=0 Else GraphicsWindow.Clear() Turtle.PenDown() GraphicsWindow.PenColor="Green" EndIf EndWhile EndSub Sub Shoot TextWindow.Write("Angle? ") ang=TextWindow.ReadNumber() TextWindow.Write("Distance? ") dist=TextWindow.ReadNumber() Turtle.Turn(ang) Turtle.Move(dist) Turtle.Turn(-ang) xs=dist*Math.Cos(Math.GetRadians(ang)) ys=dist*Math.Sin(Math.GetRadians(ang)) If (xs>=xmin And xs<=xmax And ys>=ymin And ys<=ymax) Then Sound.PlayChimes() Turtle.Speed=100 Turtle.Move(-15) Turtle.PenDown() 'The boom! visual effect For n=1 To 36 GraphicsWindow.PenColor=GraphicsWindow.GetRandomColor() Turtle.Move(30) Turtle.Turn(150) EndFor Turtle.PenUp() Turtle.Move(15) Turtle.Turn(ang) Turtle.Move(-dist) Turtle.Turn(-ang) Turtle.Hide() TextWindow.WriteLine("Target cleared!! You WIN") winner=1 Else TextWindow.Write("Target failed!! Try again (press RETURN)") TextWindow.Read() Turtle.Speed=100 Turtle.Turn(ang) Turtle.Move(-dist) Turtle.Turn(-ang) Turtle.Speed=7 winner=0 EndIf EndSub Sub GetRnd 'These variables should store the current Height and Width of GraphicsWindow, but it seems not to work he=480 wi=640 If (he < wi) Then distance=40+Math.GetRandomNumber(he/2-TargetSize-40) Else distance=40+Math.GetRandomNumber(wi/2-TargetSize-40) EndIf angle=Math.GetRandomNumber(360) xmin=distance*Math.Cos(Math.GetRadians(angle)) ymin=distance*Math.Sin(Math.GetRadians(angle)) xmax=xmin+TargetSize ymax=ymin+TargetSize EndSub Sub DrawTarget Turtle.Speed=100 Turtle.PenUp() Turtle.Turn(angle) Turtle.Move(distance) Turtle.Turn(-angle) Turtle.PenDown() For n=1 To 4 Turtle.Move(TargetSize) Turtle.TurnRight() EndFor Turtle.PenUp() Turtle.Turn(angle) Turtle.Move(-distance) Turtle.Turn(-angle) Turtle.PenDown() Turtle.Speed=7 EndSub - I love every single one of these samples!! Amazing work - it's really hard for us to pick the one to feature in our blogs. Because of that we're going to make this a weekly feature - keep your samples coming!
- mcleod_ideafix's point and shoot game is now the featured sample of the week in our Small Basic blogs (http://blogs.msdn.com/smallbasic/default.aspx)
This (ported from a Modellus sample) should draw a flower (using angular coordinates in calculations and converting to cartesian to draw). Didn't try it though cause of the issue with SmallBasic in non-English locales, so please update if not showing ok and drop-in a screenshot too if you like the output :-)
init() For i=1 To 100 oldx=x oldy=y solve() animate() t=t+dt EndFor Sub init GraphicsWindow.Show() t=0 dt=0.1 x=0 y=0 ofsx=GraphicsWindow.Width/2 ofsy=GraphicsWindow.Height/2 EndSub Sub solve theta=10*t r=10*Math.cos(60*t)+20 x=r*Math.cos(theta) y=r*Math.sin(theta) EndSub Sub animate GraphicsWindow.AddLine(ofsx+oldx,ofsy+oldy,ofsx+x,ofsy+y) EndSub
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001- Thanks to George, i used your code layout on the squarial code for this fun trick i made.
I imagine it'll make every geometric shape imaginable if it the golden ratio wasnt truncated to 10 decimal places or so.Also, doing things proper, here is a graph of the golden ratio:GraphicsWindow.Show() Turtle.Speed = 10 angle = (1+ Math.SquareRoot(5))/2 golden() Sub golden side = 0 For i = 1 to 360 Turtle.Move(side) Turtle.Turn(angle) side = side + 1 angle = angle + 1 EndFor EndSub GraphicsWindow.Show() Turtle.Speed = 10 angle = 30 golden() Sub golden side = (1+ Math.SquareRoot(5))/2 For i = 1 to 360 Turtle.Move(side) Turtle.Turn(angle) side = side + i EndFor EndSub
- 已編輯carolingian Sunday, 2 November, 2008 3:13
- 已編輯carolingian Sunday, 2 November, 2008 2:50
- Nice, ported it to Scratch to see it though (waiting for the next SmallBasic that will run ok at my system's locale). Try the above variation for a knitted-like star pattern :-). Also at your first fun-sample try using 180 instead of 360. In Scratch it shows like a 3D sphere with blasts/rays arround it (could imagine it as a star or exploding planet)
GraphicsWindow.Show() Turtle.Speed = 10 angle = 80 golden() Sub golden side = (1+ Math.SquareRoot(5))/2 For i = 1 to 180 Turtle.Move(side) Turtle.Turn(angle) side = side + 1 EndFor EndSub
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001- 已編輯George BirbilisMVPMonday, 3 November, 2008 16:44
- I was a little bored. It's obvious what this is :) Maybe I'll get up the gumption one day to write something useful.
GraphicsWindow.Show() Turtle.Speed = 10 side = 800 fib() x = 1 y = 1 Sub fib For x = 1 to 300 z = x + y x = y y = z Turtle.Move(z + 1) Turtle.Turn(side) EndFor EndSub
- Made a star field. Frustarted I can't specify RGB color. Tried Graphics.DrawPixel() with clearing sreen, but it flickered like crazy. Instead I make rectangle objects, and move those. I simulate darker colors in the back by using some flags in the array so I can alternate the color from dim to white.
Initialize() Main() Sub Initialize GraphicsWindow.Title = "Super Star Field!" GraphicsWindow.Width = 640 GraphicsWindow.Height = 480 GraphicsWindow.BackgroundColor = "black" GraphicsWindow.PenWidth = 0 GraphicsWindow.Show() num_stars = 200 For index = 0 To num_stars NewStar() EndFor EndSub Sub NewStar Array.SetValue("star_x", index, Math.GetRandomNumber(100) - 50) Array.SetValue("star_y", index, Math.GetRandomNumber(100) - 50) ' Pick a random z depth z = (Math.GetRandomNumber(50) / 100) + 0.50 Array.SetValue("star_z", index, z) ' Start with a dark color and save our shape GraphicsWindow.BrushColor = "DimGray" Array.SetValue("star_shape", index, GraphicsWindow.AddRectangle(2, 2)) Array.SetValue("star_color", index, 0) EndSub Sub Update For index = 0 To num_stars z = Array.GetValue("star_z", index) x = (Array.GetValue("star_x", index) / z) + 320 y = (Array.GetValue("star_y", index) / z) + 240 shape = Array.GetValue("star_shape", index) ' Next z position z = z - 0.02 If(x < 0 Or x > 639 Or y < 0 Or y > 479 Or z <= 0) Then GraphicsWindow.RemoveShape(shape) NewStar() Else ' Check if we should make the star brighter If(z < 0.4) Then If(Array.GetValue("star_color", index) = 0) Then GraphicsWindow.BrushColor = "White" GraphicsWindow.RemoveShape(shape) shape = GraphicsWindow.AddRectangle(2, 2) Array.SetValue("star_shape", index, shape) Array.SetValue("star_color", index, 1) EndIf EndIf GraphicsWindow.MoveShape(shape, x, y) Array.SetValue("star_z", index, z) EndIf EndFor EndSub Sub Main ' Run forever While(1 = 1) Update() EndWhile EndSub
Picture doesn't do this justice, as the real thing is like flying through space :-)
- 已編輯Jeff Sidlosky Sunday, 9 November, 2008 0:33
- 已編輯Jeff Sidlosky Sunday, 9 November, 2008 0:39
- 已編輯Jeff Sidlosky Sunday, 9 November, 2008 0:37
- Very nice, Jeff. You can use RGB colors:
GraphicsWindow.BrushColor = "#EEFFBB"
GetPixel and SetPixel are raster operations and are inherently very inefficient. Adding and moving shapes (like you have done) is the best way to achieve good performance in these kind of animations. - I had a delay in the main loop, then found out on a 3.2ghz Core 2 Duo, running as fast as the program can, it runs at a "good" speed.
This is kinda crappy though if you think about it, moving as fast as it can 200 stars at a time, it just runs "okay" on a 3.2ghz processor... :P I guess the idea of Basic though isn't speed.
I wrote this same little program in Quick Basic back in 1993? on a 486 DX2-66, using an SVGA Library for speed and to wait on VSync, it was liquid smooth on that 66mhz processor, so on a 3.2ghz processor, i'd expect the program to run TOO FAST without a delay in there.
Does Small Basic convert to .NET byte code? Are there future optimizations that could be done or am I just asking too much. I know again SmallBasic's task isn't necessarily for "game" or graphics development. - desktop.SetWallPaper(Flickr.GetRandomPicture("puppies"))Program.End()Short, sweet, and useful. Interesting language you got there.
- Version 2 - I like this better - helps me find a picture I like interactively..
While(word <> "quit") TextWindow.Show() word = TextWindow.Read() If( word <> "quit" )Then Desktop.SetWallPaper(Flickr.GetRandomPicture(word)) TextWindow.Hide() Program.Delay(1000) TextWindow.Show() Else TextWindow.Hide() EndIf EndWhile Program.End() - 已編輯Richard Gautier Sunday, 9 November, 2008 3:54
- Another turtle space filling curve, looks like I'm not the only one to write one :).. This one draws a hilbert curve.
TextWindow.WriteLine("Order:") n=TextWindow.ReadNumber() n=n+1 right() Sub left i=i+1 If (i<n) Then Turtle.TurnRight() right() Turtle.Move(10) Turtle.TurnLeft() left() Turtle.Move(10) left() Turtle.TurnLeft() Turtle.Move(10) right() Turtle.TurnRight() EndIf i=i-1 EndSub Sub right i=i+1 If (i<n) Then Turtle.TurnLeft() left() Turtle.Move(10) Turtle.TurnRight() right() Turtle.Move(10) right() Turtle.TurnRight() Turtle.Move(10) left() Turtle.TurnLeft() EndIf i=i-1 EndSub - 已編輯xhable Sunday, 9 November, 2008 11:33Took out the line numbers
- I was just messing around with loops and the turtle, and decided I should make something fun. This will take any number x, draw a polygon with x number sides, and off of each side will be a perfect star.
GraphicsWindow.Height = 800 GraphicsWindow.Width = 800 Turtle.Speed = 10 x = 75 Star: While( s < 5 ) GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() Turtle.Move(40) Turtle.Turn(144) s = s + 1 While(r < (x - 1) ) If(s = 5) Then Turtle.Move(-75) Turtle.Turn(360/x) Turtle.Move(100) s = 0 r = r + 1 Else Goto Star EndIf EndWhile EndWhile - Beth Massi said: I wanted to actually scale the images instead of a fixed height and width but unfortunately the call the ImageList.GetWidthOfImage() keeps crashing (GetHeightOfImage worksNo clues, but I can confirm ImageList.GetWidthOfImage() crashes on WinXP too.
fine). Anybody have any clues?
Andrew Burton - http://profnano.org - Draws A fractual branch of a tree.
n=7 angle=45 x=0 y=0 GraphicsWindow.Title="Fractal Plant" GraphicsWindow.PenWidth=0.5 GraphicsWindow.PenColor = "White" GraphicsWindow.Width=700 GraphicsWindow.Height=500 GraphicsWindow.BackgroundColor="Black" GraphicsWindow.Show() X() Sub X i=i+1 If (i<n) Then F() angle=angle-25 Store() Store() X() Get() angle=angle+25 X() Get() angle=angle+25 F() Store() angle=angle+25 F() X() Get() angle=angle-25 X() EndIf i=i-1 EndSub Sub Store Stack.PushValue("tree",x) Stack.PushValue("tree",y) Stack.PushValue("tree",angle) EndSub Sub Get angle=Stack.PopValue("tree") y=Stack.PopValue("tree") x=Stack.PopValue("tree") EndSub Sub F i=i+1 If (i<n) Then x2=x+(Math.Sin(angle))*4 y2=y+(Math.Cos(angle))*4 GraphicsWindow.AddLine(x,y,x2,y2) x=x2 y=y2 F() F() EndIf i=i-1 EndSub - Regarding the start field program, obviously the issue is the repaint caused by SetPixel which also causes the flashing (the flashing is probably cause that repaint also erases the background first and then redraws? [this is classic issue - in Windows you'd disable the background repaint of that window control]).
Apart from setting flags to the window handle to not repaint its background (or overriding the respective method of the control used in your .NET app) one also needs some method to batch graphics commands. From my experience the best is a command-block (internally implemented with try/finally), doing:
StartGraphics
...commands...
EndGraphics
this has to be in the language syntax (better for naive users) if the language doesn't support lambda lists to make the above some BatchUpdate(graphics-commands-as-a-lambda-list) call
cause also call those StartRefresh/EndRefresh, StartUpdate/EndUpdate or whatever sounds explanatory enough for the end user
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001- 已編輯George BirbilisMVPMonday, 10 November, 2008 10:05
- Regarding getWidthOfImage (why not getImageWidth?), maybe the image hasn't yet loaded? (they should wait for it to load or have an option if you want to wait or not). Can try polling the image in a loop (do a small sleep at each loop) till it gets a width or if you can't try/catch errors in SmallBasic (don't remember), just wait for some long enough (?) period first and then try to call the method
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001- 已編輯George BirbilisMVPMonday, 10 November, 2008 10:09
This seems a fun language to play around with. :-) I'm a big fan of spinning 3D cubes. I'm sure there's a nicer way of implementing this - it is a bit flickery, so consider yourself warned.
GraphicsWindow.Title = "Spinning Cube" GraphicsWindow.Show() Time = 0 MainLoop: RotationX = Time / 30 RotationY = Time / 40 Scale = Math.Min(GraphicsWindow.Width, GraphicsWindow.Height) * (1.2 + Math.Sin(Time / 50)) * 0.5 Time = Time + 1 GraphicsWindow.Clear() GraphicsWindow.PenWidth = Scale / 200 For x = -1 To 1 Step 2 For y = -1 To 1 Step 2 z = -1 TransformPoint() StartX = TransformedX StartY = TransformedY z = 1 TransformPoint() GraphicsWindow.AddLine(StartX, StartY, TransformedX, TransformedY) EndFor EndFor For x = -1 To 1 Step 2 For z = -1 To 1 Step 2 y = -1 TransformPoint() StartX = TransformedX StartY = TransformedY y = 1 TransformPoint() GraphicsWindow.AddLine(StartX, StartY, TransformedX, TransformedY) EndFor EndFor For z = -1 To 1 Step 2 For y = -1 To 1 Step 2 x = -1 TransformPoint() StartX = TransformedX StartY = TransformedY x = 1 TransformPoint() GraphicsWindow.AddLine(StartX, StartY, TransformedX, TransformedY) EndFor EndFor Program.Delay(10) Goto MainLoop ' Inputs: x, y, z, RotationX, RotationY, Scale. Outputs: TransformedX, TransformedY. Sub TransformPoint TransformedX = y * Math.Cos(RotationX) - x * Math.Sin(RotationX) TransformedY = -x * Math.Cos(RotationX) * Math.Sin(RotationY) - y * Math.Sin(RotationX) * Math.Sin(RotationY) - z * Math.Cos(RotationY) TransformedZ = 3 - x * Math.Cos(RotationX) * Math.Cos(RotationY) - y * Math.Sin(RotationX) * Math.Cos(RotationY) + z * Math.Sin(RotationY) TransformedX = TransformedX * Scale / TransformedZ + GraphicsWindow.Width / 2 TransformedY = TransformedY * Scale / TransformedZ + GraphicsWindow.Height / 2 EndSub - I've been enjoying working in SmallBasic; it takes me back to when I had a ZX81. I took the paddle game sample and made it work, increase in difficulty and allow the player more control of the angle and speed of the "ball"; next to add breakout style blocks to destroy.
B0ff1n
paddle = GraphicsWindow.AddRectangle(120, 12) ball = GraphicsWindow.AddEllipse(16, 16) speed=9 GraphicsWindow.FontSize = 16 GraphicsWindow.MouseMove = OnMouseMove lives = 3 score = 0 gw = Math.Floor( GraphicsWindow.Width - 8 ) gh = Math.Floor( GraphicsWindow.Height - 20 ) While (lives>0) x = Math.GetRandomNumber(gw) y = 36 deltaX = 1 deltaY = 2 GraphicsWindow.MoveShape(ball, (x-8), y) PrintScore() ' Sound.PlayChimeAndWait() For i=1 To 20 GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor() GraphicsWindow.DrawText(300, 150, "Get Ready!") Program.Delay(50) EndFor GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(10, 100, 630, 200) While (y < (gh+2)) x = x + deltaX y = y + deltaY If (x >= gw Or x <= 8) Then deltaX = -deltaX EndIf If (y <= 36) Then deltaY = -deltaY EndIf GraphicsWindow.MoveShape(ball, (x-8), y) padX = GraphicsWindow.GetLeftOfShape(paddle) 'TextWindow.WriteLine("X:"+x+" Y:"+y+" padX:"+padX+" gh:"+gh) If (y >= gh) Then 'TextWindow.WriteLine("Testing for collision") If (x >= padX And x <= padX + 120) Then 'TextWindow.WriteLine("Hit!") Sound.PlayClick() score = score + 10 PrintScore() deltaY = -deltaY 'did the user hit the ball with the very edge of the paddle? If (x<=padx+40 Or x>=padx+80) then If (x<=padx+20 And deltaX>0) then '*user hit the ball with the "corner" of the paddle; reverse the x-direction too deltaX = -deltaX EndIf If (x>=padx+100 And deltaX<0) then '*user hit the ball with the "corner" of the paddle; reverse the x-direction too deltaX = -deltaX EndIf If (Math.Abs( deltaX )<2) Then deltaX = deltaX*2 EndIf Else If (Math.Abs(deltaX)>1) Then deltaX = deltaX/2 EndIf EndIf If (Math.Remainder(score,50)=0) Then speed=speed-1 If (speed<1) Then speed=1 EndIf EndIf 'Else 'TextWindow.WriteLine("Missed!") EndIf EndIf ' GraphicsWindow.MoveShape(ball, (x-8), y) Program.Delay(speed) EndWhile lives = lives - 1 EndWhile GraphicsWindow.ShowMessage("You scored : " + score+ " points", "Paddle - Game Over") Program.End() Sub OnMouseMove paddleX = GraphicsWindow.MouseX GraphicsWindow.MoveShape(paddle, paddleX - 60, GraphicsWindow.Height - 12) EndSub Sub PrintScore ' Clear the score first and then draw the real score text GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(10, 10, 630, 20) GraphicsWindow.BrushColor = "Black" GraphicsWindow.DrawText(10, 10, "Score: " + score) GraphicsWindow.DrawText(300, 10, "Lives: " + lives) GraphicsWindow.DrawText(540, 10, "Speed: " +speed) EndSub
The reason why the original sample didn't work for me was that the graphicswindow.height was returning 480.1 and was comparing the y-ordinate to be exactly that; hence my use of math.floor and some >'s rather than ='s.
Great stuff though; now why can't Visual Studio be this good?- 已編輯B0ff1n Tuesday, 11 November, 2008 16:03
- Inside the Small Basic Samples folder there's a Fractal example; the fractal is a Sierpinski Triangle. Having written Sierpinski Triangles in other BASIC dialects such as Basic4GL & Brutus2D, I thought I'd write a new version in Small Basic.

' Sierpinski Triangle written in Small Basic GraphicsWindow.BackgroundColor = "Black" width = 640 height = 480 x1 = (width / 2) x2 = (width / 2) y1 = 0 y2 = 0 maxPoints = 100000 For i = 0 To maxPoints direct = Math.GetRandomNumber(3) If (direct = 0) Then x1 = (x2 + width / 2) / 2 y1 = (y2 + 0) / 2 EndIf If (direct = 1) Then x1 = (x2 + 0) / 2 y1 = (y2 + height) / 2 EndIf If (direct = 2) Then x1 = (x2 + width) / 2 y1 = (y2 + height) / 2 Endif GraphicsWindow.SetPixel(x1, y1, "White") x2 = x1 y2 = y1 EndFor 1 'This is a simple pong game. 2 'Player 1 is on the left, moves with the mouse 3 'Player 2 is on the right, moves with the arrow key 4 'Stop by pressing esc 5 6 7 'const 8 BALLSIZE = 15 9 PADDLEWIDTH = 10 10 PADDLEHEIGHT = 100 11 SPEED = 3 12 PlAYERDISTANCE = 20 13 PLAYERSPEED = 50 14 15 continue = 1 16 wanttoplay = 1 17 18 player1Score = 0 19 player2Score = 0 20 21 22 Start() 23 Program.Delay(2000) 24 Program.End() 25 26 27 Sub Start 28 init() 29 program.delay(1000) 30 GraphicsWindow.MouseMove = OnMouseMove 31 GraphicsWindow.KeyDown = OnKeyPressed 32 GraphicsWindow.KeyUp = OnKeyReleased 33 While(wanttoplay = 1) 34 Moveball() 35 endwhile 36 EndSub 37 38 Sub init 39 40 GraphicsWindow.Title = "Dan's pong" 41 GraphicsWindow.BackgroundColor= "black" 42 GraphicsWindow.Width = 800 43 GraphicsWindow.Height = 600 44 GraphicsWindow.Clear() 45 46 'setup background 47 GraphicsWindow.BrushColor = "LightGoldenrodYellow" 48 GraphicsWindow.FillRectangle(0,500,800,100) 49 50 'initialize players 51 GraphicsWindow.BrushColor = "red" 52 GraphicsWindow.PenColor = "red" 53 player1 = GraphicsWindow.AddRectangle(PADDLEWIDTH,PADDLEHEIGHT) 54 55 56 GraphicsWindow.BrushColor = "blue" 57 GraphicsWindow.PenColor = "blue" 58 player2 = GraphicsWindow.AddRectangle(PADDLEWIDTH,PADDLEHEIGHT) 59 60 61 'initialize ball 62 GraphicsWindow.BrushColor = "SpringGreen" 63 GraphicsWindow.PenColor = "SpringGreen" 64 ball = GraphicsWindow.AddEllipse(BALLSIZE,BALLSIZE) 65 66 'randomize ball start direction 67 temp = Math.GetRandomNumber(10) 68 If (temp < 5) Then 69 deltaY = 1 70 Else 71 deltaY = -1 72 endif 73 74 temp = Math.GetRandomNumber(10) 75 If (temp < 5) Then 76 deltaX = 1 77 Else 78 deltaX = -1 79 endif 80 81 82 83 'position players and ball 84 GraphicsWindow.MoveShape(player1,0,200) 85 GraphicsWindow.MoveShape(player2,800 - PADDLEWIDTH,200) 86 GraphicsWindow.MoveShape(ball,(800-BALLSIZE)/2,143) 87 88 'draw scoring board 89 GraphicsWindow.FontSize = 40 90 GraphicsWindow.BrushColor = "black" 91 GraphicsWindow.DrawText(360,520,player1Score +" - " + player2Score) 92 93 EndSub 94 95 96 Sub OnMouseMove 97 paddleY = GraphicsWindow.MouseY 98 If (paddleY < 50)then 99 GraphicsWindow.MoveShape(player1, GraphicsWindow.Width - 800,0) 100 Else 101 If (paddleY > 450) then 102 GraphicsWindow.MoveShape(player1, GraphicsWindow.Width - 800,400) 103 else 104 GraphicsWindow.MoveShape(player1, GraphicsWindow.Width - 800,paddleY-PADDLEHEIGHT/2) 105 EndIf 106 Endif 107 EndSub 108 109 110 Sub OnKeyPressed 111 key = GraphicsWindow.LastKey 112 113 If (key = "Up" Or key = "Down") Then 114 player2move() 115 else 116 command() 117 EndIf 118 119 EndSub 120 121 122 'reset player2 speed 123 Sub OnKeyReleased 124 PlAYERDISTANCE = 20 125 EndSub 126 127 Sub player2move 128 curpos = GraphicsWindow.GetTopOfShape(player2) 129 newpos = curpos 130 If (key = "Up") Then 131 newpos = curpos - PLAYERDISTANCE 132 If (newpos < 0) Then 133 newpos = 0 134 EndIf 135 EndIf 136 If (key = "Down") Then 137 newpos = curpos + PLAYERDISTANCE 138 If (newpos > 500 - PADDLEHEIGHT) Then 139 newpos = 500 - PADDLEHEIGHT 140 EndIf 141 EndIf 142 GraphicsWindow.AnimateShape(player2,800-PADDLEWIDTH,newpos,PLAYERSPEED) 143 144 'the longer you hold the key, the faster the paddle moves 145 PlAYERDISTANCE = PlAYERDISTANCE*1.1 146 EndSub 147 148 149 150 'stop the game 151 Sub command 152 If (key = "Escape") Then 153 wanttoplay = 0 154 EndIf 155 156 EndSub 157 158 159 160 Sub Moveball 161 x = GraphicsWindow.GetLeftOfShape(ball) 162 y = GraphicsWindow.GetTopOfShape(ball) 163 x = x + deltaX 164 y = y + deltaY 165 166 If (y < 0 Or y > 500 - BALLSIZE) Then 167 deltaY = -deltaY 168 Sound.PlayClick() 169 endif 170 171 If (x < PADDLEWIDTH Or x > 800 - PADDLEWIDTH - BALLSIZE) Then 172 deltaX = -deltaX 173 Sound.PlayClick() 174 endif 175 176 GraphicsWindow.MoveShape(ball,x,y) 177 Program.Delay(SPEED) 178 checkforgoal() 179 endsub 180 181 182 Sub checkforgoal 183 player1pos = GraphicsWindow.GetTopOfShape(player1) 184 player2pos = GraphicsWindow.GetTopOfShape(player2) 185 ballXpos = GraphicsWindow.GetLeftOfShape(ball) 186 ballYpos = GraphicsWindow.GetTopOfShape(ball) 187 188 189 If (ballXpos < 0 + PADDLEWIDTH) Then 190 If (ballYpos < player1pos Or ballYpos > player1pos + PADDLEHEIGHT) Then 191 player2Score = player2Score + 1 192 sound.PlayBellRingAndWait() 193 init() 194 endif 195 EndIf 196 197 198 If (ballXpos > 800 - PADDLEWIDTH - ballsize) Then 199 If (ballYpos < player2pos Or ballYpos > player2pos + PADDLEHEIGHT) Then 200 player1Score = player1Score + 1 201 sound.PlayBellRingAndWait() 202 init() 203 endif 204 EndIf 205 206 endsub 207 208 - Jeff Sidlosky's Star field simulation is the featured sample of this week.
GraphicsWindow.BackgroundColor = "000000" GraphicsWindow.PenColor = "#00CC44" vDistance = 100 pixelsPerUnit = 70 centerX = GraphicsWindow.Width / 2 centerY = GraphicsWindow.Height / 2 oldX = centerX oldY = centerY + vDistance Turtle.Show() Turtle.Speed = 7 Turtle.PenUp() Turtle.Move(-vDistance) Turtle.PenDown() Turtle.TurnLeft() Turtle.Speed = 10 For fi = 0 To 360 radianFi = Math.GetRadians(fi) ro = (1 + Math.Sin(radianFi)) * (1 + 0.9 * Math.Cos(8 * radianFi)) * (1 + 0.1 * Math.Cos(24 * radianFi)) dx = ro * Math.Cos(radianFi) * pixelsPerUnit dy = ro * Math.Sin(radianFi) * pixelsPerUnit newDistance = Math.SquareRoot(dx * dx + dy * dy) newX = centerX - dx newY = centerY - dy + vDistance GraphicsWindow.DrawLine(oldX, oldY, newX, newY) oldX = newX oldY = newY If (newDistance >= 10) Then Turtle.Turn(fi) Turtle.Move(newDistance) Turtle.Turn(180) Turtle.Move(newDistance) Turtle.Turn(180-fi) EndIf EndFor Turtle.TurnRight() Turtle.Speed = 5 Turtle.Move(-vDistance / 2) Turtle.PenUp()
- I would like to submit my 4 state button :D.
http://smallbasic.com/drop/buttonclick.zip
Thanks,
Pacolaco - There is a simple game, I know about few bugs (enemy balls get stuck, sometimes it starts with bad resolution - I don't know why), but it should works. If you wish, you can rewrite OnKeyDown to better movements.
PLAYERSIZE = 16 TARGESIZE = 10 ENEMYSIZE = 20 alive = "true" score = 0 numberOfBalls = 0 bonus = 1000 currentX = 0 currentY = 0 newX = 0 newY = 0 targetBallX = 0 targetBallY = 0 Init() Start() Program.Delay(2000) Program.End() Sub Init GraphicsWindow.Height = 400 GraphicsWindow.Width = 400 GraphicsWindow.BackgroundColor = "Gainsboro" GraphicsWindow.KeyDown = OnKeyDown EndSub Sub Start GraphicsWindow.BrushColor = "Red" playerBall = GraphicsWindow.AddEllipse(PLAYERSIZE, PLAYERSIZE) GraphicsWindow.MoveShape(playerBall, currentX, currentY) GraphicsWindow.BrushColor = "Gold" targetBall = GraphicsWindow.AddEllipse(TARGESIZE, TARGESIZE) MoveTargetBall() AddNewEnemy() Playing() GraphicsWindow.Clear() Program.Delay(3000) Program.End() EndSub Sub Playing While (alive = "true") Program.Delay(10) currentX = currentX + newX currentY = currentY + newY If (currentX < 0) Then currentX = 0 EndIf If (currentX > GraphicsWindow.Width - PLAYERSIZE) Then currentX = GraphicsWindow.Width - PLAYERSIZE EndIf If (currentY < 0) Then currentY = 0 EndIf If (currentY > GraphicsWindow.Height - PLAYERSIZE) Then currentY = GraphicsWindow.Height - PLAYERSIZE EndIf GraphicsWindow.MoveShape(playerBall, currentX, currentY) For i = 0 To numberOfBalls - 1 moveX = 0 moveY = 0 If (Array.GetValue("axis", i) = 1) Then moveX = Array.GetValue("speed", i) Else moveY = Array.GetValue("speed", i) EndIf x = Array.GetValue("x", i) + moveX y = Array.GetValue("y", i) + moveY If (x < 0 Or x > GraphicsWindow.Width - ENEMYSIZE) Then Array.SetValue("speed", i, -Array.GetValue("speed", i)) EndIf If (y < 0 Or y > GraphicsWindow.Height - ENEMYSIZE) Then Array.SetValue("speed", i, -Array.GetValue("speed", i)) EndIf Array.SetValue("x", i, x) Array.SetValue("y", i, y) GraphicsWindow.MoveShape(Array.GetValue("balls", i), x, y) If (Math.Abs((currentX + (PLAYERSIZE / 2)) - (x + (ENEMYSIZE / 2))) < ((PLAYERSIZE + ENEMYSIZE) / 2) And Math.Abs((currentY + (PLAYERSIZE / 2)) - (y + (ENEMYSIZE / 2))) < ((PLAYERSIZE + ENEMYSIZE) / 2)) Then alive = "false" EndIf EndFor If (Math.Abs((currentX + (PLAYERSIZE / 2)) - (targetBallX + (TARGESIZE / 2))) < ((PLAYERSIZE + TARGESIZE) / 2) And Math.Abs((currentY + (PLAYERSIZE / 2)) - (targetBallY + (TARGESIZE / 2))) < ((PLAYERSIZE + TARGESIZE) / 2)) Then score = score + 2000 + numberOfBalls * 100 If (bonus > 0) Then score = score + bonus EndIf bonus = 1000 MoveTargetBall() AddNewEnemy() EndIf bonus = bonus - 1 GraphicsWindow.Title = "Score: " + score EndWhile EndSub Sub AddNewEnemy GraphicsWindow.BrushColor = "SteelBlue" ball = GraphicsWindow.AddEllipse(ENEMYSIZE, ENEMYSIZE) Array.SetValue("balls", numberOfBalls, ball) Array.SetValue("axis", numberOfBalls, Math.GetRandomNumber(2) + 1) Array.SetValue("x", numberOfBalls, GraphicsWindow.Height - Math.GetRandomNumber(GraphicsWindow.Height - ENEMYSIZE)) Array.SetValue("y", numberOfBalls, GraphicsWindow.Width - Math.GetRandomNumber(GraphicsWindow.Width - ENEMYSIZE)) Array.SetValue("speed", numberOfBalls, Math.GetRandomNumber(4) + 1) GraphicsWindow.MoveShape(ball, Array.GetValue("x", numberOfBalls), Array.GetValue("y", numberOfBalls)) numberOfBalls = numberOfBalls + 1 axis = -axis EndSub Sub MoveTargetBall targetBallX = GraphicsWindow.Height - Math.GetRandomNumber(GraphicsWindow.Height - TARGESIZE) targetBallY = GraphicsWindow.Width - Math.GetRandomNumber(GraphicsWindow.Width - TARGESIZE) GraphicsWindow.MoveShape(targetBall, targetBallX, targetBallY) EndSub Sub OnKeyDown key = GraphicsWindow.LastKey If (key = "Down") Then If (newY = 0) Then newY = 1 Else newY = 0 EndIf EndIf If (key = "Up") Then If (newY = 0) Then newY = -1 Else newY = 0 EndIf EndIf If (key = "Left") Then If (newX = 0) Then newX = -1 Else newX = 0 EndIf EndIf If (key = "Right") Then If (newX = 0) Then newX = 1 Else newX = 0 EndIf EndIf EndSub - Here's a screenshot for Nidzo's game. It was a blast!

- Please when you post samples deselect the "line numbers" option. It's not well implemented in the forums and one copy-pastes the numbers too with the code (should have a real HTML table ther instead, probably they use a CSS layout or something). Bad for beginners that want to try some sample
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001 - Well this is my 1st "app" made in SB. It's a console slot machine (?) It's not really hard to code at all, and SB makes it easier. It still needs some work on it to make it smaller. It's in spanish, sorry =/
'Tragamonedas de consola por Rodrigo Bellusci 2008 'Hecho en Microsoft SmallBasic© dinero = 500 TextWindow.WriteLine("Introduzca su nombre:") name = TextWindow.Read() TextWindow.WriteLine("Bien Sr/a." + name + ". Su cantidad de dinero es:$" + dinero) apuestaStart: TextWindow.Write("¿Cuánto quiere apostar?:") apuesta = TextWindow.Read() If (apuesta > dinero) Then TextWindow.WriteLine("No puedes apostar más de lo que tienes.") Goto apuestaStart EndIf TextWindow.WriteLine("Apuesta hecha") nro1 = Math.GetRandomNumber(2) nro2 = Math.GetRandomNumber(1) TextWindow.Write("| ") TextWindow.Write(nro1) TextWindow.Write(" |") TextWindow.Write(" ") TextWindow.Write("| ") TextWindow.Write(nro2) TextWindow.Write(" |") TextWindow.Write(" ") If (nro1 = nro2) Then dinerodinero = dinero - apuesta + (apuesta * 2) TextWindow.Write("Ha ganado, su dinero es:$") TextWindow.Write(dinero) TextWindow.WriteLine(" ") Else dinerodinero = dinero - apuesta TextWindow.Write("Ha perdido. Su dinero es:$") TextWindow.Write(dinero) TextWindow.WriteLine(" ") EndIf If (dinero = 0) Then TextWindow.WriteLine("Gracias por jugar.") Goto goodbye EndIf TextWindow.WriteLine("Quiere jugar otra vez?:") replay = TextWindow.Read() If (replay = "Si") Then Goto apuestaStart EndIf goodbye: TextWindow.WriteLine("Vuelva pronto.")
Pic
P.S: My english isn't so good, sorry. I'm from Argentina
- This is fun! Thanks!
This program performs two sorts on colored cubes in a window - a bubble sort and a selection sort.'Globals xlimit = 10 ylimit = 10 cs = 64 cellcnt = xlimit * ylimit GraphicsWindow.BackgroundColor = "Khaki" GraphicsWindow.Title = "bsort" GraphicsWindow.Width = (xlimit * cs) GraphicsWindow.Height = (ylimit * cs) GraphicsWindow.Show() InitParr() GraphicsWindow.Title = "bsort, click in window to start bubble sort" Pause() BubbleSort() wtitle = GraphicsWindow.Title GraphicsWindow.Title = GraphicsWindow.Title + " ; click in window to start selection sort" Pause() SelectionSort() wtitle = GraphicsWindow.Title GraphicsWindow.Title = GraphicsWindow.Title + " ; click in window to exit" Pause() Program.End() Sub BubbleSort DrawSarr() stopSort = 0 GraphicsWindow.Title = "bubble+shaker sort, " + cellcnt + " cells, sorting ... press any key to stop" GraphicsWindow.KeyDown = onKey base = 1 slimit = cellcnt - 1 swap = 1 While (swap > 0) swap = 0 For ai = base To slimit If (stopSort = 1) Then Goto stopBubble EndIf bubbleCmpSwp() EndFor ' plus shaker, turn turtles to rabits If (swap = 0) Then Goto stopBubble EndIf ' For i = (slimit - 1) To 1 Step -1 -- bug, for won't count down ai = slimit - 1 While (ai >= base) If (stopSort = 1) Then Goto stopBubble EndIf bubbleCmpSwp() ai = ai - 1 EndWhile base = base + 1 slimit = slimit - 1 EndWhile stopBubble: GraphicsWindow.Title = "bubble sort, " + cellcnt + " cells, " + cmpCnt + " cmp " + swpCnt + " swp" EndSub Sub SelectionSort DrawSarr() stopSort = 0 GraphicsWindow.Title = "selection sort, " + cellcnt + " cells, sorting ... press any key to stop" GraphicsWindow.KeyDown = onKey For ai = 1 To cellcnt - 1 a = Array.GetValue("sarr",ai) minbi = ai For i = (ai + 1) To cellcnt If (stopSort = 1) Then Goto stopSelection EndIf b = Array.GetValue("sarr",i) cmpCnt = cmpCnt + 1 If (b < a) Then minbi = i a = b EndIf EndFor If (ai <> minbi) Then bi = minbi SwapAB() EndIf EndFor stopSelection: GraphicsWindow.Title = "selection sort, " + cellcnt + " cells, " + cmpCnt + " cmp " + swpCnt + " swp" EndSub Sub Pause wait = 1 GraphicsWindow.MouseDown = Unwait While (wait = 1) Program.Delay(250) EndWhile EndSub Sub Unwait wait = 0 EndSub sub onKey stopSort = 1 EndSub sub getXY lindex = index - 1 x = Math.Remainder(lindex,xlimit) * cs y = Math.Floor((lindex/xlimit)) * cs EndSub Sub bubbleCmpSwp a = Array.GetValue("sarr",ai) b = Array.GetValue("sarr",(ai+1)) cmpCnt = cmpCnt + 1 If (b < a) Then bi = ai + 1 SwapAB() swap = 1 EndIf EndSub Sub SwapAB 'ai, bi are indexes into sarr la = array.GetValue("sarr",ai) lb = array.GetValue("sarr",bi) index = ai getXY() GraphicsWindow.BrushColor = Array.GetValue("carr",lb) GraphicsWindow.FillRectangle(x,y,cs,cs) index = bi getXY() GraphicsWindow.BrushColor = Array.GetValue("carr",la) GraphicsWindow.FillRectangle(x,y,cs,cs) Array.SetValue("sarr",ai,lb) Array.SetValue("sarr",bi,la) swpCnt = swpCnt + 1 EndSub Sub DrawSarr GraphicsWindow.Title = "bsort, initializing sort table" For index = 1 To cellcnt a = Array.GetValue("parr",index) Array.SetValue("sarr",index,a) getXY() GraphicsWindow.BrushColor = Array.GetValue("carr",a) GraphicsWindow.FillRectangle(x,y,cs,cs) EndFor cmpCnt = 0 swpCnt = 0 EndSub Sub InitParr ' Global array of sortable colors Array.SetValue("carr",1,"White") Array.SetValue("carr",2,"Blue") Array.SetValue("carr",3,"Cyan") Array.SetValue("carr",4,"Gray") Array.SetValue("carr",5,"Green") Array.SetValue("carr",6,"Magenta") Array.SetValue("carr",7,"Red") Array.SetValue("carr",8,"Yellow") Array.SetValue("carr",9,"Black") Array.SetValue("carr",10,"DarkBlue") Array.SetValue("carr",11,"CadetBlue") Array.SetValue("carr",12,"DimGray") Array.SetValue("carr",13,"DarkGreen") Array.SetValue("carr",14,"DarkMagenta") Array.SetValue("carr",15,"DarkRed") Array.SetValue("carr",16,"DarkOrange") ' build array to sort For i = 1 To cellcnt cell = Math.GetRandomNumber(16) + 1 Array.SetValue("parr",i,cell) EndFor EndSub Sub DumpSarr j = 0 For i = 1 To cellcnt j = j +1 TextWindow.Write(Array.GetValue("sarr",i) + " ") If ( j = 25 ) Then TextWindow.WriteLine(" ") j = 0 EndIf EndFor EndSub
- Very slow...
' Draws the mandelbrot & julia set on the graphics window ' See http://en.wikipedia.org/wiki/Mandelbrot_set#For_programmers and ' http://en.wikipedia.org/wiki/Julia_set ' ' Author: Matthias Loeu ' Date: 24 November 2008 GraphicsWindow.Show() ' Size of the window (make it >= resolution) GraphicsWindow.Width = 800 GraphicsWindow.Height = 800 ' Resolution of the rendering, higher = better & slower resolutionx = 300 resolutiony = 300 ' The section of the complex plane we are interested in (x + y*i) minx = -1.5 miny = -1.3 maxx = 1.5 maxy = 1.3 ' The complex parameter (for the julia set) cx = -0.4 cy = 0.6 ' Draw the mandelbrot (1) or julia (0) draw_mandelbrot = 0 ' Max number of iterations, higher = more accurate & slower max_iter = 500 If (minx > maxx) Then t = minx minx = maxx maxx = t EndIf If (miny > maxy) Then t = miny miny = maxy maxy = t EndIf 'TextWindow.WriteLine("min (" + minx + ", " + miny + ")") 'TextWindow.WriteLine("max (" + maxx + ", " + maxy + ")") ' Step size, in the complex plane stepx = (maxx - minx)/resolutionx stepy = (maxy - miny)/resolutiony ' Size of a "pixel" sizex = GraphicsWindow.Width / resolutionx sizey = GraphicsWindow.Height / resolutiony ' The colors Array.SetValue("color", 0, "white") Array.SetValue("color", 1, "lavender") Array.SetValue("color", 2, "thistle") Array.SetValue("color", 3, "plum") Array.SetValue("color", 4, "violet") Array.SetValue("color", 5, "orchid") Array.SetValue("color", 6, "fuchsia") Array.SetValue("color", 7, "mediumorchid") Array.SetValue("color", 8, "mediumpurple") Array.SetValue("color", 9, "blueviolet") Array.SetValue("color", 10, "darkviolet") Array.SetValue("color", 11, "darkorchid") Array.SetValue("color", 12, "purple") Array.SetValue("color", 13, "indigo") count_colors = 13 ' The actual computations start = Clock.Hour*3600 + 60*Clock.Minute + Clock.Second ' loop trough every "pixel" For i=1 To resolutionx For j=1 To resolutiony ' point in the complex plane x = minx + i * stepx y = miny + j * stepy iter = 0 If (draw_mandelbrot = 1) Then cx = x cy = y EndIf ' iterate... While (x * x + y * y <= 4 And iter < max_iter) ' compute z = z^2 + c t = x * x - y * y + cx y = 2 * x * y + cy x = t iter = iter + 1 EndWhile GraphicsWindow.BrushColor = Array.GetValue("color", Math.Floor(count_colors * iter / max_iter)) ' Draw a "pixel" GraphicsWindow.FillRectangle((i-1)*sizex, (j-1)*sizey, sizex, sizey) EndFor 'TextWindow.Write(i + " ") EndFor ' Running this program during midnight is bad... end = 3600*Clock.Hour + 60*Clock.Minute + Clock.Second GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawText(0, 0, "Finished in " + (end-start) + " seconds")
Image Image 2 - The following is code to search a specific text file for specific text and return the entire line it appears in.
filepath = "C:\testfilepath.txt" searchtext = "text to find" line = 1 While (File.ReadLine(filepath, line) <> "") filetext = File.ReadLine(filepath, line) If (Text.IsSubText(filetext,searchtext)) Then TextWindow.WriteLine(filetext) EndIf line = line + 1 EndWhile - OK, I finally put one together that I can post.
It's super simple but it's pretty. :-)
Randomize a color.
Then just draw line from top-left to bottom-right of graphic screen, increase the X at top and decrease bottom X by an random number.
When X reaches top-right and bottom-left, choose another random color and start increaseing the right-hand Y and decreasing the left-hand Y by a different random number.
Start over again.
It would have taken less time if I would have left it at that, but noooo. I had to add instructions and the ability to Exit out.
...and while I was reading keyboard commands, why not add the ability to slow down the spin of the spoke?
I call it Random Spoke.
*Problem Corrected - small problem with program locking-up. Random step was finding a number between 0 and 99. When the step was zero, the program would lock-up. So added 1 to each of the two "S =" lines.*
'Setup graphics window. GraphicsWindow.Height=600 GraphicsWindow.Width=600
GraphicsWindow.Height=600GraphicsWindow.Show() 'Show instructions GraphicsWindow.Title="Random Spoke instructions" GraphicsWindow.BrushColor = "Black" GraphicsWindow.DrawText(10,20,"Simple instructions...") GraphicsWindow.DrawText(30,40,"Down arrow to decrease speed.") GraphicsWindow.DrawText(30,60,"Up arrow to increase speed.") GraphicsWindow.DrawText(30,75,"(Spoke starts at fastest speed.)") GraphicsWindow.DrawText(30,95,"Escape to end program.") GraphicsWindow.DrawText(10,120,"Press Space Bar to start.") While (GraphicsWindow.LastKey <> "Space") EndWhile 'Init GraphicsWindow.BackgroundColor=0 GraphicsWindow.Title="What does up, must come down. Spinning wheel, got to go round..." 'Run game until While (EndProgram<>"yes") Start() EndWhile Program.End() Sub Start ' spoke turn left/right GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() S = Math.GetRandomNumber(100) + 1 For X = 0 To 600 Step S GraphicsWindow.DrawLine(X,0,600-X,600) Program.Delay(delay) ' check keypress If (GraphicsWindow.LastKey = "Escape") Then EndProgram = "yes" EndIf If (GraphicsWindow.LastKey = "Down") Then delay = delay + 1 EndIf If (GraphicsWindow.LastKey = "Up") Then delay = delay - 1 If (delay < 0) Then delay = 0 EndIf EndIf EndFor ' spoke turn up/down GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() S = Math.GetRandomNumber(100) + 1 For Y = 0 To 600 Step S GraphicsWindow.DrawLine(600,Y,0,600-y) Program.Delay(delay) ' check keypress If (GraphicsWindow.LastKey = "Escape") Then EndProgram = "yes" EndIf If (GraphicsWindow.LastKey = "Down") Then delay = delay + 1 EndIf If (GraphicsWindow.LastKey = "Up") Then delay = delay - 1 If (delay < 0) Then delay = 0 EndIf EndIf EndFor EndSub - 已編輯Vijaye RajiMSFT, 擁有者Thursday, 27 November, 2008 0:17Fixed some typos
- 已編輯Path_drc Monday, 1 December, 2008 17:58edited program error
- Nice DRC. Although the program quickly freezes on my PC.
- I didn't have a problem on my work PC, but on my home PC (which is much faster) the graphics window keeps the correct width but the height is almost double the size and, like you Dink, it locks up after just a few passes.
I know it is not a simple mistake, like the program is running but the lines are not drawing, because the Esc key doesn't work.
I'm going to post this as new thread and see if anyone has any ideas.- 已編輯Path_drc Thursday, 27 November, 2008 18:55correct typos

index = 0
NeedToDraw = 1
GraphicsWindow.KeyDown = OnKeyDown
InitMatrix()
Play()
Sub InitMatrix
GraphicsWindow.BackgroundColor = "#000000"
Array.SetValue("color", 00, "#003300")
Array.SetValue("color", 01, "#004400")
Array.SetValue("color", 02, "#005500")
Array.SetValue("color", 03, "#006600")
Array.SetValue("color", 04, "#007700")
Array.SetValue("color", 05, "#008800")
Array.SetValue("color", 06, "#009900")
Array.SetValue("color", 17, "#00AA00")
Array.SetValue("color", 18, "#00BB00")
Array.SetValue("color", 19, "#00CC00")
Array.SetValue("color", 10, "#00DD00")
Array.SetValue("color", 11, "#00EE00")
Array.SetValue("color", 12, "#00FF00")
For x = 0 To GraphicsWindow.Width Step 13
index = index + 1
Array.SetValue("x", index, x)
Array.SetValue("y", index, Math.GetRandomNumber(GraphicsWindow.Height))
Array.SetValue("dy", index, 5 + Math.GetRandomNumber(7))
Array.SetValue("colors", index, Array.GetValue("color", Math.GetRandomNumber(13)))
If(Math.GetRandomNumber(2) = 0) Then
Array.SetValue("ch", index, "0")
Else
Array.SetValue("ch", index, "1")
EndIf
EndFor
EndSub
Sub DrawMatrix
For i = 0 To index
x = Array.GetValue("x", i)
y = Array.GetValue("y", i)
GraphicsWindow.BrushColor = GraphicsWindow.BackgroundColor
GraphicsWindow.FillRectangle(x, y, 20, 20)
y = y + Array.GetValue("dy", i)
GraphicsWindow.BrushColor = Array.GetValue("colors", i)
GraphicsWindow.DrawText(x, y, Array.GetValue("ch", i))
If(y > GraphicsWindow.Height) Then
y = -20
Array.SetValue("colors", i, Array.GetValue("color", Math.GetRandomNumber(13)))
EndIf
Array.SetValue("y", i, y)
EndFor
EndSub
Sub Play
While(NeedToDraw = 1)
DrawMatrix()
EndWhile
Program.End()
EndSub
Sub OnKeyDown
key = GraphicsWindow.LastKey
If(key = "Escape") Then
NeedToDraw = 0
EndIf
EndSub- Can you please post the code without the line numbering so we can copy and paste it and run the code.
- I developed an example program that converts decimal numbers into their hexadecimal equivalent.
It initially sounded like a rather simple endeavor, a little text manipulation, and a bit of recursion using the stack to pass values to subroutines.
Two things to keep in mind:
Firstly, all variables seem to be global, when recursing, push everything you may need onto the stack as it will most
likely get trashed.
Secondly, sometimes text will get treated as a number and concatenating two such strings results in them getting added rather than appended.
The first one is the most important to remember in general, but the second one chewed up the most of my time to find out.
The Text.Append that is planned for Xmas release will be gladly welcomed :)
I am aware that the recursion is totally unnecessary and extremely inefficient but thought it a good way to demonstrate the concept.
I'll re-write this to do away with the recursion and use something simpler to demo that, maybe Newton's square root approximation or factorials.'Demonstration code to convert decimal numbers in hexadecimal 'By tekgno , Wednesday 3 December 2008 'This example demonstrates recursion and some text manipulation 'Initialise our array of decimal to hex characters Array.SetValue("dec2hex",0,"0") Array.SetValue("dec2hex",1,"1") Array.SetValue("dec2hex",2,"2") Array.SetValue("dec2hex",3,"3") Array.SetValue("dec2hex",4,"4") Array.SetValue("dec2hex",5,"5") Array.SetValue("dec2hex",6,"6") Array.SetValue("dec2hex",7,"7") Array.SetValue("dec2hex",8,"8") Array.SetValue("dec2hex",9,"9") Array.SetValue("dec2hex",10,"A") Array.SetValue("dec2hex",11,"B") Array.SetValue("dec2hex",12,"C") Array.SetValue("dec2hex",13,"D") Array.SetValue("dec2hex",14,"E") Array.SetValue("dec2hex",15,"F") TextWindow.Show() 'Loop through a range of numbers to demonstrate For i = 1 To 255 'In order to pass values to our subroutine, we use the stack 'Push on here Stack.PushValue("hex",i) 'Call the sub toHex() 'Pop our answer off the top of the stack txt = Stack.PopValue("hex") TextWindow.WriteLine(i+" "+txt) endfor Sub toHex 'Get the value passed to the sub h = Stack.PopValue("hex") t = "" 'If 'h' is greater than 15, then we cannot use our lookup table If (h > 15) Then 'Push everything we need onto the stack 'We need to do this otherwise everything seems to get trashed Stack.PushValue("hex",h) 'Take the modulus of the value we wish to convert, we convert this with our lookup table r = Math.Remainder(h,16) Stack.PushValue("hex",r) 'Divide the value by 16 and recurse to convert it j = (h - r) / 16 Stack.PushValue("hex",j) toHex() 'Retrieve the answer and all our other variables t = Stack.PopValue("hex") r = Stack.PopValue("hex") h = Stack.PopValue("hex") EndIf 'If h < 16 we can use our lookup table If (h < 16) Then r = h EndIf 'We convert for a single character c = Array.GetValue("dec2hex",r) 'Append our converted character to the rest of the string if applicable 'The extra space and the line to remove it again are needed as ' smallbasic will treat the text as numbers if it can ' Christmas release will allow us to use Text.Append and clean this up t = " " + t + c t = Text.GetSubText(t,1,text.GetLength(t)-1) 'Finally Push our answer onto the stack Stack.PushValue("hex",t) EndSub - OK, this version lacks recursion, but still uses the stack to pass values to/from the sub.
'Demonstration code to convert decimal numbers in hexadecimal ' Version 2.0 'By tekgno , Wednesday 3 December 2008 'Demonstrates use of the stack to pass values to/from a sub 'Initialise our array of decimal to hex characters Array.SetValue("dec2hex",0,"0") Array.SetValue("dec2hex",1,"1") Array.SetValue("dec2hex",2,"2") Array.SetValue("dec2hex",3,"3") Array.SetValue("dec2hex",4,"4") Array.SetValue("dec2hex",5,"5") Array.SetValue("dec2hex",6,"6") Array.SetValue("dec2hex",7,"7") Array.SetValue("dec2hex",8,"8") Array.SetValue("dec2hex",9,"9") Array.SetValue("dec2hex",10,"A") Array.SetValue("dec2hex",11,"B") Array.SetValue("dec2hex",12,"C") Array.SetValue("dec2hex",13,"D") Array.SetValue("dec2hex",14,"E") Array.SetValue("dec2hex",15,"F") TextWindow.Show() 'Loop through a range of numbers to demonstrate For i = 1 To 255 'In order to pass values to our subroutine, we use the stack 'Push on here Stack.PushValue("hex",i) 'Call the sub toHex() 'Pop our answer off the top of the stack txt = Stack.PopValue("hex") TextWindow.WriteLine(i+" "+txt) endfor Sub toHex 'Get the value passed to the sub h = Stack.PopValue("hex") t = "" While (h > 0) 'Take the modulus of the value we wish to convert, we convert this with our lookup table r = Math.Remainder(h,16) 'The extra space and the line to remove it again are needed as ' smallbasic will treat the text as numbers if it can ' Christmas release will allow us to use Text.Append and clean this up t = " " + Array.GetValue("dec2hex",r) + t t = Text.GetSubText(t,1,text.GetLength(t)-1) 'Divide the value by 16 h = (h - r) / 16 EndWhile 'Finally Push our answer onto the stack Stack.PushValue("hex",t) EndSub
- Here is a much easier to understand recursion demo for calculating factorials:
'Factorials! 'By Tekgno, Wednesday 3 December 2008 'A demo in recursion TextWindow.Show() 'Show the factorials for all numbers up to 27, any higher and it crashes :( For i = 0 To 27 'Use the push/pop for value passing Stack.PushValue("fact",i ) factorial() a = Stack.PopValue("fact") TextWindow.WriteLine(i+": "+a) EndFor Sub factorial 'Grab the number we wish to find the factorial for from the stack f = Stack.PopValue("fact") r = 1 'Since n! = n * (n-1)! 'If n > 1 then we find what (n-1)! is If (f > 1) Then Stack.PushValue("fact",f) Stack.PushValue("fact",f-1) factorial() r = Stack.PopValue("fact") f = Stack.PopValue("fact") EndIf 'At this point, r will either still be initialised at 1, or will contain (n-1)! r = f * r 'The factorial for 0 is 1 If (f = 0) Then r = 1 EndIf 'The factorial for negative numbers is undefined If (f < 0) Then r = "Undefined" EndIf Stack.PushValue("fact",r) EndSub
- Really nice, Tekgno. I really like the recursion demonstration with factorials!
- Since there's a Stack object, how come SmallBasic doesn't support function parameters? Wouldn't be hard to generate code internally to push all params to stack and then at the function pop them at the reverse order into local variables
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001 - could also try porting some of the demos from the other SmallBASIC (see screenshots at http://smallbasic.sourceforge.net/?q=node/835)
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001 - The reason we don't have function parameters is because there isn't a notion of scopes in Small Basic (just like QBasic). In order for function parameters to work, they should be made applicable only inside of sub body, which contradicts the "all variables are global" principle.
- The problem with the lack of scope is that you can't expect schools to use this for teaching programming, except for very young kids (primary school maybe, although many would use visual programming [see Scratch or Boku for example] at that age). You shouldn't use GWBasic/QBasic as example in my opinion, should use QuickBasic/TurboBasic/PowerBasic instead as example in my opinion.
Also, as I've written elsewhere on the forum, it's contradictory/inconsistent that object (library) methods that you provide take params whereas the end-user's own methods (for "libraries" the end-user [educator or child] wants to make in SmallBasic code) don't take params. That way you have two classes of calls, with the user's defined stuff being inferior to the ones you've defined (or that others have defined as SmallBasic extensions in low-level C# etc. code)
For example Logo uses the concept of "local" and "global" with commands like "localmake" (for locals) and "make" (for globals). First-time users will use "make" and later on will get introduced to "localmake" (also it has say local "x command which is remembered and if followed by make "x 10 later on it does a localmake for "x)
Microsoft MVP J# 2004-2007, Borland Spirit of Delphi 2001 - Still working on the 3D maze thing but wanted to complete something (getting a bit of coder's block) to get my mind off it.
I call this one Random Bouncing Points.
Enter the number of points, from 2 to 20.
Those points bounce around the screen in random directions and in random increments, drawing a line from point 1 to point 2 to point 3... depending on number of points entered, and then from last point to first point.
The color of lines are random and change to a random color every time any point bounces off a wall.
While points are bouncing, you can press keys to do the following:
End Program = Escape key
Increase delay (up to 200 ms)
(slow down the time between points replotting) = Up arrow
Decrease delay (to zero)
(speeds up time between points replotting) = Down arrow
'Random Bouncing Points 'created for Microsoft Small Basic 'by David R. Crutchfield on 12/11/2008 correctkey = "False" While (correctkey = "False") TextWindow.Show() TextWindow.WriteLine("Type number of points to bounce (from 2 to 20, or 0 to exit)") TextWindow.Write("and press the Enter key: ") numofpoints = TextWindow.ReadNumber() If (numofpoints>1 And numofpoints<21) Then correctkey = "True" Else If (numofpoints = 0) Then correctkey = "True" Program.End() Else TextWindow.WriteLine("") TextWindow.WriteLine("Number can be no less than 2 and no larger than 20,") TextWindow.WriteLine("or 0 (zero) to exit.") TextWindow.WriteLine("") Sound.PlayBellRingAndWait() EndIf EndIf EndWhile TextWindow.Hide() 'ranomize X, Y starting coordinates , direction, and point movement amount For pointnum = 1 To numofpoints Array.SetValue("X",pointnum,Math.GetRandomNumber(801)) Array.SetValue("Y",pointnum,Math.GetRandomNumber(800)) ' randomize X axis start direction direction = Math.GetRandomNumber(2) If (direction = 0) Then Array.SetValue("directionX",pointnum,-1) Else Array.SetValue("directionX",pointnum,1) EndIf ' randomize Y axis start direction direction = Math.GetRandomNumber(2) If (direction = 0) Then Array.SetValue("directionY",pointnum,-1) Else Array.SetValue("directionY",pointnum,1) EndIf ' randomize start move amount for X and Y axis Array.SetValue("moveX",pointnum,Math.GetRandomNumber(50)+1) Array.SetValue("moveY",pointnum,Math.GetRandomNumber(50)+1) EndFor 'initialize graphics window GraphicsWindow.Height = 800 GraphicsWindow.Width = 800 GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.Title = "Random Bouncing Points" GraphicsWindow.Show() GraphicsWindowGraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() GraphicsWindow.KeyDown = ReadKey repeat = "True" While (repeat) Program.Delay(pause) For pointnum = 1 To numofpoints If (pointnum<numofpoints) Then GraphicsWindow.DrawLine(Array.GetValue("X",pointnum), Array.GetValue("Y",pointnum), Array.GetValue("X",pointnum+1), Array.GetValue("Y",pointnum+1)) Else GraphicsWindow.DrawLine(Array.GetValue("X",pointnum), Array.GetValue("Y",pointnum), Array.GetValue("X",1), Array.GetValue("Y",1)) EndIf ' move X axis newX = Array.GetValue("X",pointnum)+Array.GetValue("moveX",pointnum)*Array.GetValue("directionX",pointnum) If (newX<0 Or newX>800) Then If (newX>800) Then newX = 800 - (newX - 800) Array.SetValue("directionX",pointnum,-1) Else newX = newX * -1 Array.SetValue("directionX",pointnum,1) EndIf ' randomize X axis move amount after hitting wall. Array.SetValue("moveX",pointnum,Math.GetRandomNumber(50)+1) 'get random color when point hits wall GraphicsWindow.GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndIf Array.SetValue("X",pointnum,newX) ' move Y axis newY = Array.GetValue("Y",pointnum)+Array.GetValue("moveY",pointnum)*Array.GetValue("directionY",pointnum) If (newY<0 Or newY>800) Then If (newY>800) Then newY = 800 - (newY - 800) Array.SetValue("directionY",pointnum,-1) Else newYnewY = newY * -1 Array.SetValue("directionY",pointnum,1) EndIf ' randomize Y axis move amount after hitting wall. Array.SetValue("moveY",pointnum,Math.GetRandomNumber(50)+1) 'get randome color when point hits wall GraphicsWindowGraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndIf Array.SetValue("Y",pointnum,newY) EndFor EndWhile Program.End() Sub ReadKey key = GraphicsWindow.LastKey If (key = "Escape") Then repeat = "False" EndIf If (key = "Up") Then pausepause = pause + 1 If (pause > 200) Then pause = 200 EndIf EndIf If (key = "Down") Then pausepause = pause - 1 If (pause < 0) Then pause = 0 EndIf EndIf GraphicsWindow.Title = "Random Bouncing Points Delay = "+pause+" milliseconds" EndSub
Lines of code = 103
Remark lines = 14
Blank lines = 23
Total lines = 140
Executable file size = 6 KB
By the way.
I sent the executable file to a friend in the office here.
He has the same office computer that I have, but when he runs it, it immediately crashes and wants to send a report to Microsoft.
If I want to share the programs I create do the recipients have to have something special to run the exe's? - Path_drc,
The code you provided seems to have some typos in it,
GraphicsWindow GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor()
To send to a friend you must include your .exe file and SmallBasicLibrary.dll, plus any other libraries(.dll) you used to create your program. They must also have the .Net Framework Runtime installed on their computer - I don't know how that happened. I copied straight from the editor after a few succesfull runs.
I'll correct it tomorrow.
THNX! - Love it, DRC. Here's DRC's program with the typos fixed.
'Random Bouncing Points 'created for Microsoft Small Basic 'by David R. Crutchfield on 12/11/2008 correctkey = "False" While (correctkey = "False") TextWindow.Show() TextWindow.WriteLine("Type number of points to bounce (from 2 to 20, or 0 to exit)") TextWindow.Write("and press the Enter key: ") numofpoints = TextWindow.ReadNumber() If (numofpoints>1 And numofpoints<21) Then correctkey = "True" Else If (numofpoints = 0) Then correctkey = "True" Program.End() Else TextWindow.WriteLine("") TextWindow.WriteLine("Number can be no less than 2 and no larger than 20,") TextWindow.WriteLine("or 0 (zero) to exit.") TextWindow.WriteLine("") Sound.PlayBellRingAndWait() EndIf EndIf EndWhile TextWindow.Hide() 'ranomize X, Y starting coordinates , direction, and point movement amount For pointnum = 1 To numofpoints Array.SetValue("X",pointnum,Math.GetRandomNumber(801)) Array.SetValue("Y",pointnum,Math.GetRandomNumber(800)) ' randomize X axis start direction direction = Math.GetRandomNumber(2) If (direction = 0) Then Array.SetValue("directionX",pointnum,-1) Else Array.SetValue("directionX",pointnum,1) EndIf ' randomize Y axis start direction direction = Math.GetRandomNumber(2) If (direction = 0) Then Array.SetValue("directionY",pointnum,-1) Else Array.SetValue("directionY",pointnum,1) EndIf ' randomize start move amount for X and Y axis Array.SetValue("moveX",pointnum,Math.GetRandomNumber(50)+1) Array.SetValue("moveY",pointnum,Math.GetRandomNumber(50)+1) EndFor 'initialize graphics window GraphicsWindow.Height = 800 GraphicsWindow.Width = 800 GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.Title = "Random Bouncing Points" GraphicsWindow.Show() GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() GraphicsWindow.KeyDown = ReadKey repeat = "True" While (repeat) Program.Delay(pause) For pointnum = 1 To numofpoints If (pointnum800) Then If (newY>800) Then newY = 800 - (newY - 800) Array.SetValue("directionY",pointnum,-1) Else newYnewY = newY * -1 Array.SetValue("directionY",pointnum,1) EndIf ' randomize Y axis move amount after hitting wall. Array.SetValue("moveY",pointnum,Math.GetRandomNumber(50)+1) 'get randome color when point hits wall GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndIf Array.SetValue("Y",pointnum,newY) EndFor EndWhile Program.End() Sub ReadKey key = GraphicsWindow.LastKey If (key = "Escape") Then repeat = "False" EndIf If (key = "Up") Then pause = pause + 1 If (pause > 200) Then pause = 200 EndIf EndIf If (key = "Down") Then pause = pause - 1 If (pause < 0) Then pause = 0 EndIf EndIf GraphicsWindow.Title = "Random Bouncing Points Delay = "+pause+" milliseconds" EndSub - Thanks Vijaye, I didn't get back to make the corrections myself.
Lots of stuff going on with Christmas so close.
Christmas.... hmmmmm...
How about an unoffical Christmas tree contest? :D
Maybe I could get my random color lines to bounce around in the shape of a tree?
Nah - too redundant. lol - Although a Mandelbrot drawing program was already posted, I figured I'd submit mine as well. It makes use of the new GraphicsWindow.GetColorFromRGB method in Small Basic 0.2 (and let me discover a bug in that as well: it seems to have errors in calculating the colour components so that 255 is counted as 0 [probably through a rounding error that results in 256]).
' MANDELBROT.SB - Coded in 2008 by Steven Don - http://www.shdon.com ' ' This small demonstration draws a picture of the Mandelbrot set according to ' the Escape Time Algorithm. While an in-depth discussion of complex and ' imaginary functions is beyond the scope of a sample program (for more ' information, please refer to Wikipedia's article on the Mandelbrot set: ' http://en.wikipedia.org/wiki/Mandelbrot_set ' ' This program demonstrates the use of simple for-loops, arrays and building a ' picture by plotting individual pixels. 'How many times to apply the Mandelbrot polynomial. The higher this number, the more accurate (and slower) the results max_iteration = 50 'Get the dimensions of the graphics viewport width = GraphicsWindow.Width height = GraphicsWindow.Height 'Dividing those dimensions gets the coordinates of the center of the viewport half_width = width / 2 half_height = height / 2 'Set up a gradient of colours For i = 0 To max_iteration 'How far into the loop are we? fraction = i / max_iteration 'Calculate colour components based on that - play around with these to get different colour schemes red = Math.Min (fraction * 8, 1) green = Math.Max (0, Math.Min ((fraction * 4) - 0.5, 1)) blue = Math.Min (fraction, 1) 'Combine them into a colour - the components should actually be multiplied by 255 rather than 254, but there is a bug in Small Basic rgb = GraphicsWindow.GetColorFromRGB (red * 254, green * 254, blue * 254) 'Store it for later reference Array.SetValue ("colours", i, rgb) EndFor 'Last colour (for points belonging to the actual Mandelbrot set) is black Array.SetValue ("colours", max_iteration, "black") 'Open the graphics display GraphicsWindow.Show () 'Handle all pixels For y_pixel = 0 To height 'Get fractional vertical coordinate y_fractional = (y_pixel / half_height) - 1 For x_pixel = 0 To width 'Get fractional horizontal coordinate x_fractional = (x_pixel / half_width) - 1.5 'These for the components (real and imaginary parts) of a complex number real = x_fractional imaginary = y_fractional 'Repeatedly apply the Mandelbrot polynomial, with a maximum of "max_iteration" steps iteration = 0 While (real*real+imaginary*imaginary<=4 And iteration<max_iteration) 'Generate a new real component (square of real component is positive, square of imaginary component is negative so subtract it, add in the original real part) real_new = real*real - imaginary*imaginary + x_fractional 'Generate a new imaginary component and use it imaginary = 2*real*imaginary + y_fractional 'Use that new real component real = real_new 'Count as another step iteration = iteration + 1 EndWhile 'Draw the pixel based on the number of iterations GraphicsWindow.SetPixel (x_pixel, y_pixel, Array.GetValue ("colours", iteration)) EndFor EndFor 'By the time we get here, a long time may have passed - play a sound to let the user know it's done Sound.PlayChime ()
I hope somebody finds it amusing. At the very least, it'll be a pretty picture.
- Screenshot of the Mandelbrot program by Steven. Using max_iteration = 500.
This one took about an hour to complete.
- The Mandelbrot program is awesome Steven.
GraphicsWindow.Title = "David's Rose" DrawRose() Sub DrawRose GraphicsWindow.BrushColor = "Black" GraphicsWindow.FillRectangle(0, 0, GraphicsWindow.Width, GraphicsWindow.Height) GraphicsWindow.PenWidth = 2 GraphicsWindow.PenColor = "Crimson" Turtle.Speed = 9 Turtle.Show() For sideLength = 1 To 250 Turtle.Move(sideLength) Turtle.Turn(89) EndFor GraphicsWindow.PenColor = "DarkRed" For sideLength = 0 To 249 Turtle.Move(250 - sideLength) Turtle.Turn(89) EndFor Turtle.Hide() EndSub Here's a rose that my son drew for his mom.- 已編輯W. Kevin HazzardMVPSaturday, 20 December, 2008 15:34The code didn't paste in correctly. Fixed it.
- Very pretty Kevin. Here's the screenshot of David's Rose.

- The rose program crashes my SB.
- Neat code Steven, mandelbrot sets are usually the first thing I play with in a new language. Something you may like to try to speed things up a bit is to precalculate the squares for real and imaginary to save calculating them twice each loop. Another thing (which wont be much use if you decide to add a zoom feature) is to take advantage of the symmetry about the y-axis.
'Spiral Radius = 200 RadiusStep = .2 Angle = 0 x1 = 320 + Math.Sin(Angle) * Radius y1 = 220 + Math.Cos(Angle) * Radius While Radius > 0 x = 320 + Math.Sin(Angle) * Radius y = 220 + Math.Cos(Angle) * Radius Angle = Angle + .1 GraphicsWindow.DrawLine(x,y,x1,y1) x1 = x y1 = y Radius = Radius - RadiusStep RadiusStep = RadiusStep - .0001 EndWhile
- I probably wrote this the first time about 20 years ago. It's simple enough where I remembered most it from memory.
x1 = Math.GetRandomNumber(640) y2 = Math.GetRandomNumber(480) h1 = 5 v1 = 5 x2 = Math.GetRandomNumber(640) y2 = Math.GetRandomNumber(480) h2 = 3 v2 = 3 GraphicsWindow.PenWidth = 2 start: x1 = x1 + h1 y1 = y1 + v1 x2 = x2 + h2 y2 = y2 + v2 If x1 < 0 Or x1 > 640 Then h1 = -h1 EndIf If y1 < 0 Or y1 > 480 Then v1 = -v1 EndIf If x2 < 0 Or x2 > 640 Then h2 = -h2 EndIf If y2 < 0 Or y2 > 480 Then v2 = -v2 EndIf GraphicsWindow.PenColor = GraphicsWindow.GetColorFromRGB( Math.GetRandomNumber(255), Math.GetRandomNumber(255), Math.GetRandomNumber(255)) GraphicsWindow.DrawLine( x1, y1, y1, y2 ) Goto start 
I wrote a simple Tetris program in Small Basic:
Code posted to the wiki: http://smallbasic.com/smallbasic.com/wiki/Sample%20Tetris.ashx- The Tetris game is awesome Kenny and is the best game I've seen made with SB so far.
- Here's a calc.exe (based on my extension).
CurrentText = "0" ClearBeforeType = "True" GraphicsWindow.Hide() GraphicsWindow.Title="Calculator made in Small Basic" GraphicsWindow.Hide() GraphicsWindow.Width=350 GraphicsWindow.Height=185 GraphicsWindow.CanResize="False" GraphicsWindow.BackgroundColor = GraphicsWindow.GetColorFromRGB(240,240,240) Shapes.LoadTheme("Vista") GraphicsWindow.BrushColor="#f9f9f9" GraphicsWindow.PenColor="#B2DFF8" GraphicsWindow.PenWidth=1 ' Fausse textbox 'Bordure Rect1 = Shapes.AddRectangle(336, 25) Shapes.Move(Rect1, 8, 10) ' Label GraphicsWindow.BrushColor="Black" ResultLabel = Shapes.AddLabel(335, 23, "0") Shapes.Move(ResultLabel, 11, 11) ' Autre déco GraphicsWindow.BrushColor="#E6F5FD" GraphicsWindow.PenColor="#B2DFF8" Rect1 = Shapes.AddRectangle(247, 145) Shapes.Move(Rect1, 8, 34) GraphicsWindow.BrushColor="White" GraphicsWindow.PenColor="#B2DFF8" Rect1 = Shapes.AddRectangle(90, 145) Shapes.Move(Rect1, 8+246, 34) ' Bouttons : ' - Chiffres For V = 0 To 9 CurrentCol = 2-Math.Remainder((9-V), 3) CurrentRow = Math.Floor((9-V)/3) CurrentWidth = 75 If V=0 Then CurrentWidth = 321-(2*82) CurrentCol = 0 EndIf CurrentButton = Shapes.AddButton(CurrentWidth, 30, V) Array.SetValue("Buttons", v, CurrentButton) Shapes.Move(CurrentButton, 12+82*CurrentCol,40+35*CurrentRow) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") EndFor ' - Point CurrentButton = Shapes.AddButton(75, 30, ".") Shapes.Move(CurrentButton, 11+82*2,40+35*3) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") ' - Parenthèses CurrentButton = Shapes.AddButton(38, 30, "(") Shapes.Move(CurrentButton, 12+82*3,40+35*0) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") CurrentButton = Shapes.AddButton(38, 30, ")") Shapes.Move(CurrentButton, 55+82*3,40+35*0) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") ' - Addition CurrentButton = Shapes.AddButton(38, 30, "+") Shapes.Move(CurrentButton, 12+82*3,40+35*1) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") CurrentButton = Shapes.AddButton(38, 30, "-") Shapes.Move(CurrentButton, 55+82*3,40+35*1) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") ' - Multiplication CurrentButton = Shapes.AddButton(38, 30, "*") Shapes.Move(CurrentButton, 12+82*3,40+35*2) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") CurrentButton = Shapes.AddButton(38, 30, "/") Shapes.Move(CurrentButton, 55+82*3,40+35*2) Shapes.RegisterMouseUpEvent(CurrentButton, "AddToText") ' - Résultat CurrentButton = Shapes.AddButton(38, 30, "=") Shapes.Move(CurrentButton, 12+82*3,40+35*3) Shapes.RegisterMouseUpEvent(CurrentButton, "GetResult") CurrentButton = Shapes.AddButton(38, 30, "<==") Shapes.Move(CurrentButton, 55+82*3,40+35*3) Shapes.RegisterMouseUpEvent(CurrentButton, "RemoveToText") ' Show the window GraphicsWindow.Show() Sub AddToText Src = Shapes.LastEventSource Src = Shapes.GetText(Src) If ClearBeforeType="True" Then If Math.Floor(Src)=Src Then CurrentText="" EndIf ClearBeforeType="False" EndIf CurrentText = Text.Append(CurrentText, Src) Shapes.SetText(ResultLabel, CurrentText) EndSub Sub RemoveToText If ClearBeforeType="True" Then CurrentText="" ClearBeforeType="False" Shapes.SetText(ResultLabel, CurrentText) Else Len = Text.GetLength(CurrentText) CurrentText = Text.GetSubText(CurrentText, 0, len-1) Shapes.SetText(ResultLabel, CurrentText) EndIf EndSub Sub GetResult ClearBeforeType="True" 'SmallBasic.Eval("CurrentText = (" + CurrentText +")") CurrentText = SmallBasic.MathEval(CurrentText) Shapes.SetText(ResultLabel, CurrentText) EndSub 
Fremy VB & C#- 已編輯FremyCompany解答者Saturday, 3 January, 2009 11:05Adding a link
- Very nice, Francois. Could you also provide a link to your extension from your post (you can edit your post to add that link). That way people wouldn't have to go searching for it.
- The calculator looks great Fremy.
- Here's a print screen of a game I'm currently making in Small Basic.
I think the final release will come with a compass for more ease in the reading of the data written in the top-left.
I don't post the code at this time, because there isn't any IA at this time, so the only thing you can do is moving around the second boat and firing on it (but you'll not inflige damage to him). When the IA will be clear (it can take several time because I'm back to school), I'll edit this post to include the code and a fresh preview.
[EDIT: The fault of calculation are due to the fact I was using my fr-fr culture when I took the screenshot, so the calculation is wrong]
Fremy VB & C# - Awesome Tetris game Kenny!
Your remarks document the code in detail and the game itself plays great.
I found the random shapes to not be random enough at times. Like 5 boxes in a row one time and then, as the shapes were reaching the top, I got 7 purple shapes (backwards L or 7 - depends on how you turn it :D) in a row.
...or does that happen a lot in the original Tetris games?
Besides that, and adding sound, this game is just about perfect.
A great add-on would be to keep high score in a text file.
...and even get a little more fancy by asking for a name to go with high score.
Thanks again Kenny. <Echoy voice>Turtle in spaaaaaaaaaaaaace!</Echoy voice>
This proggie displays a filled circle that's supposed to be a planet, and then has the turtle going around in an orbit around the planet. If you move the mouse left and right over the graphics window, the turtle spins around itself so you can make it face any direction you want. The turtle even has an engine that thrusts him forward, in whatever direction he's facing, as long as you hold the left mouse button down.
Tips for playing:
To make the turtle fly further out from the planet, make him face the direction of flight, and give him a gentle push with the engine (short press on the left mouse button). Conversely, you can bring him back down by turning the tail end towards the direction of flight, and fire the engines again.
Be careful no to go too fast; if the turtle gets beyond what's known as escape velocity, he's going to fly away from the planet forever, never to return to the confines of your graphics window.
Tips for hacking/expanding on this program:
If the turtle is flying too slow or too fast for your taste on your machine, the trick is to change the numbers in VelX = 0.03 and Gravity = 0.001 at the beginning of the program. It takes a bit of tries (or nasty, hard-core math) to find the balance between plunging to the ground like a rock, and flying off the graphics window alltogether.
The whole idea in this program, is that "everything" (at least the position and speed) is split up into two parts; a horizontal ("left/right") part called the X co-ordinate, and a vertical ("up/down") part called the Y co-ordinate -- and then every change and every motion is done to both of these parts (notice how a lot of things in the code below come in pairs of "something-X" and "something-Y").
As you've probably found out after a bit of playing around with the turtle, you can't "crash" onto the planet's surface; you just "plunge into" inside the planet! The program already computes the distance to the center of the planet (it's in the variable called R), so if this R less than the radius of the planet (which is 100 pixels in my code), we've hit the ground. To make it possible to "crash", see if you can make it stop (and perhaps play a noise) when that happens.
Some "flight instruments" would be nice too; e.g. something to tell you how high up above the surface you are. You can work out your height above the now "crash-enabled" planetary surface, as Height = R - 100 (remember the 100 was the planet's radius, measured in pixels), and display it in a corner somewhere.
An by keeping a copy (called, say, OldHeight) of the previous value of Height, just before a new Height is calculated, you can then subtract the OldHeight from the NewHeight to work out how fast you're ascending or descending.
You can also work out your current speed like this: Speed = Math.SquareRoot(VelX * VelX + VelY * VelY)VelX = 0.03 ' Set the initial velocity in x and y directions in VelY = 0 ' VelX and VelY Gravity = 0.001 ' Sets the strength of this planet's gravitational field GraphicsWindow.BackgroundColor = "Black" ' Black background GraphicsWindow.BrushColor = "#2030FF" ' Color for the planet GraphicsWindow.Width = 600 ' Set the size of the GraphicsWindow.Height = 600 ' graphics window GraphicsWindow.FillEllipse(200,200,200,200) ' Draw the planet PosX = 0 ' Set the space-faring turtle's initial position as PosY = 130 ' a pair of x and y coordinates in PosX and PosY Heading = 0 ' Set the turtle's initial "heading", or direction Turtle.Show() ' Display the turtle "astronaut" MainLoop: ' We keep going back to this label, as long as the "flight simulation" runs... Heading = Mouse.MouseX ' Use the left/right position of the mouse cursor to select heading If Mouse.IsLeftButtonDown Then ' If the left mouse button is pressed down, we fire the engine VelX = VelX + 0.0001 * Math.Sin(Math.GetRadians(Heading)) ' Add a little forward thrust VelY = VelY + 0.0001 * Math.Cos(Math.GetRadians(Heading)) ' in the direction the turtle faces EndIf ' (Ends check on whether the mouse button was pressed in order to fire the engine) R2 = PosX * PosX + PosY * PosY ' Get the square of the distance to the planet's center GForce = Gravity / R2 ' The force of gravity is inversely proportional to the square of the distance R = Math.SquareRoot(R2) ' Takes the square root to get the distance "itself" Ratio = GForce / R ' Ratio between the force of gravity to excert, and the distance VelX = VelX - Ratio * PosX ' Now we can calculate the effect that the planet's gravity VelY = VelY - Ratio * PosY ' has on the current velocity, in the x and y directions PosX = PosX + VelX ' Update the current position by adding the speeds in VelX PosY = PosY + VelY ' and VelY, to the position coordinates in PosX and PosY Turtle.X = 300 + PosX ' Place the turtle by converting the PosX and PosY coor- Turtle.Y = 300 - PosY ' dinates to screen coordinates, centered on the planet Turtle.Angle = Heading ' Have the turtle face in the direction given in Heading If GraphicsWindow.LastKey <> "Escape" Then ' So long as the Escape key is *not* pressed Goto MainLoop ' Go back and repeat the whole thing to keep the simulation going. EndIf ' (Ends check on whether the Escape key was pressed or not)
38911 BASIC bytes free...- Kenny Kasajian's dancing lines reminds me of an old game; "Stix" or "Styx" or something like that: While a bunch of "sticks" danced around the screen just like in your program, the player moved something like the turtle in Small Basic around the screen, to "enclose" more and more screen area. If the dancing sticks hit the line as the player was "drawing" it, he/she lost a life. Cover 75(?) percent of the screen, and the game advances to the next level...
38911 BASIC bytes free... - Whoops, hit wrong button to post my program.
...so I'll just copy and paste it over here. :-)
Wow, where do I start?
I have been working on this little project for over a month now (don’t remember exactly when I started), and it has been fun and at times frustrating.
What I am presenting today is a 3D maze program, that will eventually grow into a RPG in the flavor of the old Wizardy wireframe dungeons. There are a few shortcomings in this maze;
1) Doesn’t look for walls beyond a single wide hall (to exclude rooms too). If you change the mapdata to reflect anything more than single wide corridors, nothing will be drawn.
2) The maze data is setup in a way where every point of the graph is in the data: the space you are standing in is x = 2, y = 2 the place for a wall to the east is 3, 2 - you never stand in 3, 2 (you can stand in 4, 2) because the odd numbers are wall place holders. Not only is this slightly confusing to the casual observer, but makes the coding (to me anyway) much more complex to pull wall data.
3) When you hit a wall, it plays a cool Windows XP Low Battery .wav file (C:\WINDOWS\Media\Windows XP Battery Low.wav) – problem is it only plays once per game.
4) A few TODO’s left – to include asking for player’s name, and others shown in remarks within my code.
As I was fixing some small problems, I decided that I want to revamp the data. The next prgrams's data will be a little more complex than what is in this program, but will make coding a little easier.
Something that amazed me was how I coded the entire maze program before running any part of it and only had a few syntax errors, and most of those were due to copying and pasting code that didn’t have enough paren’s in it. I also surprised myself, when finding something that didn’t work right (like some of the walls didn’t draw correctly), by knowing exactly where to go and, in some cases, know exactly what I needed to change before I got there.
I am ready to take any suggestions and/or criticism, especially better ways to code. Maybe I overlooked something or maybe there’s a better way, in Small Basic, to
perform the same tasks.
'3D Wireframe Maze
'by David R. Crutchfield (a.k.a. Pathdrc)
'ver: 1.0
'Date:1/19/2009
GraphicsWindow.BackgroundColor="Black"GraphicsWindow.Height = 600 GraphicsWindow.Width = 800 GraphicsWindow.Show() GraphicsWindow.KeyDown = ReadKey 'Information frame on left GraphicsWindow.BrushColor = "Gainsboro" GraphicsWindow.FillRectangle(0,0,200,600) 'text in Info Frame GraphicsWindow.BrushColor = "Black" GraphicsWindow.DrawText(48,1,"Adventurer's Name") GraphicsWindow.DrawText(48,80,"Map Coordinates:") GraphicsWindow.DrawText(5,220,"Forward = Up Arrow") GraphicsWindow.DrawText(5,240,"Back = Down Arrow") GraphicsWindow.DrawText(5,260,"Turn left = Left Arrow") GraphicsWindow.DrawText(5,280,"Turn right = Right Arrow") GraphicsWindow.DrawText(5,320,"To start over = Back Space") GraphicsWindow.DrawText(5,340,"End program = Esc") 'draw box around Maze-View window on the right GraphicsWindow.PenColor = "White" GraphicsWindow.PenWidth = 4 GraphicsWindow.DrawRectangle(200,0,600,600) 'Map data MapWidth = 9 MapHeight = 11 StartX = 4 StartY = 10 StartFacing = 1 Array.SetValue("mapdata",1,"000111000000") Array.SetValue("mapdata",2,"000101000000") Array.SetValue("mapdata",3,"000101111111") Array.SetValue("mapdata",4,"000101000001") Array.SetValue("mapdata",5,"000101111101") Array.SetValue("mapdata",6,"000100000001") Array.SetValue("mapdata",7,"011101111111") Array.SetValue("mapdata",8,"010001000000") Array.SetValue("mapdata",9,"011101000000") Array.SetValue("mapdata",10,"00010100000") Array.SetValue("mapdata",11,"00011100000") 'Setup variables CurrentX = StartX CurrentY = StartY Facing = StartFacing '1 = north/up, 2 = east/right, 3 = south/down, 4 = west/left Main = "True" 'Start main program While (Main) DrawWalls() DisplayCurrentXY() 'show coordinates in information frame. loop = "True" keyisupdated = "False" WaitForKeyDownAndProcess() EndWhile Program.End() Sub WaitForKeyDownAndProcess While (loop) If (keyisupdated = "True") Then If (key = "Up") Then 'test if wall is blocking forward movement If NoForward = "True" Then HitWall() keyisupdated = "False" Else loop = "False" 'find facing and update current position based on forward movement. If Facing = 1 Then CurrentYCurrentY = CurrentY - 2 ElseIf Facing = 2 Then CurrentXCurrentX = CurrentX + 2 ElseIf Facing = 3 Then CurrentYCurrentY = CurrentY + 2 ElseIf Facing = 4 Then CurrentXCurrentX = CurrentX - 2 EndIf EndIf EndIf '[TODO] code for key = BackSpace (restart position at beginging of maze) If key = "Left" Then NoForward = "False" loop = "False" FacingFacing = Facing - 1 If Facing < 1 Then Facing = 4 Endif EndIf If key = "Right" Then NoForward = "False" loop = "False" FacingFacing = Facing + 1 If Facing > 4 Then Facing = 1 EndIf EndIf If key = "Down" Then loop = "False" 'Make sure no wall behind you and then move back one. If Facing = 1 and Text.GetSubText(Array.GetValue("mapdata",CurrentY+1),CurrentX,1) = 0 Then CurrentYCurrentY = CurrentY + 2 ElseIf Facing = 2 and Text.GetSubText(Array.GetValue("mapdata",CurrentY),CurrentX-1,1) = 0 Then CurrentXCurrentX = CurrentX - 2 ElseIf Facing = 3 and Text.GetSubText(Array.GetValue("mapdata",CurrentY-1),CurrentX,1) = 0 Then CurrentYCurrentY = CurrentY - 2 ElseIf Facing = 4 and Text.GetSubText(Array.GetValue("mapdata",CurrentY),CurrentX+1,1) = 0 Then CurrentXCurrentX = CurrentX + 2 Else HitWall() EndIf keyisupdated = "False" EndIf If key = "Back" Then loop = "False" keyisupdated = "False" RestartMazeQuestion() EndIf If (key = "Escape") Then Main = "False" loop = "False" EndIf EndIf EndWhile keyisupdated = "False" Sound.PlayClickAndWait() EndSub Sub DrawWalls EraseMazeWalls() 'determine walls For fm = 0 to 4 WallSection1 = 0 WallSection2 = 0 WallSection3 = 0 ' facing north/south If Facing = 1 Or Facing = 3 Then If Facing = 1 then wd = 1 Else wd = -1 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY-(fm*2*wd)),CurrentX - wd,1) = 1 Then WallSection1 = 1 ElseIf Text.GetSubText(Array.GetValue("mapdata",CurrentY-(fm*2*wd + wd)),CurrentX - (2*wd),1) = 1 Then WallSection1 = 2 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY-(fm*2*wd + wd)),CurrentX,1) = 1 Then WallSection2 = 1 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY-(fm*2*wd)),CurrentX + wd,1) = 1 Then WallSection3 = 1 ElseIf Text.GetSubText(Array.GetValue("mapdata",CurrentY-(fm*2*wd + (1*wd))),CurrentX + (2*wd),1) = 1 Then WallSection3 = 2 EndIf EndIf ' facing east/west If Facing = 2 Or Facing = 4 Then If Facing = 2 then wd = 1 Else wd = -1 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY-(1*wd)),CurrentX +(fm*2*wd),1) = 1 Then WallSection1 = 1 ElseIf Text.GetSubText(Array.GetValue("mapdata",CurrentY-(2*wd)),CurrentX + (fm*2*wd+(1*wd)),1) = 1 Then WallSection1 = 2 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY),CurrentX +(fm*2*wd+(1*wd)),1) = 1 Then WallSection2 = 1 EndIf If Text.GetSubText(Array.GetValue("mapdata",CurrentY+(1*wd)),CurrentX +(fm*2*wd),1) = 1 Then WallSection3 = 1 ElseIf Text.GetSubText(Array.GetValue("mapdata",CurrentY+(2*wd)),CurrentX +(fm*2*wd+(1*wd)),1) = 1 Then WallSection3 = 2 EndIf EndIf 'draw the walls GraphicsWindow.BrushColor = "White" If fm = 0 Then ' immediate If WallSection1 = 1 Then GraphicsWindow.DrawLine(200,0,240,40) GraphicsWindow.DrawLine(240,40,240,560) GraphicsWindow.DrawLine(240,560,200,600) EndIf If WallSection1 = 2 Then GraphicsWindow.DrawLine(200,40,240,40) GraphicsWindow.DrawLine(240,40,240,560) GraphicsWindow.DrawLine(240,560,200,560) EndIf If WallSection2 = 1 Then GraphicsWindow.DrawLine(240,40,240,560) GraphicsWindow.DrawLine(240,560,760,560) GraphicsWindow.DrawLine(760,560,760,40) GraphicsWindow.DrawLine(760,40,240,40) fm = 4 'end wall drawing because you can't see any further NoForward = "true" EndIf If WallSection3 = 1 Then GraphicsWindow.DrawLine(800,0,760,40) GraphicsWindow.DrawLine(760,40,760,560) GraphicsWindow.DrawLine(760,560,800,600) EndIf If WallSection3 = 2 Then GraphicsWindow.DrawLine(800,40,760,40) GraphicsWindow.DrawLine(760,40,760,560) GraphicsWindow.DrawLine(760,560,800,560) EndIf Else ' greater than immediate WallSize = 80 WallPositionLeftX = 240 WallPositionRightX = 760 WallPositionTopY = 40 WallPositionBottomY =560 If fm > 1 Then For count = 1 To fm-1 WallPositionLeftXWallPositionLeftX = WallPositionLeftX + WallSize WallPositionRightXWallPositionRightX = WallPositionRightX - WallSize WallPositionTopYWallPositionTopY = WallPositionTopY + WallSize WallPositionBottomYWallPositionBottomY = WallPositionBottomY - WallSize WallSizeWallSize = WallSize - Math.Round(WallSize / 4) EndFor EndIf If WallSection1 = 1 Then GraphicsWindow.DrawLine(WallPositionLeftX,WallPositionTopY,WallPositionLeftX + WallSize,WallPositionTopY + WallSize) GraphicsWindow.DrawLine(WallPositionLeftX + WallSize,WallPositionTopY + WallSize,WallPositionLeftX + WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallpositionLeftX + WallSize,WallPositionBottomY - WallSize,WallPositionLeftX,WallPositionBottomY) GraphicsWindow.DrawLine(WallPositionLeftX,WallPositionBottomY,WallPositionLeftX,WallPositionTopY) EndIf If WallSection1 = 2 Then GraphicsWindow.DrawLine(WallPositionLeftX,WallPositionTopY + WallSize,WallPositionLeftX + WallSize,WallPositionTopY + WallSize) GraphicsWindow.DrawLine(WallPositionLeftX + WallSize,WallPositionTopY + WallSize,WallPositionLeftX + WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallpositionLeftX + WallSize,WallPositionBottomY - WallSize,WallPositionLeftX,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallPositionLeftX,WallPositionBottomY - WallSize,WallPositionLeftX,WallPositionTopY + WallSize) EndIf If WallSection2 = 1 Then GraphicsWindow.DrawLine(WallPositionLeftX + WallSize,WallPositionTopY + WallSize,WallPositionRightX - WallSize,WallPositionTopY + WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionTopY + WallSize,WallPositionRightX - WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionBottomY - WallSize,WallpositionLeftX + WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallpositionLeftX + WallSize,WallPositionBottomY - WallSize,WallPositionLeftX + WallSize,WallPositionTopY + WallSize) fm = 4 'end wall drawing because you can't see any further EndIf If WallSection3 = 1 Then GraphicsWindow.DrawLine(WallPositionRightX,WallPositionTopY,WallPositionRightX - WallSize,WallPositionTopY + WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionTopY + WallSize,WallPositionRightX - WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionBottomY - WallSize,WallPositionRightX,WallPositionBottomY) GraphicsWindow.DrawLine(WallPositionRightX,WallPositionBottomY,WallPositionRightX,WallPositionTopY) EndIf If WallSection3 = 2 Then GraphicsWindow.DrawLine(WallPositionRightX,WallPositionTopY + WallSize,WallPositionRightX - WallSize,WallPositionTopY + WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionTopY + WallSize,WallPositionRightX - WallSize,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallPositionRightX - WallSize,WallPositionBottomY - WallSize,WallPositionRightX,WallPositionBottomY - WallSize) GraphicsWindow.DrawLine(WallPositionRightX,WallPositionBottomY - WallSize,WallPositionRightX,WallPositionTopY + WallSize) EndIf EndIf EndFor EndSub Sub HitWall 'play sound to indicate hit wall Sound.PlayAndWait("C:\WINDOWS\Media\Windows XP Battery Low.wav") '[TODO]'s 'maybe put "OUCH" in maze view 'put message in information frame that you ran into a wall '(IDEA: when secret walls are implemented, make some sound like magic or "swush" like sound when walking through secret wall) 'Note: be sure to clear both messages once a succesful Forward, left, right, or back move has been made. EndSub Sub ReadKey key = GraphicsWindow.LastKey keyisupdated = "True" EndSub Sub EraseMazeWalls 'erase walls from maze-view window GraphicsWindow.BrushColor = "Black" GraphicsWindow.PenWidth = 2 GraphicsWindow.FillRectangle(202,2,596,596) 'draw box around Maze-View window on the right GraphicsWindow.PenColor = "White" GraphicsWindow.PenWidth = 4 GraphicsWindow.DrawRectangle(200,0,600,600) EndSub Sub DisplayCurrentXY 'erase old coordinates GraphicsWindow.BrushColor = "Gainsboro" GraphicsWindow.FillRectangle(48,95,110,45) 'display new coordinates GraphicsWindow.BrushColor = "Black" CoordinatesText = "X = " + CurrentX + " Y = " + CurrentY DirectionText = "Facing: " If Facing = 1 Then DirectionTextDirectionText = DirectionText + "North" ElseIf Facing = 2 Then DirectionTextDirectionText = DirectionText + "East" ElseIf Facing = 3 Then DirectionTextDirectionText = DirectionText + "South" Else DirectionTextDirectionText = DirectionText + "West" EndIf GraphicsWindow.DrawText(48,95,CoordinatesText) GraphicsWindow.DrawText(48,110,DirectionText) EndSub Sub RestartMazeQuestion RestartMazeQuestionAnswered = "False" GraphicsWindow.BrushColor = "Black" GraphicsWindow.DrawText(5,400,"You pressed the Backspace key.") GraphicsWindow.DrawText(5,415,"Do you really wish to restart") GraphicsWindow.DrawText(5,430,"the maze?") While (RestartMazeQuestionAnswered = "False") If text.ConvertToLowerCase(key) = "y" Then CurrentX = StartX CurrentY = StartY Facing = StartFacing RestartMazeQuestionAnswered = "True" ElseIf text.ConvertToLowerCase(key) = "n" Then RestartMazeQuestionAnswered = "True" EndIf EndWhile 'erase Restart Maze message GraphicsWindow.BrushColor = "Gainsboro" GraphicsWindow.FillRectangle(5,400,195,595) EndSub You're welcome on the Tetris game.
Funny about the randomness. The code is just using the built-in random number function. But we can probably make it work a little more like what you expect. Perhaps we can ensure that the next shape is different than the current shape.
high score is a good idea.
sound won't really do the right thing. currently, the sound system is only to play wave files, and it does it in the background. There's indeterminate amount of delay between the code that invokes a sound and when you actually hear the sound.
As I was playing the game myself, and my son came and asked me to help him with his homework, I realized another feature I left out -- the Pause button. :)
So when I have time, I may go and and add those features there. Or perhaps, someone else can. :)- The game was QIX
Hi B0ff1n,
I too have been modifying the paddle game to create a simple version of Breakout (will be posting soon) you may want to combine your improvements with my code.
Anyway, I noticed when running your code, that the ball sinks halfway down into the paddle. Looking at the values used a correction should be made when testing for the ball hitting the paddle. The co-ordinates of the ball are those of the top-left corner of the imaginary enclosing square. This means that you have to allow for the diameter of the ball and not the radius as you would if you were taking the centre of the ball as your reference.
If you change your test for collision to "If (y >= gh-8)" then the ball will change direction when it touches the paddle. It actually looks better though with "If (y >= gh-6)" as this gives a more positive contact.
- I developed this program from the paddle example. There is plenty of scope for improvement. For example, the click sound has been commented out. If left in a burst of noise is generated when the bricks move downwards. This needs fixing. There is plenty of code duplication for the different colours of bricks which could be streamlined.
'BrickWall 'A development of the paddle game sample. 'Revove all the bricks to complete the game. ' Game over if you miss the ball. 'You are penalised -1 each time no bricks are hit. 'The movement of the ball is influenced by where it hits the paddle. 'Do not let the bricks reach the bottom of the screen. GameStart: paddle = GraphicsWindow.AddRectangle(120, 12) ball = GraphicsWindow.AddEllipse(16, 16) bricksLeft = 48 brickStartY = 35 hitCount = 0 GraphicsWindow.FontSize = 14 GraphicsWindow.MouseMove = OnMouseMove For idx = 0 To 15 Array.SetValue("GreenBricks", idx, 1) Array.SetValue("YellowBricks", idx, 1) Array.SetValue("RedBricks", idx, 1) Endfor DrawBricks() score = 0 PrintScore() gw = GraphicsWindow.Width gh = GraphicsWindow.Height y = gh - 28 GraphicsWindow.MoveShape(ball, x, y) deltaX = 1 deltaY = -2 Sound.PlayBellRingAndWait() RunLoop: xx = x + deltaX yy = y + deltaY gw = GraphicsWindow.Width gh = GraphicsWindow.Height If (x >= gw - 16 Or x <= 0) Then deltaX = -deltaX EndIf If (y <= 0) Then deltaY = -deltaY EndIf padX = GraphicsWindow.GetLeftOfShape(paddle) If ((y >= gh - 28 + 2) And x >= padX And x <= padX + 120) Then y = gh - 28 + 2 'Sound.PlayClick() hitCounthitCount = hitCount + 1 If Math.Remainder(hitCount, 3) = 0 Then 'Move bricks downwards For idx = 0 To 15 RemoveGreenBrick() RemoveYellowBrick() RemoveRedBrick() Endfor brickStartYbrickStartY = brickStartY + 20 DrawBricks() EndIf TestRed: For idx = 0 To 15 If Array.GetValue("RedBricks", idx) = 1 Then If brickStartY > gh - 160 Then Goto EndGame EndIf EndIf EndFor TestYellow: For idx = 0 To 15 If Array.GetValue("YellowBricks", idx) = 1 Then If brickStartY > gh - 100 Then Goto EndGame EndIf EndIf EndFor TestGreen: For idx = 0 To 15 If Array.GetValue("GreenBricks", idx) = 1 Then If brickStartY > gh - 40 Then Goto EndGame EndIf EndIf EndFor EndTest: deltaXdeltaX = deltaX - 2 + (x - padX) / 30 ' Add some skill If score = oldScore Then 'No bricks hit scorescore = score - 1 EndIf oldScore = score PrintScore() deltaY = -deltaY 'Change the ball direction EndIf GraphicsWindow.MoveShape(ball, x, y) Program.Delay(5) ' Green Bricks If y > brickStartY - 16 And y < brickStartY + 20 Then ' y position of brick - diameter of ball idx = (x+8) / 40 ' Radius of ball / length of brick idx = Math.Floor(idx) ' take integer part If Array.GetValue("GreenBricks", idx) = 1 Then Array.SetValue("GreenBricks", idx, 0) RemoveGreenBrick() Sound.PlayChime() bricksLeftbricksLeft = bricksLeft - 1 deltaY = -deltaY 'Change ball direction scorescore = score + 15 PrintScore() CheckEnd() EndIf EndIf ' Yellow Bricks If y > brickStartY + 44 And y < brickStartY + 80 Then ' y position of brick - diameter of ball = 19 idx = (x+8) / 40 ' Radius of ball / length of brick idx = Math.Floor(idx) ' take integer part If Array.GetValue("YellowBricks", idx) = 1 Then Array.SetValue("YellowBricks", idx, 0) RemoveYellowBrick() Sound.PlayChime() bricksLeftbricksLeft = bricksLeft - 1 deltaY = -deltaY 'Change ball direction scorescore = score + 10 PrintScore() CheckEnd() EndIf EndIf ' Red Bricks If y > brickStartY + 104 And y < brickStartY + 140 Then ' y position of brick - diameter of ball = 19 idx = (x+8) / 40 ' Radius of ball / length of brick idx = Math.Floor(idx) ' take integer part If Array.GetValue("RedBricks", idx) = 1 Then Array.SetValue("RedBricks", idx, 0) RemoveRedBrick() Sound.PlayChime() bricksLeftbricksLeft = bricksLeft - 1 deltaY = -deltaY 'Change ball direction scorescore = score + 5 PrintScore() CheckEnd() EndIf EndIf If (y < gh) Then 'Ball not reached bottom of window Goto RunLoop EndIf EndGame: GraphicsWindow.ShowMessage("Your score is: " + score, "BrickWall") Program.End() Sub OnMouseMove paddleX = GraphicsWindow.MouseX GraphicsWindow.MoveShape(paddle, paddleX - 60, GraphicsWindow.Height - 12) EndSub Sub PrintScore ' Clear the score first and then draw the real score text GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(10, 10, 200, 20) GraphicsWindow.BrushColor = "Black" GraphicsWindow.DrawText(10, 10, "Score: " + score) EndSub Sub DrawBricks For idx = 0 To 15 ' Draw bricks 'Program.Delay(100) If Array.GetValue("GreenBricks", idx) = 1 Then GraphicsWindow.PenColor = "Black" GraphicsWindow.BrushColor = "Green" Else GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" EndIf GraphicsWindow.FillRectangle(idx * 40, brickStartY, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY, 40, 20) GraphicsWindow.BrushColor = "Yellow" If Array.GetValue("YellowBricks", idx) = 1 Then GraphicsWindow.PenColor = "Black" GraphicsWindow.BrushColor = "Yellow" Else GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" EndIf GraphicsWindow.FillRectangle(idx * 40, brickStartY + 60, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY + 60, 40, 20) GraphicsWindow.BrushColor = "Red" If Array.GetValue("RedBricks", idx) = 1 Then GraphicsWindow.PenColor = "Black" GraphicsWindow.BrushColor = "Red" Else GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" EndIf GraphicsWindow.FillRectangle(idx * 40, brickStartY + 120, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY + 120, 40, 20) endfor EndSub Sub RemoveGreenBrick GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(idx * 40, brickStartY, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY, 40, 20) EndSub Sub RemoveYellowBrick GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(idx * 40, brickStartY + 60, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY + 60, 40, 20) EndSub Sub RemoveRedBrick GraphicsWindow.PenColor = "White" GraphicsWindow.BrushColor = "White" GraphicsWindow.FillRectangle(idx * 40, brickStartY + 120, 40, 20) GraphicsWindow.DrawRectangle(idx * 40, brickStartY + 120, 40, 20) EndSub Sub CheckEnd If bricksLeft = 0 Then GraphicsWindow.ShowMessage("Well Done. Wall destroyed. Your score is: " + score, "BrickWall") 'Goto GameStart Program.End() 'Goto EndGame EndIf EndSub
There is no provision for a high score table (this could make use of a file to remember high scores between sessions).
The ball sometimes gets stuck going up and down on the left edge of the window.
The noise made when a brick is hit gets a bit annoying but it needs something. The click sound is better but then it seems wrong to use it for the paddle as well.
When a brick is removed, the brick to its left loses the black line on its right-hand edge.
The bricks are moved down the screen as the game progresses. The time taken to erase them and redraw them in the new position is visible as a slight pause. I'm sure this could be re-written to speed this up.
I urge beginners to have a play with this and then see what they can do to alter/improve on it. That is a useful learning exercise.
Unfortunately, the forum code submission insists on converting x to xx and y to yy after the RunLoop: label. Please edit these back before running. SmallBasic is brilliant. I will save the details for another forum topic, but I will say now that it solves all of the problems I have been having keeping my Intro to Programming students interested in the subject. Bravo!
With that said, I offer up this little chestnut. It’s the example I use for one of our first projects. Shape iteration is based on multiples of shape sides. This ensures that the "facets" of the resulting shape line up. Side count is limited to ten. After that the shapes start looking like circles. And I could decide between different colors for each shape or holding the color for the entire design; so I didn’t.
Keep up the good work guys.
'Small Basic "SpiralGraph" 'Author: Matthew L. Parets top: sides = Math.GetRandomNumber(7) + 3 intrMult = Math.GetRandomNumber(5) sidLen = 720 / sides colorDepth = Math.GetRandomNumber(2) Turtle.Speed = 10 if colorDepth = 1 then GraphicsWindowGraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndIf For j=1 To sides * intrMult if colorDepth = 2 then GraphicsWindowGraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndIf For i=1 To sides Turtle.Move(sidLen) Turtle.Turn(360/sides) EndFor Turtle.Turn(360/(sides*intrMult)) EndFor Program.Delay(4000) GraphicsWindow.Clear() Goto top
- Monty Hall Paradox in Small Basic (more on the paradox at Wikipedia).
losses = 0 wins = 0 For n = 0 To 10000 win = Math.GetRandomNumber(3) For i = 1 To 3 If win = i Then TextWindow.Write("1" + " ") Else TextWindow.Write("0" + " ") EndIf EndFor shot = Math.GetRandomNumber(3) TextWindow.Write("shot = " + shot + " ") If win = shot Then losseslosses = losses + 1 TextWindow.WriteLine("Loss") Else winswins = wins + 1 TextWindow.WriteLine("Win") EndIf EndFor TextWindow.WriteLine("Losses = " + losses) TextWindow.WriteLine("Wins = " + wins)
- Today I offer up my latest opus. While being a hoot to write, this little app does show how environments like SmallBasic tend to encourage spaghetti code. But like it said, it was fun to write.
This program does show off a problem with the turtle graphics system. The longer the program is up, the slower it runs. After about 20 mins the pauses between movements is so long that the turtle appears to stutter.'Snaking:random curving paths for our turtle friend 'author: Matthew L. Parets 'Initalization '************************************************************************************ Turtle.Speed = 10 red = Math.GetRandomNumber(256) - 1 blue = Math.GetRandomNumber(256) - 1 green = Math.GetRandomNumber(256) - 1 GraphicsWindow.PenColor = GraphicsWindow.GetColorFromRGB(red,green,blue) turnIntr = Math.GetRandomNumber(45) + 5 turnCnt = 0 direction = ((Math.GetRandomNumber(90)/10) - 5) Turtle.Turn(Math.GetRandomNumber(360) - 1) 'Main Loop top: '******************************************************************************* red = red + (Math.GetRandomNumber(3) - 2) blue = blue + (Math.GetRandomNumber(3) - 2) green = green + (Math.GetRandomNumber(3) - 2) GraphicsWindow.PenColor = GraphicsWindow.GetColorFromRGB(red,green,blue) Turtle.Move(2) turnCnt = turnCnt + 1 If turnCnt >= turnIntr Then direction = ((Math.GetRandomNumber(90)/10) - 5) if direction = 0 then maxArc = 100 else maxArc = 135 / math.Abs(direction) EndIf turnIntr = Math.GetRandomNumber(maxArc) turnCnt = 0 EndIf Turtle.Turn(direction) 'Range Checking '***************************************************************************************** If Turtle.X > GraphicsWindow.Width Then Turtle.X = GraphicsWindow.Width If Turtle.Angle > 90 Then Turtle.Angle = 180 Else Turtle.Angle = 0 EndIf direction = 0 turnCnt = turnIntr EndIf If Turtle.X < 0 Then Turtle.X = 0 If Turtle.Angle > 270 Then Turtle.Angle = 0 Else Turtle.Angle = 180 EndIf direction = 0 turnCnt = turnIntr EndIf If Turtle.Y > GraphicsWindow.Height Then Turtle.Y = GraphicsWindow.Height If Turtle.Angle > 180 Then Turtle.Angle = 270 Else Turtle.Angle = 90 EndIf direction = 0 turnCnt = turnIntr EndIf If Turtle.Y < 0 Then Turtle.Y = 0 If Turtle.Angle > 0 And Turtle.Angle < 90 then Turtle.Angle = 90 Else Turtle.Angle = 270 EndIf direction = 0 turnCnt = turnIntr EndIf Goto top
- I have updated my BrickWall example to cover the breaking changes in v0.3. If you want it it is here
http://smallbasic.com/program/?QRQ360. For my next offering, I give you this recreation of an early PC app. The default text is a minor nod to my wife on Valentines weekend. While creating it, I stumbled across a little inconstancy in the graphics rendering system. The anti-aliasing for the text and the shapes leaves artifacts behind when you try to clear the text or shapes by redrawing the shape in the background color.
The code can be directly imported with the import ID: HZN400
'Blimp - A remake of an early PC basic app. 'author: Matthew L. Parets 'Initial Default Values '************************************************************************************ offset = 75 textoffset = 175 blmWid = 500 blmHei = 250 steps = 8 gap = 10 centerX = GraphicsWindow.Width / 2 centerY = GraphicsWindow.Height / 2 bgColor = "lightblue" msg = "Sara and Matt...Forever!...XOXOXOXOXOXOXOXOXOXOXOXOXOXO" 'Draw the blimp '************************************************************************************ GraphicsWindow.BackgroundColor = bgColor GraphicsWindow.BrushColor = "blue" GraphicsWindow.PenColor = "black" ewid = blmWid ehei = blmHei For i = 1 To steps GraphicsWindow.FillEllipse(centerX - (ewid/2),centerY - (ehei/2) - offset,ewid,ehei) GraphicsWindow.DrawEllipse(centerX - (ewid/2),centerY - (ehei/2) - offset,ewid,ehei) hg = ehei ehei = ehei - gap gap = gap + (gap * 0.35) If Math.Remainder(i,2) = 0 Then GraphicsWindow.BrushColor = "blue" GraphicsWindow.PenColor = "black" Else GraphicsWindow.BrushColor = "yellow" GraphicsWindow.PenColor = "black" EndIf EndFor 'Draw the gandola '************************************************************************************ GraphicsWindow.BrushColor = "brown" GraphicsWindow.FillRectangle(centerX - 75,centerY + (blmHei/2) - offset - 5,150,20) GraphicsWindow.DrawRectangle(centerX - 75,centerY + (blmHei/2) - offset - 5,150,20) GraphicsWindow.DrawLine(centerX + 75, centerY + (blmHei/2) - offset + 5,centerX + 85, centerY + (blmHei/2) - offset + 5) GraphicsWindow.BrushColor = "lightblue" GraphicsWindow.FillRectangle(centerX - 73,centerY + (blmHei/2) - offset - 0,15,10) GraphicsWindow.DrawRectangle(centerX - 73,centerY + (blmHei/2) - offset - 0,15,10) GraphicsWindow.FillRectangle(centerX - 47,centerY + (blmHei/2) - offset - 0,30,10) GraphicsWindow.DrawRectangle(centerX - 47,centerY + (blmHei/2) - offset - 0,30,10) GraphicsWindow.FillRectangle(centerX - 4,centerY + (blmHei/2) - offset - 0,30,10) GraphicsWindow.DrawRectangle(centerX - 4,centerY + (blmHei/2) - offset - 0,30,10) GraphicsWindow.FillRectangle(centerX + 38,centerY + (blmHei/2) - offset - 0,30,10) GraphicsWindow.DrawRectangle(centerX + 38,centerY + (blmHei/2) - offset - 0,30,10) 'Final Setup '************************************************************************************ GraphicsWindow.FontName = "Courier New" GraphicsWindow.FontSize = 36 sep = ".............." disp = sep + msg + sep i = 1 'Main control loop While "true" i = i + 1 If i >= Text.GetLength(disp) - Text.GetLength(sep) Then i = 1 EndIf prt = Text.GetSubText(disp,i,text.GetLength(sep)) textcolor = "black" DispText() Program.Delay(100) textcolor = "yellow" DispText() Spin() EndWhile 'Displaying marquee text on blimp '************************************************************************************ Sub DispText GraphicsWindow.BrushColor = textcolor letpos = 24 For j=0 To 6 chr = Text.GetSubText(prt,j,1) fntSiz = 21 + (j * 3) GraphicsWindow.FontSize = fntSiz GraphicsWindow.DrawText(centerX - textoffset+(letpos),centerY - offset - ((24 + (j * 3))/2),chr) letpos = letpos + (fntsiz * 0.75) EndFor For j=7 To 1 Step -1 chr = Text.GetSubText(prt,(Text.GetLength(prt)-j),1) fntSiz = 21 + ((j - 1) * 3) GraphicsWindow.FontSize = fntsiz GraphicsWindow.DrawText(centerX - textoffset+(letpos),centerY - offset - ((24 + ((j - 1) * 3))/2),chr) letpos = letpos + (fntsiz * 0.75) EndFor EndSub 'Move the propeller '************************************************************************************ Sub Spin GraphicsWindow.PenWidth = 0.5 If spinSwitch = 0 Then spinSwitch = 1 GraphicsWindow.BrushColor = bgColor GraphicsWindow.PenColor = bgColor '(centerX + 85), (centerY + (blmHei/2) - offset + 5) GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.BrushColor = "darkgray" GraphicsWindow.PenColor = "black" GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)+9) Else spinSwitch = 0 GraphicsWindow.BrushColor = bgColor GraphicsWindow.PenColor = bgColor GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.BrushColor = "darkgray" GraphicsWindow.PenColor = "black" GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-4,(centerY + (blmHei/2) - offset + 5)-9,(centerX + 85)+2,(centerY + (blmHei/2) - offset + 5)-9) GraphicsWindow.FillTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)+9) GraphicsWindow.DrawTriangle((centerX + 85),(centerY + (blmHei/2) - offset + 5),(centerX + 85)-2,(centerY + (blmHei/2) - offset + 5)+9,(centerX + 85)+4,(centerY + (blmHei/2) - offset + 5)+9) EndIf EndSub Next weeks submission will be my first use of the animation system for some drifting landmarks.
Just out of curiosity, I did a net search and found the original source at http://cd.textfiles.com/hof91/GRAPHIC3/. There is something magical about the internet.
I made a calculator in small basic
The import code is DJD934
TextWindow.Title = "Calculator"
If (Clock.Hour < 12) Then
TextWindow.Write("Good morning, would you like to do a sum? (y/n) ")
answ = TextWindow.Read()
EndIf
If (Clock.Hour > 12) Then
TextWindow.Write("Good afternoon, would you like to do a sum? (y/n) ")
answ = TextWindow.Read()
EndIf
If (Text.StartsWith(Text.ConvertToLowerCase(answ),"y")) Then
start:
TextWindow.Write("Enter the first number: ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Enter the second number: ")
num2 = TextWindow.ReadNumber()
TextWindow.WriteLine("1 = Addition")
TextWindow.WriteLine("2 = Subtraction")
TextWindow.WriteLine("3 = Division")
TextWindow.WriteLine("4 = Multiplication")
TextWindow.Write("What calculation would you like to do: ")
calc = TextWindow.ReadNumber()
If (calc = 1) Then
num3 = num1 + num2
TextWindow.WriteLine(num1+ "+" +num2+ "=" +num3)
EndIf
If (calc = 2) Then
num3 = num1 - num2
TextWindow.WriteLine(num1+ "-" +num2+ "=" +num3)
EndIf
If (calc = 3) Then
num3 = num1 / num2
TextWindow.WriteLine(num1+ "/" +num2+ "=" +num3)
EndIf
If (calc = 4) Then
num3 = num1 * num2
TextWindow.WriteLine(num1+ "*" +num2+ "=" +num3)
EndIf
TextWindow.Write("Would you like to do another sum? (y/n) ")
e = TextWindow.Read()
If (Text.StartsWith(Text.ConvertToLowerCase(e),"y")) Then
Goto start
EndIf
EndIf
TextWindow.WriteLine("Goodbye")- I have made a dictionary app that can save the definition to a text file name with the word that has been looked up. The import code is: CJJ955 and the web address is http://smallbasic.com/program/?CJJ955 you'll have to uncomment the line it has automatically commented for the save function.
- Here's a Hex Dump program so you can see how all of those bytes in your programs look!
Import code is: RBV160'HexDump
'HexDump
Revision 1
'Added scroll capability because a larger file would exceed the buffer
'capacity in the textwindow'Get file path and read data to string
TextWindow.Write("Enter full path of file to dump: ")
Filepath=textwindow.Read()
Data=File.ReadContents(Filepath)
TotalFileLength=text.GetLength(Data)
TextWindow.WriteLine("File length is "+TotalFileLength+" characters")'Make Data copy without line feeds, carriage returns and bells for text side printing
For Position=0 to TotalFileLength-1
if Text.GetSubText(Data,Position,1)=Text.GetCharacter(10) or text.getsubtext(Data,Position,1)=text.getcharacter(13) or text.getsubtext(Data,Position,1)=text.getcharacter(7)then
DataCopy=Text.Append(DataCopy,Text.GetCharacter(46)) 'Replaces with "."
else
DataCopy=Text.Append(DataCopy,Text.GetSubText(Data,Position,1))
endif
endforFor FilePosition=0 to TotalFileLength-1 Step 16
If (TotalFileLength-1)-FilePosition > 15 then
LineLength=15 'Actually 16 because 0 is a position
Else
LineLength=TotalFileLength-FilePosition-1
endif
TextWindow.WriteLine("") 'Every other line on the screen is blank
Separator=0
For z = FilePosition To FilePosition+LineLength
Separator=Separator+1
If Separator=9 Then
TextWindow.Write("- ")
endif
charactercode=text.GetCharacterCode(Text.GetSubText(Data,z,1))
'Gets rid of FFFD character code
If charactercode = 65533 then
charactercode=0
endif
'Start breaking characters into hex
UpperHalf=math.Floor(Charactercode/16)UpperHalfCopy=UpperHalf
'Does upper half byte
ConvertHexHigher()
'Does lower half byte
UpperDecimal=UpperHalfCopy*16
LowerHalf=charactercode-UpperDecimal
ConvertHexLower()'Write full byte + space
TextWindow.Write(text.Append(UpperHalf ,LowerHalf+" "))
endfor'Separates the Hex side from the Decimal
spaces=" "
If Separator < 9 then
spaces=spaces + " " 'Adds 2 spaces for missing separator
endifFor padding =0 to 16-LineLength
spaces=spaces+" "
endfor
TextWindow.Writeline(spaces+text.GetSubText(DataCopy,FilePosition,LineLength+1))
Buffercount=Buffercount+1
If Buffercount=150 Then
TextWindow.WriteLine("Review Buffer. Hit Enter to Continue")
TextWindow.Read()
Buffercount=0
endif
endfor
TextWindow.WriteLine("")
TextWindow.writeline("Text Window will close by pressing Enter")
TextWindow.Read()
Program.End()Sub ConvertHexHigher 'Converts upper half byte to hex format
If UpperHalf=10 Then
UpperHalf="A"
ElseIf UpperHalf=11 then
UppereHalf="B"
elseif UpperHalf=12 then
UpperHalf="C"
elseif UpperHalf=13 then
UpperHalf="D"
Elseif UpperHalf=14 then
UpperHalf="E"
elseif UpperHalf=15 then
UpperHalf="F"
EndIf
EndSubSub ConvertHexLower 'Converts lower half byte to hex format
If LowerHalf=10 Then
LowerHalf="A"
ElseIf LowerHalf=11 then
LowerHalf="B"
elseif LowerHalf=12 then
LowerHalf="C"
elseif LowerHalf=13 then
LowerHalf="D"
Elseif LowerHalf=14 then
LowerHalf="E"
elseif LowerHalf=15 then
LowerHalf="F"
EndIf
EndSub - Here's a nice app to convert between USD, EUR and GBP (Based on Exchange rates of 18/2/09). Was going to add variable exchange rates and user=inputs, but i was too busy at the time
start: TextWindow.WriteLine("Exchange rates are based on 20/2/09") TextWindow.WriteLine("1. Convert from GBP to USD") TextWindow.WriteLine("2. Convert from USD to GBP") TextWindow.WriteLine("3. Convert from GBP to EUR") TextWindow.WriteLine("4. Convert from EUR to GBP") TextWindow.WriteLine("5. Convert from EUR to USD") TextWindow.WriteLine("6. Convert from USD to EUR") TextWindow.WriteLine("7. Exit") TextWindow.Write("Choose your selection: ") input = TextWindow.ReadNumber() If (input = 1) Then goto i1 EndIf If (input = 2) Then goto i2 EndIf If (input = 3) Then Goto i3 EndIf If (input = 4) Then Goto i4 EndIf If (input = 5) Then Goto i5 EndIf If (input = 6) Then Goto i6 EndIf If (input = 7) Then Goto i7 Else TextWindow.WriteLine("Invalid Entry - Try again!") Program.Delay(1000) TextWindow.Clear() Goto start EndIf i1: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in GBP: ") gbpi1 = TextWindow.ReadNumber() usdo1 = gbpi1*1.4349 TextWindow.WriteLine(gbpi1 + " GBP = " + usdo1 + " USD") Program.Delay(5000) TextWindow.Clear() Goto start i2: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in USD: ") usdi2 = TextWindow.ReadNumber() gbpo2 = usdi2*0.6969 TextWindow.WriteLine(usdi2 + " USD = " + gbpo2 + " GBP") Program.Delay(5000) TextWindow.Clear() Goto start i3: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in GBP: ") gbpi3 = TextWindow.ReadNumber() euro3 = gbpi3*1.1335 TextWindow.WriteLine(gbpi3 + " GBP = " + euro3 + " EUR") Program.Delay(5000) TextWindow.Clear() Goto start i4: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in EUR: ") euri4 = TextWindow.ReadNumber() gbpo4 = gbpi3*0.8867 TextWindow.WriteLine(euri4 + " EUR = " + gbpo4 + " GBP") Program.Delay(5000) TextWindow.Clear() Goto start i5: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in EUR: ") euri5 = TextWindow.ReadNumber() usdo5 = euri5*1.2690 TextWindow.WriteLine(euri5 + " EUR = " + usdo5 + " USD") Program.Delay(5000) TextWindow.Clear() Goto start i6: Program.Delay(1000) TextWindow.Clear() TextWindow.Write("Enter amount in USD: ") usdi6 = TextWindow.ReadNumber() euro6 = usdi6*0.7870 TextWindow.WriteLine(usdi6 + " USD = " + euro6 + " EUR") Program.Delay(5000) TextWindow.Clear() Goto start i7: Program.Delay(1000) TextWindow.Clear() TextWindow.WriteLine("Thank you for using this application") TextWindow.WriteLine(" ") TextWindow.WriteLine("(C)2009, Shmuxel (www.shmuxel.info)") TextWindow.WriteLine(" ") TextWindow.WriteLine("This Application was written on Microsoft Small Basic") Program.Delay(5000) Program.End()
I have re-written my Brick Wall program using Shapes for the bricks instead of drawing them.
Despite what Vijaye said about shapes being more "heavy/expensive" ("Adding a Shape Without it Showing in the Top Left Corner" thread) the speed of the code has improved, probably due to reduced complexity at the source level. I have also taken the opportunity to add a background image and do some tweaks to the software.
The shapes all get added at 0,0. I decided to use this as a feature instead of regarding it as a problem. The bricks are animated to their starting positions which I think gives quite a pleasing effect.Import ref: HBB072
- good job!!
moonhyuk choi - Thanks moonhyuk,
I now offer up a piece of "op art" in the spirit of Small Basic, in that it serves no purpose but it's just fun. Import "Sticks" from FWM281. - this is a music player i wipped up i might not work but i also might i dont know if it will.
1 music player! 2 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\Windows XP Startup.wav") 3 GraphicsWindow.ShowMessage("Thank you For lisening to my small basic media player","Thank You") 4 GraphicsWindow.Hide() 5 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\200265__Donkey_.mp3") 6 GraphicsWindow.ShowMessage("now for the next song","2") 7 GraphicsWindow.Hide() 8 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\Oh_No_Full_Length.mp3") 9 GraphicsWindow.ShowMessage("now for the next song","3") 10 GraphicsWindow.Hide() 11 Program.Delay(10) 12 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\alchemy[1].mp3") 13 GraphicsWindow.ShowMessage("now for the next song","4") 14 GraphicsWindow.Hide() 15 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\gamestartup01.mp3") 16 GraphicsWindow.ShowMessage("now for the next song","5") 17 GraphicsWindow.Hide() 18 Sound.PlayAndWait("C:\Documents and Settings\Jordan\Desktop\New Folder\windowsv.wav") 19 GraphicsWindow.ShowMessage("now for the next song","6") 20 GraphicsWindow.Hide() 21 Sound.PlayAndWait("135468_rickpwnerolledRemix.mp3") 22 GraphicsWindow.ShowMessage("Thanks agian for lisening and have a nice rest of your day","THANKs agian") 23 GraphicsWindow.ShowMessage("oh and last thing if you use my program add your name to the give credit list","one last thing" ) 24 GraphicsWindow.ShowMessage("this program gives credit to jfmherokiller","credit given list") 25 GraphicsWindow.Hide() - Desktop Wallpaper Change from web page contents
Sorry for my englishMain() Program.End() Sub Main PageContents=Network.GetWebPageContents("http://www.fotocommunity.de/pc/pc/channel/2/extra/new/display") TmpDir=File.GetTemporaryFilePath() File.WriteContents(TmpDir,PageContents) File.AppendContents(TmpDir,"Ronely") i=0 While("True") Text=File.ReadLine(TmpDir,i) i=i+1 SubText=Text.IsSubText(Text,"http://cdn.fotocommunity.com/thumbs/") if SubText="true" Then Len=Text.GetLength(Text) Goto Next Endif Endwhile Next: For i=0 To Len-1 Step 1 CmpSubText = Text.GetSubText(Text, i, 1) If CmpSubText = "d" then CmpSubText = Text.GetSubText(Text, i, 2) if CmpSubText = "di" then CmpSubText = Text.GetSubText(Text, i, 3) if CmpSubText = "dis" then ImgName = Text.GetSubText(Text, i+8 , 8) Goto Finish Endif Endif Endif EndFor Finish: desktop.SetWallPaper("http://cdn.fotocommunity.com/photos/"+ImgName+".jpg") Endsub - A simple yet difficult "lights out" style game where you try to turn all of the squares black. When you press ENTER on a square, you change its color, as well as the colors of the squares on its sides. Try it out, you'll see what I mean...
'The point of the game is to turn all of the squares black 'Move with arrow keys, 'Change select square with Enter GraphicsWindow.Width = 400 GraphicsWindow.Height = 400 GraphicsWindow.BackgroundColor = "DarkGray" GraphicsWindow.Title = "Turn em Off" GraphicsWindow.KeyDown = OnKeyDown GraphicsWindow.Clear() curx = 10 cury = 10 newx = 10 newy = 10 'Randomize and draw squars For i=0 To 5 For j=0 To 5 x = Math.GetRandomNumber(2) If (x = 2) Then curcolor = "Black" Else curcolor = "Yellow" EndIf GraphicsWindow.BrushColor = curcolor GraphicsWindow.FillRectangle(j*65+10,i*65+10,50,50) EndFor EndFor DrawCur() 'Draw currently selected square by drawing larger red square then a smaller square inside Sub DrawCur curcolor = GraphicsWindow.GetPixel(curx+25,cury+25) GraphicsWindow.BrushColor = "Red" GraphicsWindow.FillRectangle(curx,cury,50,50) GraphicsWindow.BrushColor = curcolor GraphicsWindow.FillRectangle(curx+2,cury+2,46,46) EndSub Sub OnKeyDown lkey = GraphicsWindow.LastKey 'Pre-set new cursor position If (lkey = "Right") And (curx < 300) Then newx = curx + 65 newy = cury EndIf If (lkey = "Left") And (curx > 10) Then newx = curx - 65 newy = cury EndIf If (lkey = "Down") And (cury < 300) Then newx = curx newy = cury + 65 EndIf If (lkey = "Up") And (cury > 10) Then newx = curx newy = cury - 65 EndIf 'Draw square in currunt square w/o red borders and move GraphicsWindow.BrushColor = curcolor GraphicsWindow.FillRectangle(curx,cury,50,50) curx = newx cury = newy If (lkey = "Return") Then 'Change current color tempcolor = curcolor ChangeColor() GraphicsWindow.FillRectangle(curx,cury,50,50) 'Change top color If (cury > 10) Then tempcolor = GraphicsWindow.GetPixel(curx+25,cury-40) ChangeColor() GraphicsWindow.FillRectangle(curx,cury-65,50,50) EndIf 'Change left color If (curx > 10) Then tempcolor = GraphicsWindow.GetPixel(curx-40,cury+25) ChangeColor() GraphicsWindow.FillRectangle(curx-65,cury,50,50) EndIf 'Change right color If (curx < 300) Then tempcolor = GraphicsWindow.GetPixel(curx+90,cury+25) ChangeColor() GraphicsWindow.FillRectangle(curx+65,cury,50,50) EndIf 'Change bottom color If (cury < 300) Then tempcolor = GraphicsWindow.GetPixel(curx+25,cury+90) ChangeColor() GraphicsWindow.FillRectangle(curx,cury+65,50,50) EndIf CheckWin() EndIf 'Redraw currently selected square DrawCur() EndSub 'Change color from black to yellow and otherwise Sub ChangeColor If (tempcolor = "#FFFF00") Then 'Yellow tempcolor = "Black" Else tempcolor = "Yellow" EndIf GraphicsWindow.BrushColor = tempcolor EndSub 'Check all spaces for any yellow. If not, you win and quit Sub CheckWin flagw = 0 For i=0 To 5 For j=0 To 5 If (GraphicsWindow.GetPixel(j*65+35,i*65+35) = "#FFFF00") Then flagw = 1 EndIf EndFor EndFor If (flagw = 0) Then GraphicsWindow.ShowMessage("YOU WIN!","WINNER") Program.End() EndIf EndSub
Good luck, it IS possible to beat. Oh, and thanks for small basic! - "Lights Out" is our sample of the week: http://blogs.msdn.com/smallbasic
- I know you have already chosen your program for the blog but heres mine anyway, its just a simple etch a scetch although dose draw at a bit of an angle =D
'My first SB app, not my first VB one though ;) 'Learnt all of this syntax from all of you =D thankyou! 'By Oliver Caldwell, 15, VB and SB rule! 'And this runs off my memory stick...code in school =) posx = GraphicsWindow.Width / 2 posy = GraphicsWindow.Height / 2 Switch1 = False GraphicsWindow.Show() GraphicsWindow.Title = "Etch a scetch!" GraphicsWindow.Width = 1000 GraphicsWindow.Height = 700 GraphicsWindow.Left = 20 GraphicsWindow.Top = 20 GraphicsWindow.BackgroundColor = "Red" GraphicsWindow.BrushColor = "Gray" GraphicsWindow.FillRectangle(20, 20, 960, 660) GraphicsWindow.BrushColor = "White" GraphicsWindow.FillEllipse(10, 650, 100, 100) GraphicsWindow.FillEllipse(890, 650, 100, 100) GraphicsWindow.BrushColor = "Black" GraphicsWindow.MouseDown = MouseDown GraphicsWindow.MouseUp = MouseUp GraphicsWindow.MouseMove = OnMouseMove Sub MouseDown Switch1 = "True" EndSub Sub MouseUp Switch1 = "False" EndSub Sub OnMouseMove If Mouse.MouseX > posx And Switch1 = "True" Then posx = posx + 1 GraphicsWindow.FillRectangle(posx, posy, 1, 1) ElseIf Mouse.MouseX < posx And Switch1 = "True" Then posx = posx - 1 GraphicsWindow.FillRectangle(posx, posy, 1, 1) EndIf If Mouse.MouseY > posy And Switch1 = "True" Then posy = posy + 1 GraphicsWindow.FillRectangle(posx, posy, 1, 1) ElseIf Mouse.MouseY < posy And Switch1 = "True" Then posy = posy - 1 GraphicsWindow.FillRectangle(posx, posy, 1, 1) Endif EndSub
Heres a screen shot:
Have fun ;) Wolfy87oc. I've written an extension that makes the serial port usable in Small Basic. It can be downloaded at http://code.msdn.microsoft.com/sbserial.
In the spirit of Small Basic, the extension purposefully makes assumptions about data bits, parity and stop bits. Flow control defaults to None, but hardware flow control can be activated if needed. There is no error handling, but (some) parameters passed to the extension are checked for validity and ignored if invalid. If the extension fails to find the comm port specified in OpenPort, the highest numbered port available is opened.
Example SB code to use with a serial loopback cable: SNL137
' Example code for use with the SmallBasicSerialPort extension and a loopback
' serial cable.
' Replace "COM8", 75000 with settings appropriate for your system.
' Nino Carrillo 2009CommPort.OpenPort("COM8",75000) 'Open COM8 at 75000 baud
CommPort.TXString("Hello World") 'Send a string to the port
CommPort.TXByte(10) 'Send linefeed
CommPort.TXByte(13) 'Send carriage return
Program.Delay(500) 'wait for buffers to fill
TextWindow.Write(CommPort.RXAll()) 'read the entire contents of the receive buffer and display
CommPort.TXString("A") 'send the letter A
Program.Delay(500)
TextWindow.Write("The value of the received byte is: " + CommPort.RXByte())
CommPort.TXByte(10) 'Send linefeed
CommPort.TXByte(13) 'Send carriage return
Program.Delay(500)
TextWindow.Write(CommPort.RXAll())
CommPort.TXString("A")
TextWindow.Write("The character received is: "+ CommPort.RXChar())
CommPort.TXByte(10) 'Send linefeed
CommPort.TXByte(13) 'Send carriage return
Program.Delay(500)
TextWindow.Write(CommPort.RXAll())
CommPort.ClosePort()
TextWindow.Write("List of ports available: " + CommPort.AvailablePorts())This is Login/Laod program, save program coming soon. This is just a small EX:
T = 5 F = File.GetTemporaryFilePath() TextWindow.WriteLine("Welcome to the land of Ncioah") TextWindow.WriteLine("Are you a new or old user?") R = TextWindow.Read() If(R = "new")Then TextWindow.Hide() TextWindow.Show() TextWindow.WriteLine("Signup Sheet") TextWindow.Write("Username:") Y = TextWindow.Read() TextWindow.WriteLine("Password:") X = TextWindow.Read() File.WriteContents(F, Y + " " + X) C = File.ReadContents(F) Textwindow.WriteLine("Please login") Goto start EndIf If(R = "old")Then Start: If(T = "0")Then Program.End() EndIf TextWindow.WriteLine("Username") RR = TextWindow.Read() TextWindow.WriteLine("Password") RRR = TextWindow.Read() RRRR = File.ReadContents(F) If(Text.IsSubText(RRRR, RR + " " + RRR))Then TextWindow.WriteLine("You have succesfully logged in") Else T = T-1 TextWindow.WriteLine("Login Failed " + T + " tries left") Goto Start EndIf EndIfTry it and tell me what you think. This can be used for like mario style games. Or maybe you suddenly have to stop pong but you were doing so good. This will help that.
Here is my Color Script. The turtle paints a pretty picture in my opinion! Enjoy!
GraphicsWindow.KeyDown = K
GraphicsWindow.Show()
GraphicsWindow.PenColor = "black"
GraphicsWindow.BackgroundColor = "blue"
Turtle.Speed = 10
angle = 12343
Squiral()
Sub Squiral
side = 0
For i = 1 To 360
Turtle.Move(side)
Turtle.Turn(angle)
side = side + 1
EndFor
EndSub
Program.Delay(10)Sub K
If(GraphicsWindow.LastKey = "F1")Then
Program.End()
EndIf
EndSub
If you tamper around with the angle you find that the figure changes drastically. It is sure to come up with many more shapes and excitment!!! By: Jacob- This is V1.0 of a Paint program I am working on. This program uses the GraphicsWindow as the workspace, and the TextWindow as the command reader. Type in commands in the textwindow to change the tools in the GraphicsWindow, most of the commands are listed in the Help section. Select the graphicsWindow and press H for most of the commands.
Please post requests for new functions and Ideas so that I can keep improving this program, my next V1.2 will be posted probably in a week or two. I am working on V1.2 and I have added a turtle function. You can either type in the co's X and Y for it to move to that position or type which direction and color and how far. I haven't made it so you can do angles yet though.GraphicsWindow.Title = "Paint V1.0" TextWindow.Title = "Command reader for Paint V1.0" OH = GraphicsWindow.Height OW = GraphicsWindow.Width GraphicsWindow.Height = OH GraphicsWindow.Width = OW GraphicsWindow.MouseMove = OnMouseMove GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.KeyDown = K GraphicsWindow.BrushColor = "red" GraphicsWindow.DrawBoundText(10,10,100,"Press H for help") GraphicsWindow.DrawBoundText(10,30,200,"Click to draw") GraphicsWindow.DrawBoundText(10,50,200,"Type commands in the Text Window") GraphicsWindow.DrawBoundText(10,80,300,"Paint your masterpeice!") While(1=1) TextWindow.WriteLine("type commands") P = TextWindow.Read() C = Text.ConvertToLowerCase(P) Read() EndWhile Sub K If(GraphicsWindow.LastKey = "H")Then Help() Endif Endsub Sub OnMouseDown prevX = GraphicsWindow.MouseX prevY = GraphicsWindow.MouseY EndSub Sub OnMouseMove x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY If (Mouse.IsLeftButtonDown) Then GraphicsWindow.DrawLine(prevX, prevY, x, y) EndIf prevX = x prevY = y EndSub Sub Read If(C = "color")Then Color() EndIf If(C = "bg color")Then Bgcolr() EndIf If(C = "pensize")Then Pen() EndIf If(C = "clear")Then Clear() EndIf If(C = "window size")Then GWS() EndIf If(C = "clear tewindow")Then ClearT() EndIf If(C = "eraser")Then Eraser() EndIf If(C = "rbg color")Then RBG() EndIf If(C = "window.size = desktop")Then Desktop() EndIf If(C = "window.size = half")Then Half() EndIf If(C = "window.size = orignal")Then Original() EndIf If(C = "rp color")Then RPC() EndIf If(C = "text.color")Then TC() EndIf If(C = "new")Then New() EndIf If(C = "commands")Then Commands() EndIf EndSub Sub Color TextWindow.WriteLine("Type color") L = TextWindow.Read() GraphicsWindow.PenColor = L EndSub Sub Bgcolr TextWindow.WriteLine("Type color") W = TextWindow.Read() GraphicsWindow.BackgroundColor = W EndSub Sub Pen TextWindow.WriteLine("Type size") Size = TextWindow.ReadNumber() GraphicsWindow.PenWidth = Size EndSub Sub Clear GraphicsWindow.Clear() EndSub Sub GWS TextWindow.WriteLine("Type Height") HE = TextWindow.ReadNumber() TextWindow.WriteLine("Type Width") WI = TextWindow.ReadNumber() GraphicsWindow.Height = HE GraphicsWindow.Width = WI EndSub Sub Help GraphicsWindow.ShowMessage("Instructions", "HELP") GraphicsWindow.ShowMessage("Click to draw", "HELP") GraphicsWindow.ShowMessage("Use the Text Window to type commands", "HELP") GraphicsWindow.ShowMessage("Type color to access the colors function", "HELP") GraphicsWindow.ShowMessage("Then type the color you want to change it to", "HELP") GraphicsWindow.ShowMessage("Type bg color to access the background colors", "HELP") GraphicsWindow.ShowMessage("Type window size to resize the Graphics window", "HELP") GraphicsWindow.ShowMessage("Type clear to clear the screen", "HELP") GraphicsWindow.ShowMessage("Type clear textwindow to clear the textwindow", "HELP") GraphicsWindow.ShowMessage("Type window.size = desktop to make a full screen window", "HELP") GraphicsWindow.ShowMessage("Type window.size = half for a half screen window", "HELP") GraphicsWindow.ShowMessage("Type rbg color for a random background color", "HELP") GraphicsWindow.ShowMessage("Type rp color for a random pencolor", "HELP") EndSub Sub ClearT TextWindow.Clear() EndSub Sub Eraser GraphicsWindow.PenColor = GraphicsWindow.BackgroundColor EndSub Sub RBG GraphicsWindow.BackgroundColor = GraphicsWindow.GetRandomColor() EndSub Sub Desktop GraphicsWindow.Height = Desktop.Height - 65 GraphicsWindow.Width = Desktop.Width - 10 EndSub Sub Half GraphicsWindow.Height = Desktop.Height-200 GraphicsWindow.Width = Desktop.Width-200 EndSub Sub Original GraphicsWindow.Width = OW GraphicsWindow.Height = OH EndSub Sub RPC GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndSub Sub TC TextWindow.WriteLine("Type color") Forec = TextWindow.Read() TextWindow.ForegroundColor = Forec EndSub Sub New GraphicsWindow.Clear() TextWindow.Clear() EndSub Sub Commands GraphicsWindow.Clear() GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawBoundText(10,10,100,"Soon to come") 'I will add this in the next version' 'it will be a list of all the commands and sub commands in the system' EndSub
The Hacker A Chess Game in Small Basic (no, there's no AI !)
The moves are checked to see if they are valid. You need two players to play the game.
The game is in French (though it's only welcome & error messages that are in French). Echecs are not discovered by the program, the play stops when one of the king are taken by another piece.
If you discover bug, I'm ready to fix theses, but I think everything should be good.
[EDIT] Edited today to support Roques. My program doesn't check if the king is in echec at any position of the roque's move.
You can download the game (.exe), the source code and the images at this location :
http://cid-201f3835d49587fe.skydrive.live.com/self.aspx/Public/Small%20Basic/ChessGame.zip
For information, there's 550 lines of code. I used my extension for the UI.
Fremy
Fremy - Developer in VB.NET, C# and JScript ... - Feel free to try my extension- 已編輯FremyCompany解答者Sunday, 19 April, 2009 7:44
- Here is V1.1 of my paint program, it now has 435 lines of code. The turtle function has been added and if you type commands.list in the command window it will list all the commands in the system V1.1 and all the sub commands will be added in V1.2. Try it out!
'SKC161' '435 lines!' GraphicsWindow.Title = "Paint V1.0" TextWindow.Title = "Command reader for Paint V1.0" OH = GraphicsWindow.Height OW = GraphicsWindow.Width GraphicsWindow.Height = OH GraphicsWindow.Width = OW GraphicsWindow.MouseMove = OnMouseMove GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.KeyDown = K GraphicsWindow.BrushColor = "red" GraphicsWindow.DrawBoundText(10,10,100,"Press H for help") GraphicsWindow.DrawBoundText(10,30,200,"Click to draw") GraphicsWindow.DrawBoundText(10,50,200,"Type commands.list in the Text Window for more help") GraphicsWindow.DrawBoundText(10,80,300,"Paint your masterpeice!") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("What's your name?") RNT = TextWindow.Read() GraphicsWindow.Title = RNT + "'s masterpeice! V1.1" TextWindow.ForegroundColor = "gray" While(1=1) TextWindow.WriteLine("type commands") P = TextWindow.Read() C = Text.ConvertToLowerCase(P) Read() EndWhile Sub K If(GraphicsWindow.LastKey = "H")Then Help() Endif Endsub Sub OnMouseDown prevX = GraphicsWindow.MouseX prevY = GraphicsWindow.MouseY EndSub Sub OnMouseMove x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY If (Mouse.IsLeftButtonDown) Then GraphicsWindow.DrawLine(prevX, prevY, x, y) EndIf prevX = x prevY = y EndSub Sub Read If(C = "pen.color")Then Color() EndIf If(C = "paint.bgcolor")Then Bgcolr() EndIf If(C = "pen.size")Then Pen() EndIf If(C = "paint.clear")Then Clear() EndIf If(C = "paint.window.size")Then GWS() EndIf If(C = "text.clear")Then ClearT() EndIf If(C = "paint.eraser")Then Eraser() EndIf If(C = "paint.rbgcolor")Then RBG() EndIf If(C = "window.size = desktop")Then Desktop() EndIf If(C = "window.size = half")Then Half() EndIf If(C = "window.size = orignal")Then Original() EndIf If(C = "paint.rpcolor")Then RPC() EndIf If(C = "text.color")Then TC() EndIf If(C = "project.new")Then New() EndIf If(C = "commands.list")Then Commands() EndIf If(C = "turtle.moveto")Then TurtleM() EndIf If(C = "turtle.move")Then Turtle() EndIf If(C = "flickr.random")THen Flickr() Endif If(C = "text.bgcolor")Then TBGC() EndIf If(C = "text.name")THen TWN() EndIf If(C = "project.name")Then PaintN() EndIf If(C = "paint.pen")Then PPEN() EndIf EndSub Sub Color TextWindow.WriteLine("Type color") L = TextWindow.Read() GraphicsWindow.PenColor = L EndSub Sub Bgcolr TextWindow.WriteLine("Type color") W = TextWindow.Read() GraphicsWindow.BackgroundColor = W EndSub Sub Pen TextWindow.WriteLine("Type size") Size = TextWindow.ReadNumber() GraphicsWindow.PenWidth = Size EndSub Sub Clear GraphicsWindow.Clear() EndSub Sub GWS TextWindow.WriteLine("Type Height") HE = TextWindow.ReadNumber() TextWindow.WriteLine("Type Width") WI = TextWindow.ReadNumber() GraphicsWindow.Height = HE GraphicsWindow.Width = WI EndSub Sub Help GraphicsWindow.ShowMessage("Instructions", "HELP") GraphicsWindow.ShowMessage("Click to draw", "HELP") GraphicsWindow.ShowMessage("Use the Text Window to type commands", "HELP") GraphicsWindow.ShowMessage("Type color to access the colors function", "HELP") GraphicsWindow.ShowMessage("Then type the color you want to change it to", "HELP") GraphicsWindow.ShowMessage("Type bg color to access the background colors", "HELP") GraphicsWindow.ShowMessage("Type window size to resize the Graphics window", "HELP") GraphicsWindow.ShowMessage("Type clear to clear the screen", "HELP") GraphicsWindow.ShowMessage("Type clear textwindow to clear the textwindow", "HELP") GraphicsWindow.ShowMessage("Type window.size = desktop to make a full screen window", "HELP") GraphicsWindow.ShowMessage("Type window.size = half for a half screen window", "HELP") GraphicsWindow.ShowMessage("Type rbg color for a random background color", "HELP") GraphicsWindow.ShowMessage("Type rp color for a random pencolor", "HELP") EndSub Sub ClearT TextWindow.Clear() EndSub Sub Eraser GraphicsWindow.PenColor = GraphicsWindow.BackgroundColor EndSub Sub RBG GraphicsWindow.BackgroundColor = GraphicsWindow.GetRandomColor() EndSub Sub Desktop GraphicsWindow.Height = Desktop.Height - 65 GraphicsWindow.Width = Desktop.Width - 10 EndSub Sub Half GraphicsWindow.Height = Desktop.Height-200 GraphicsWindow.Width = Desktop.Width-200 EndSub Sub Original GraphicsWindow.Width = OW GraphicsWindow.Height = OH EndSub Sub RPC GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() EndSub Sub TC TextWindow.WriteLine("Type text foreground color") Forec = TextWindow.Read() TextWindow.ForegroundColor = Forec EndSub Sub New GraphicsWindow.Clear() TextWindow.Clear() EndSub Sub Commands TextWindow.Clear() TextWindow.ForegroundColor = "yellow" TextWindow.WriteLine("Here is a list of all the commands") TextWindow.WriteLine("Commands will be listed in red") TextWindow.WriteLine("Sub commands will be liste in blue under there parent command(Will be added in later version)") TextWindow.WriteLine("Summarys of commands and Sub commands will be listed under there parent in gray") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("pen.color") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("will let you choose the color of the pen/pencil") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Pen.Size") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the size of the pen/pencil") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.bgcolor") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the background color of the graphicswindow") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Clear") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will clear the project screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Window.Size") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the size of the project window") TextWindow.ForegroundColor = "red" TextWindow.WriteLine(" ") TextWindow.WriteLine("Text.Clear") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will clear the command screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Eraser") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen to an eraser") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Pen") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen from eraser back to pen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.RBGColor") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the project screens background color to a random color") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you change the size of the project window") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size = Desktop") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will make the project window full screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size = Half") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the project window to half screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.RPColor") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen to a random color") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.Color") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you change the color of the text in the command screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Project.New") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will clear both the command screen and the project screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Commands.List") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will list all the commands and sub commands in the system") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Turtle.Move") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you draw lines with the turtle function") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Turtle.MoveTo") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you draw lines with the turtle using the X and Y axis") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Flickr.Random") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will choose a random picture from Flickr and set it for the background") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.BGColor") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the background color for the command screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.Name") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the name of the command screen, the text on the top bar of the command screen") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Project.Name") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you change the name of the project screen, the text on the top bar of the project screen") EndSub Sub TurtleM TextWindow.WriteLine("Pen up or Pen down?") RRR = TextWindow.Read() If(RRR = "up")Then Turtle.PenUp() TextWindow.WriteLine("Turtle.MoveTo X co's?") R = TextWindow.ReadNumber() TextWindow.WriteLine("Turtle.MoveTo Y co's") RR = TextWindow.ReadNumber() Turtle.MoveTo(R,RR) ElseIf(RRR = "down")Then TextWindow.WriteLine("What color?") RRRR = TextWindow.Read() GraphicsWindow.PenColor = RRRR Turtle.PenDown() TextWindow.WriteLine("Turtle.MoveTo X co's?") R = TextWindow.ReadNumber() TextWindow.WriteLine("Turtle.MoveTo Y co's") RR = TextWindow.ReadNumber() Turtle.MoveTo(R,RR) EndIf EndSub Sub Turtle TextWindow.WriteLine("Which direction") RD = TextWindow.Read() TextWindow.WriteLine("How many degrees?") RTD = TextWindow.ReadNumber() TextWindow.WriteLine("Pen up or Pen down?") RUD = TextWindow.Read() TextWindow.WriteLine("How far?") RDD = TextWindow.ReadNumber() TextWindow.WriteLine("What color?") RC = TextWindow.Read() GraphicsWindow.PenColor = RC If(RUD = "up")Then Turtle.PenUp() ElseIf(RUD = "down")Then Turtle.PenDown() EndIf If(RD = "right")Then Turtle.TurnRight() Turtle.Move(RDD) ElseIf(RD = "left")Then Turtle.TurnLeft() Turtle.Move(RDD) EndIf If(RD = "angle")Then Turtle.Turn(RTD) Turtle.Move(RDD) EndIf EndSub Sub Flickr TextWindow.WriteLine("Subject one?") RSO = TextWindow.Read() TextWindow.WriteLine("Subject two") RST = TextWindow.Read() Pic = Flickr.GetRandomPicture(RSO + RST) GraphicsWindow.DrawResizedImage(Pic,0,0,GraphicsWindow.Width,GraphicsWindow.Height) EndSub Sub TBGC TextWindow.WriteLine("Type text background color") RTBGC = TextWindow.Read() TextWindow.BackgroundColor = RTBGC TextWindow.Clear() EndSub Sub TWN TextWindow.WriteLine("New Name?") RNN = TextWindow.Read() TextWindow.Title = RNN Endsub Sub PaintN TextWindow.WriteLine("New project name?") RNPN = TextWindow.Read() GraphicsWindow.Title = RNPN EndSub Sub PPEN GraphicsWindow.PenColor = "black" EndSub - Looks great, the hacker.
It would be even better if you can use buttons in the master window to handle the GUI.
You should then restrict the zone where we can paint, though...
Fremy - Developer in VB.NET, C# and JScript ... - Feel free to try my extension I am actually working on a version with buttons and the textwindow. So that the buttons will control the main commands like color, eraser e.t.c. Thanks for the idea.
I have finished a few buttons and the painting box for V1.3, but ran into some difficultys with the turtle functions. So it might be a little longer then expected but it'll be worth the wait!- Here is V1.3(Added buttons). Features have been added that have not been listed yet, but don't worry they will be. I am still having problems with the turtle functions. I can't get it to stop drawing once it leaves the square. But if you have any function requests or ideas please contribute them. If you find any bugs please tell me as well.
'Epic Paint' 'V1.3(beta)' '802 lines!' 'WDL232' Size = 1 L = GraphicsWindow.PenColor GraphicsWindow.Title = "Paint V1.3" TextWindow.Title = "Command reader for Paint V1.3" 'Sets the first buttons X and Y co's' ButtonY = GraphicsWindow.Height-20 ButtonX = GraphicsWindow.Width-625 'Sets the height and width of all the buttons' ButtonHe = 10 ButtonWi = 10 'Sets the second buttons X and Y co's' Button2Y = GraphicsWindow.Height-20 Button2X = GraphicsWindow.Width-614 GreenY = GraphicsWindow.Height-20 GreenX = GraphicsWindow.Width-602 ToolsX = 10 ToolsY = 200 EraserX = 15 EraserY = 205 EraserWi = 40 EraserHe = 15 PenX = 65 PenY = 205 GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawRectangle(PenX,PenY,EraserWi,EraserHe) GraphicsWindow.DrawBoundText(PenX+5,PenY,EraserWi,"Pen") GraphicsWindow.DrawBoundText(EraserX,EraserY,EraserWi,"Eraser") GraphicsWindow.DrawRectangle(EraserX,EraserY,40,15) BoxX = 120 BoxY = 10 BoxHe = 400 BoxWi = 500 GraphicsWindow.DrawRectangle(ToolsX,ToolsY,100,200) GraphicsWindow.BrushColor = "green" GraphicsWindow.FillRectangle(GreenX,GreenY,ButtonWi,ButtonHe) GraphicsWindow.DrawRectangle(BoxX,BoxY,BoxWi,BoxHe) 'Draws the first button' GraphicsWindow.BrushColor = "blue" GraphicsWindow.FillRectangle(Button2X,Button2Y,ButtonWi,ButtonHe) 'Draws the second button' GraphicsWindow.BrushColor = "red" GraphicsWindow.FillRectangle(ButtonX,ButtonY,ButtonWi,ButtonHe) GraphicsWindow.BrushColor = "blue" GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-40,100,"Pen.Size = " + Size) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-60,300, "Turtle.Color = " + L) OH = GraphicsWindow.Height OW = GraphicsWindow.Width GraphicsWindow.Height = OH GraphicsWindow.Width = OW GraphicsWindow.MouseMove = OnMouseMove GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.KeyDown = K 'Draws a few help commands' GraphicsWindow.BrushColor = "red" GraphicsWindow.DrawBoundText(10,10,100,"1, Press H for help") GraphicsWindow.DrawBoundText(10,50,100,"2, Click to draw") GraphicsWindow.DrawBoundText(10,80,100,"3, Type commands.list in the Text Window for more help") GraphicsWindow.DrawBoundText(10,160,100,"4, Paint your masterpeice") 'Changes the title of the project windows to "Your name here"(s) masterpeice' TextWindow.ForegroundColor = "red" TextWindow.WriteLine("What's your name?") RNT = TextWindow.Read() GraphicsWindow.Title = RNT + "'s masterpeice! V1.1" TextWindow.Title = RNT + "'s masterpeice TextWindow.ForegroundColor = "gray" 'Generates a forever going While loop that reads the users commands' While(1=1) 'Plays a clicking sound' Sound.PlayClick() TextWindow.WriteLine("type commands") P = TextWindow.Read() C = Text.ConvertToLowerCase(P) Read() EndWhile Sub K If(GraphicsWindow.LastKey = "H")Then Sound.PlayClick() Help() Endif Endsub Sub OnMouseDown Sound.PlayClick() 'Gets the X and Y co's for where the mouse clicked' prevX = GraphicsWindow.MouseX prevY = GraphicsWindow.MouseY 'Checks if they clicked inside the first button' If(prevX > ButtonX And prevX < (ButtonX + ButtonWi)) And (prevY > ButtonY And prevY < (ButtonY + ButtonHe))Then GraphicsWindow.PenColor = "red" GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) L = GraphicsWindow.PenColor GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) 'Checks if they clicked inside the second button' ElseIf(prevX > Button2X And prevX < (Button2X + ButtonWi)) And (prevY > Button2Y And prevY < (Button2Y + ButtonHe))Then GraphicsWindow.PenColor = "blue" GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) L = GraphicsWindow.PenColor GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) ElseIf(prevX > GreenX And prevX < (GreenX + ButtonWi)) And (prevY > GreenY And prevY < (GreenY + ButtonHe))Then GraphicsWindow.PenColor = "green" GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) L = GraphicsWindow.PenColor GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) ElseIf(prevX > EraserX And prevX < (EraserX + EraserWi)) And (prevY > EraserY And prevY < (EraserY + EraserHe))Then GraphicsWindow.PenColor = GraphicsWindow.BackgroundColor GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = Eraser") ElseIf(prevX > PenX And prevX < (PenX + EraserWi)) And (prevY > PenY And prevY < (PenY + EraserHe))Then GraphicsWindow.PenColor = "black" GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = Black") EndIf If(prevX > BoxX And prevX < (BoxX + BoxWi)) And (prevY > BoxY And prevY < (BoxY + BoxHe))Then If(Mouse.IsRightButtonDown = "true")Then GraphicsWindow.DrawRectangle(GraphicsWindow.MouseX,GraphicsWindow.MouseY,50,50) EndIf EndIf EndSub Sub OnMouseMove If(prevX > BoxX And prevX < (BoxX + BoxWi)) And (prevY > BoxY And prevY < (BoxY + BoxHe))Then 'Gets the X and Y co's of the mouse whenever it moves forever' x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY 'Checks if the left is down and draws the line' If (Mouse.IsLeftButtonDown) Then GraphicsWindow.DrawLine(prevX, prevY, x, y) EndIf EndIf prevX = x prevY = y EndSub Sub Read 'Checks if the command inputed by the user is valid' If(C = "pen.color")Then Sound.PlayClick() Color() EndIf If(C = "paint.bgcolor")Then Sound.PlayClick() Bgcolr() EndIf If(C = "pen.size")Then Sound.PlayClick() Pen() EndIf If(C = "paint.clear")Then Sound.PlayClick() Clear() EndIf If(C = "paint.window.size")Then Sound.PlayClick() GWS() EndIf If(C = "text.clear")Then Sound.PlayClick() ClearT() EndIf If(C = "paint.eraser")Then Sound.PlayClick() Eraser() EndIf If(C = "paint.rbgcolor")Then Sound.PlayClick() RBG() EndIf If(C = "window.size = desktop")Then Sound.PlayClick() Desktop() EndIf If(C = "window.size = half")Then Sound.PlayClick() Half() EndIf If(C = "window.size = orignal")Then Sound.PlayClick() Original() EndIf If(C = "paint.rpcolor")Then RPC() EndIf If(C = "text.color")Then TC() EndIf If(C = "project.new")Then Sound.PlayClick() New() EndIf If(C = "commands.list")Then Sound.PlayClick() Commands() EndIf If(C = "turtle.moveto")Then Sound.PlayClick() TurtleM() EndIf If(C = "turtle.move")Then Sound.PlayClick() Turtle() EndIf If(C = "flickr.random")THen Sound.PlayClick() Flickr() Endif If(C = "text.bgcolor")Then Sound.PlayClick() TBGC() EndIf If(C = "text.name")THen Sound.PlayClick() TWN() EndIf If(C = "project.name")Then Sound.PlayClick() PaintN() EndIf If(C = "paint.pen")Then Sound.PlayClick() PPEN() EndIf If(C = "turtle.hide")Then Sound.PlayClick() TurtleH() EndIf If(C = "turtle.draw.rect")Then Turtlerect() EndIf If(C = "turtle.draw.star")Then Star() EndIf EndSub Sub Color 'Changes the pen color to whatever color you can think of' TextWindow.WriteLine("Type color") L = TextWindow.Read() GraphicsWindow.PenColor = L GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub Sub Bgcolr 'Changes the background color to whatever color you can think of' TextWindow.WriteLine("Type color") W = TextWindow.Read() GraphicsWindow.BackgroundColor = W EndSub Sub Pen Pen: 'Changes the pen size to whatever number you wish below 6' TextWindow.WriteLine("Type size") Size = TextWindow.ReadNumber() If(Size < 6)Then GraphicsWindow.PenWidth = Size GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-40,110,15) GraphicsWindow.BrushColor = "blue" GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-40,100,"Pen.Size = " + Size) ElseIf(Size >= 6)Then TextWindow.WriteLine("Invalid size") Goto Pen EndIf EndSub Sub Clear GraphicsWindow.Clear() EndSub Sub GWS TextWindow.WriteLine("Type Height") HE = TextWindow.ReadNumber() Sound.PlayClick() TextWindow.WriteLine("Type Width") WI = TextWindow.ReadNumber() GraphicsWindow.Height = HE GraphicsWindow.Width = WI EndSub Sub Help GraphicsWindow.ShowMessage("Instructions", "HELP") GraphicsWindow.ShowMessage("Click to draw", "HELP") GraphicsWindow.ShowMessage("Use the Text Window to type commands", "HELP") GraphicsWindow.ShowMessage("Type color to access the colors function", "HELP") GraphicsWindow.ShowMessage("Then type the color you want to change it to", "HELP") GraphicsWindow.ShowMessage("Type bg color to access the background colors", "HELP") GraphicsWindow.ShowMessage("Type window size to resize the Graphics window", "HELP") GraphicsWindow.ShowMessage("Type clear to clear the screen", "HELP") GraphicsWindow.ShowMessage("Type clear textwindow to clear the textwindow", "HELP") GraphicsWindow.ShowMessage("Type window.size = desktop to make a full screen window", "HELP") GraphicsWindow.ShowMessage("Type window.size = half for a half screen window", "HELP") GraphicsWindow.ShowMessage("Type rbg color for a random background color", "HELP") GraphicsWindow.ShowMessage("Type rp color for a random pencolor", "HELP") EndSub Sub ClearT TextWindow.Clear() EndSub Sub Eraser GraphicsWindow.PenColor = GraphicsWindow.BackgroundColor EndSub Sub RBG GraphicsWindow.BackgroundColor = GraphicsWindow.GetRandomColor() EndSub Sub Desktop GraphicsWindow.Height = Desktop.Height - 65 GraphicsWindow.Width = Desktop.Width - 10 EndSub Sub Half GraphicsWindow.Height = Desktop.Height-200 GraphicsWindow.Width = Desktop.Width-200 EndSub Sub Original GraphicsWindow.Width = OW GraphicsWindow.Height = OH EndSub Sub RPC GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor() L = GraphicsWindow.PenColor GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub Sub TC TextWindow.WriteLine("Type text foreground color") Forec = TextWindow.Read() TextWindow.ForegroundColor = Forec EndSub Sub New 'Epic Paint' 'V1.3(beta)' '700 lines!' Size = 1 L = GraphicsWindow.PenColor GraphicsWindow.Title = "Paint V1.3" TextWindow.Title = "Command reader for Paint V1.3" 'Sets the first buttons X and Y co's' ButtonY = GraphicsWindow.Height-20 ButtonX = GraphicsWindow.Width-625 'Sets the height and width of all the buttons' ButtonHe = 10 ButtonWi = 10 'Sets the second buttons X and Y co's' Button2Y = GraphicsWindow.Height-20 Button2X = GraphicsWindow.Width-614 GreenY = GraphicsWindow.Height-20 GreenX = GraphicsWindow.Width-602 ToolsX = 10 ToolsY = 200 EraserX = 15 EraserY = 205 EraserWi = 40 EraserHe = 15 GraphicsWindow.BrushColor = "black" GraphicsWindow.DrawBoundText(EraserX,EraserY,EraserWi,"Eraser") GraphicsWindow.DrawRectangle(EraserX,EraserY,40,15) BoxX = 120 BoxY = 10 BoxHe = 400 BoxWi = 500 GraphicsWindow.DrawRectangle(ToolsX,ToolsY,100,200) GraphicsWindow.BrushColor = "green" GraphicsWindow.FillRectangle(GreenX,GreenY,ButtonWi,ButtonHe) GraphicsWindow.DrawRectangle(BoxX,BoxY,BoxWi,BoxHe) 'Draws the first button' GraphicsWindow.BrushColor = "blue" GraphicsWindow.FillRectangle(Button2X,Button2Y,ButtonWi,ButtonHe) 'Draws the second button' GraphicsWindow.BrushColor = "red" GraphicsWindow.FillRectangle(ButtonX,ButtonY,ButtonWi,ButtonHe) GraphicsWindow.BrushColor = "blue" GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-40,100,"Pen.Size = " + Size) GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) OH = GraphicsWindow.Height OW = GraphicsWindow.Width GraphicsWindow.Height = OH GraphicsWindow.Width = OW GraphicsWindow.MouseMove = OnMouseMove GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.KeyDown = K 'Draws a few help commands' GraphicsWindow.BrushColor = "red" GraphicsWindow.DrawBoundText(10,10,100,"1, Press H for help") GraphicsWindow.DrawBoundText(10,50,100,"2, Click to draw") GraphicsWindow.DrawBoundText(10,80,100,"3, Type commands.list in the Text Window for more help") GraphicsWindow.DrawBoundText(10,160,100,"4, Paint your masterpeice") 'Changes the title of the project windows to "Your name here"(s) masterpeice' TextWindow.ForegroundColor = "red" TextWindow.WriteLine("What's your name?") RNT = TextWindow.Read() GraphicsWindow.Title = RNT + "'s masterpeice! V1.1" TextWindow.Title = RNT + "'s masterpeice TextWindow.ForegroundColor = "gray" 'Generates a forever going While loop that reads the users commands' EndSub Sub Commands TextWindow.Clear() TextWindow.ForegroundColor = "yellow" TextWindow.WriteLine("Here is a list of all the commands") Sound.PlayClick() TextWindow.WriteLine("Commands will be listed in red") Sound.PlayClick() TextWindow.WriteLine("Sub commands will be liste in blue under there parent command(Will be added in later version)") Sound.PlayClick() TextWindow.WriteLine("Summarys of commands and Sub commands will be listed under there parent in gray") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" Sound.PlayClick() TextWindow.WriteLine("pen.color") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("will let you choose the color of the pen/pencil") TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" Sound.PlayClick() TextWindow.WriteLine("Pen.Size") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the size of the pen/pencil") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.bgcolor") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the background color of the graphicswindow") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Clear") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will clear the project screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Window.Size") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the size of the project window") Sound.PlayClick() TextWindow.ForegroundColor = "red" TextWindow.WriteLine(" ") TextWindow.WriteLine("Text.Clear") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will clear the command screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Eraser") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen to an eraser") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.Pen") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen from eraser back to pen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.RBGColor") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the project screens background color to a random color") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you change the size of the project window") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size = Desktop") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will make the project window full screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Window.Size = Half") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the project window to half screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Paint.RPColor") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will change the pen to a random color") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.Color") TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you change the color of the text in the command screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Project.New") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will clear both the command screen and the project screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Commands.List") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will list all the commands and sub commands in the system") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Turtle.Move") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you draw lines with the turtle function") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Turtle.MoveTo") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you draw lines with the turtle using the X and Y axis") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Flickr.Random") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will choose a random picture from Flickr and set it for the background") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.BGColor") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the background color for the command screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Text.Name") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("Will let you choose the name of the command screen, the text on the top bar of the command screen") Sound.PlayClick() TextWindow.WriteLine(" ") TextWindow.ForegroundColor = "red" TextWindow.WriteLine("Project.Name") Sound.PlayClick() TextWindow.ForegroundColor = "gray" TextWindow.WriteLine("This will let you change the name of the project screen, the text on the top bar of the project screen") EndSub Sub TurtleM TextWindow.WriteLine("Pen up or Pen down?") RRR = TextWindow.Read() Sound.PlayClick() If(RRR = "up")Then Turtle.PenUp() Sound.PlayClick() TextWindow.WriteLine("Turtle.MoveTo X co's?") R = TextWindow.ReadNumber() Sound.PlayClick() TextWindow.WriteLine("Turtle.MoveTo Y co's") RR = TextWindow.ReadNumber() Turtle.MoveTo(R,RR) ElseIf(RRR = "down")Then Sound.PlayClick() TextWindow.WriteLine("What color?") L = TextWindow.Read() GraphicsWindow.PenColor = L Turtle.PenDown() Sound.PlayClick() TextWindow.WriteLine("Turtle.MoveTo X co's?") R = TextWindow.ReadNumber() Sound.PlayClick() TextWindow.WriteLine("Turtle.MoveTo Y co's") RR = TextWindow.ReadNumber() Turtle.MoveTo(R,RR) EndIf GraphicsWindow.PenColor = L GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub Sub Turtle Loop = 0 TextWindow.WriteLine("Which direction") RD = TextWindow.Read() Sound.PlayClick() TextWindow.WriteLine("How many degrees?") RTD = TextWindow.ReadNumber() Sound.PlayClick() TextWindow.WriteLine("Pen up or Pen down?") RUD = TextWindow.Read() Sound.PlayClick() TextWindow.WriteLine("How far?") RDD = TextWindow.ReadNumber() Sound.PlayClick() TextWindow.WriteLine("What color?") L = TextWindow.Read() GraphicsWindow.PenColor = L Sound.PlayClick() TextWindow.WriteLine("Loop how many times?") Looptime = TextWindow.ReadNumber() While(Loop<Looptime) Loop = Loop + 1 If(RUD = "up")Then Turtle.PenUp() ElseIf(RUD = "down")Then Turtle.PenDown() EndIf If(RD = "right")Then Turtle.TurnRight() Turtle.Move(RDD) ElseIf(RD = "left")Then Turtle.TurnLeft() Turtle.Move(RDD) EndIf If(RD = "angle")Then Turtle.Turn(RTD) Turtle.Move(RDD) EndIf EndWhile GraphicsWindow.PenColor = L GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub Sub Flickr TextWindow.WriteLine("Subject one?") RSO = TextWindow.Read() Sound.PlayClick() TextWindow.WriteLine("Subject two") RST = TextWindow.Read() Pic = Flickr.GetRandomPicture(RSO + RST) GraphicsWindow.DrawResizedImage(Pic,0,0,GraphicsWindow.Width,GraphicsWindow.Height) EndSub Sub TBGC TextWindow.WriteLine("Type text background color") RTBGC = TextWindow.Read() TextWindow.BackgroundColor = RTBGC TextWindow.Clear() EndSub Sub TWN TextWindow.WriteLine("New Name?") RNN = TextWindow.Read() TextWindow.Title = RNN Endsub Sub PaintN TextWindow.WriteLine("New project name?") RNPN = TextWindow.Read() GraphicsWindow.Title = RNPN EndSub Sub PPEN GraphicsWindow.PenColor = "black" GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = Black") EndSub Sub TurtleH Turtle.Hide() EndSub Sub Turtlerect TextWindow.WriteLine("X co's") RectX = TextWindow.ReadNumber() TextWindow.WriteLine("Y co's?") RectY = TextWindow.ReadNumber() TextWindow.WriteLine("Height?") RectHe = TextWindow.ReadNumber() TextWindow.WriteLine("Width") RectWi = TextWindow.ReadNumber() TextWindow.WriteLine("Color") L = TextWindow.Read() GraphicsWindow.PenColor = L Turtle.PenUp() Turtle.MoveTo(RectX,RectY) Turtle.PenDown() Turtle.Move(RectHe) Turtle.TurnRight() Turtle.Move(RectWi) Turtle.TurnRight() Turtle.Move(RectHe) Turtle.TurnRight() Turtle.Move(RectWi) GraphicsWindow.PenColor = L GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub Sub Star TextWindow.Write("Enter the number of points (odd numbers only):") points = TextWindow.ReadNumber() If Math.Remainder(points,2) = 1 then angle = 180-(360/points/2) TextWindow.Write("Enter the color:") GraphicsWindow.PenColor = TextWindow.Read() TextWindow.Write("Enter the X coordinate of the stars center:") x = TextWindow.ReadNumber() TextWindow.Write("Enter the Y coordinate of the stars center:") y = TextWindow.ReadNumber() Turtle.PenUp() Turtle.MoveTo(x,y) Turtle.PenDown() Turtle.Speed = 10 side = 0 For i = 1 To 100 Turtle.Move(side) Turtle.Turn(angle) side = side + 1 EndFor Turtle.Speed = 1 Else TextWindow.Write("Invalid Number") EndIf GraphicsWindow.PenColor = L GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300,12) GraphicsWindow.BrushColor = L GraphicsWindow.DrawBoundText(GraphicsWindow.Width-GraphicsWindow.Width+10,GraphicsWindow.Height-50,300, "Pen.Color = " + L) EndSub - A paint program created in small basic using Fremy's extention.
'_____________________ 'Paint program V1 'Author Dratii 'Made with Fremy's extention '_____________________ 'Variables set = 0 Erase = 0 Pen = "black" Helptext = "Welcome." Helptext2 = "The buttons are for using the functions." Helptext3 = "For some functions pressing the button again will disable the function." Helptext4 = "The lables above the buttons show the current colour, size, and tool." Helptext5 = "The 'Eraser' button removes parts of the drawing." Helptext6 = "The 'Clear' button clears the drawing area." Helptext7 = "The 'Line' button draw straight lines." Helptext8 = "The 'Colour' button changes the pen colour." Helptext9 = "And the '+ and -' buttons change the pensize." GraphicsWindow.MouseDown = OnMouseDown GraphicsWindow.BackgroundColor = "White" GraphicsWindow.PenWidth = 1 GraphicsWindow.Width = 715 GraphicsWindow.Height = 530 GraphicsWindow.MouseMove = OnMouseMove GraphicsWindow.Title = "Paint Program" GraphicsWindow.CanResize = "no" Pen = "black" Pwidth = 3 buttons() 'creates the buttons 'Colour function Sub Clicker Pen = Dialogs.AskForColor() If(Pen<>"")then Erase = 0 GraphicsWindow.PenColor = Pen GraphicsWindow.BrushColor = Pen Pen2 = Pen If(Currenttool = "Eraser")then 'Redraws the lable Pen2 = Pen Controls.Remove(Currenttool) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Pen") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = "black" GraphicsWindow.BrushColor = Pen Pen2 = Pen endif endif 'Redraws the lable Controls.Remove(CurrentColour) CurrentColour = Controls.AddRectangle(10, 10) Controls.Move(CurrentColour, 74, 478) endsub 'Help Function Sub Clicker2 GraphicsWindow.ShowMessage(Helptext, "Help") GraphicsWindow.ShowMessage(Helptext2, "Help") GraphicsWindow.ShowMessage(Helptext3, "Help") GraphicsWindow.ShowMessage(Helptext4, "Help") GraphicsWindow.ShowMessage(Helptext5, "Help") GraphicsWindow.ShowMessage(Helptext6, "Help") GraphicsWindow.ShowMessage(Helptext7, "Help") GraphicsWindow.ShowMessage(Helptext8, "Help") GraphicsWindow.ShowMessage(Helptext9, "Help") endsub 'Eraser Function Sub Clicker8 If(Erase = 0)Then GraphicsWindow.PenColor = "white" Pen2 = Pen Pen = "white" 'Redraws the lable Controls.Remove(Currenttool) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Eraser") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = "black" Erase = 1 set = 0 Else Erase = 0 GraphicsWindow.PenColor = Pen2 Pen = Pen2 'Redraws the lable Controls.Remove(Currenttool) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Pen") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = "black" endif endsub 'Clear Function Sub Clicker9 GraphicsWindow.BrushColor = "white" GraphicsWindow.FillRectangle(0, 0, 725, 600) endsub 'Size Functions Sub Clicker10 If(Pwidth < 10)then Pwidth = Pwidth + 1 endif Repen() endsub Sub Clicker11 If(Pwidth > 1)then Pwidth = Pwidth - 1 endif Repen() endsub 'Line Function Sub Clicker12 If(set = 1)or(set = 2)then set = 0 'Redraws the lable Controls.Remove(Currenttool) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Pen") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = "black" Erase = 0 else set = 1 Pen = Pen2 GraphicsWindow.PenColor = Pen 'Redraws the lable Controls.Remove(Currenttool) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Line") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = Pen Erase = 0 EndIf endsub sub Repen GraphicsWindow.PenWidth = Pwidth 'Redraws the lable Controls.Remove(CurrentSize) GraphicsWindow.BrushColor = "red" CurrentSize = Controls.AddLabel(30, 25, Pwidth) Controls.Move(CurrentSize, 170, 470) GraphicsWindow.BrushColor = Pen endsub Sub buttons Controls.LoadTheme("XPBlue") GraphicsWindow.PenWidth = 1 GraphicsWindow.BrushColor="#E6F5FD" GraphicsWindow.PenColor="#B2DFF8" Rect1 = Controls.AddRectangle(800, 80) Controls.Move(Rect1, 0, 460) GraphicsWindow.PenWidth = Pwidth GraphicsWindow.PenColor=Pen GraphicsWindow.PenColor = "black" GraphicsWindow.BrushColor = "black" 'Lables Lable = Controls.AddLabel(120, 25, "Colour") Controls.Move(Lable, 20, 470) CurrentColour = Controls.AddRectangle(10, 10) Controls.Move(CurrentColour, 74, 478) Lable2 = Controls.AddLabel(120, 25, "Pen Size") Controls.Move(Lable2, 110, 470) GraphicsWindow.BrushColor = "red" CurrentSize = Controls.AddLabel(30, 25, "3") Controls.Move(CurrentSize, 170, 470) GraphicsWindow.BrushColor = "black" Lable3 = Controls.AddLabel(120, 25, "Tool") Controls.Move(Lable3, 200, 470) GraphicsWindow.BrushColor = "red" Currenttool = Controls.AddLabel(120, 25, "Pen") Controls.Move(Currenttool, 237, 470) GraphicsWindow.BrushColor = "black" 'buttons Button = Controls.AddButton(80, 25, "Colour") Controls.Move(Button, 420, 500) Controls.RegisterMouseDownEvent(Button, "Clicker") Button8 = Controls.AddButton(80, 25, "Eraser") Controls.Move(Button8, 20, 500) Controls.RegisterMouseDownEvent(Button8, "Clicker8") Button9 = Controls.AddButton(80, 25, "Clear") Controls.Move(Button9, 120, 500) Controls.RegisterMouseDownEvent(Button9, "Clicker9") Button10 = Controls.AddButton(80, 25, "+") Controls.Move(Button10, 520, 500) Controls.RegisterMouseDownEvent(Button10, "Clicker10") Button11 = Controls.AddButton(80, 25, "-") Controls.Move(Button11, 620, 500) Controls.RegisterMouseDownEvent(Button11, "Clicker11") Button12 = Controls.AddButton(80, 25, "Line") Controls.Move(Button12, 320, 500) Controls.RegisterMouseDownEvent(Button12, "Clicker12") Button2 = Controls.AddButton(80, 25, "Help") Controls.Move(Button2, 220, 500) Controls.RegisterMouseDownEvent(Button2, "Clicker2") endsub Sub Line If(set = 2)then GraphicsWindow.PenColor = Pen GraphicsWindow.BrushColor = Pen GraphicsWindow.DrawLine(NewX, NewY, oldX, oldY) set = 1 endif oldX = GraphicsWindow.MouseX oldY = GraphicsWindow.MouseY If(set = 1)then Mousedown2() endif endsub 'The pen Sub Mousedown2 NewX= GraphicsWindow.MouseX NewY = GraphicsWindow.MouseY GraphicsWindow.SetPixel(NewX, NewY, Pen) set = 2 endsub Sub OnMouseDown If(set <> 0)then Line() endif oldX = GraphicsWindow.MouseX oldY = GraphicsWindow.MouseY EndSub Sub OnMouseMove x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY If (Mouse.IsLeftButtonDown)And(set = 0) then GraphicsWindow.DrawLine(oldX, oldY, x, y) endif If(Mouse.IsLeftButtonDown)And(set = 0)And(Pwidth > 3) then GraphicsWindow.SetPixel(x, y, Pen) GraphicsWindow.SetPixel(x +1, y +1, Pen) GraphicsWindow.SetPixel(x -1, y -1, Pen) GraphicsWindow.SetPixel(x +2, y +2, Pen) GraphicsWindow.DrawLine(oldX + 2, oldY + 2, x + 2, y + 2) endif oldX = x oldY = y EndSub A paint program created in small basic using Fremy's extention.
Looks very great ! The UI is beautiful to see.
Maybe you can useControls.SetTextinstead of removing old labels and adding new ones, but for the rest, it seems great. Idem for the color preview (you can useControls.SetBackground). Hum, just another small remark. The first time I clicked on the 'Line' button, I didn't find how to get the 'Pen' mode ack. Maybe you should useControls.SetTexttoo to change the caption of the button in 'Pen' when the mode is 'Line', and 'Line' when the mode is 'Pen'.
Now, if you want some challenge to make the program even better, you could add the possibilities to draw rectangle or circles ;)
Behalve the few remarks, it is good written. You take advantage of subs and made good use of comments. It's pleasant to look at your code. Keep programming like that.
Fremy - Developer in VB.NET, C# and JScript ... - Feel free to try my extension- Fun little ball bounce program.
'Define a circle, it's size, position and speed
circleRadius = 50
xPosition = circleRadius
yPosition = circleRadius
xSpeed = 50
ySpeed = 0
'Set up a timer to tick once for every frame of animation
Timer.Interval = 33 '33 = 30 frames per second
Timer.Tick = onTimerTick
'Set up events so you can drag the ball around
GraphicsWindow.MouseMove = onMouseMove
GraphicsWindow.MouseDown = onMouseDown
'Put a suiting title on the window
GraphicsWindow.Title = "Ball Bounce Example - Drag and Release to 'Throw' the ball"
'--------------------------------------------------------------------------------------------------------------
'onTimerTick - This is what happens every frame
'--------------------------------------------------------------------------------------------------------------
Sub onTimerTick
'Call the subroutine that updates the ball for this frame
Update()
'Now Draw the frame
Redraw()
EndSub
'--------------------------------------------------------------------------------------------------------------
'Update - Updates everything to the next frame of animation
'--------------------------------------------------------------------------------------------------------------
Sub Update
'Move the position of the ball by it's speed
'-------------------------------------------------
xPosition = xPosition + xSpeed
yPosition = yPosition + ySpeed
'Check for a bounce against any of the 4 sides of the window
'-----------------------------------------------------------------------
'first figure out where the sides are
rightSide = GraphicsWindow.Width - circleRadius
leftSide = circleRadius
bottomSide = GraphicsWindow.Height - circleRadius
topSide = circleRadius
'then bounce if we need to
If xPosition > rightSide then 'right side
xPosition = rightSide - circleRadius
xSpeed = -xSpeed
EndIf
If xPosition < leftSide then 'left side
xPosition = leftSide
xSpeed = -xSpeed
EndIf
If yPosition > bottomSide then 'bottom
yPosition = bottomSide
ySpeed = -ySpeed
EndIf
If yPosition < topSide then 'top
yPosition = topSide
ySpeed = -ySpeed
EndIf
'Gravity (increases the speed in the down direction to make it fall)
'-------------------------------------------------------------------------------
ySpeed = ySpeed + 2
'Friction (make the overall speed 95% of it's current speed)
'---------------------------------------------------------------------
xSpeed = xSpeed * .95
ySpeed = ySpeed * .95
'Hooking - Advanced Friction (when the ball has so little energy it gets "caught" and can no longer move)
'-----------------------------------------------------------------------------------------------------------------------------
If Math.Abs(xSpeed) < .1 then 'Math.Abs() is a simple math function to make negative numbers positive
xSpeed = 0 'we're checking to see if the movement ( backwards (negative) or forward (positive) )
EndIf 'is less than .1. If it is, just stop the movement all together.
If Math.Abs(ySpeed) < .1 then
ySpeed = 0
EndIf
EndSub
'--------------------------------------------------------------------------------------------------------------
'Redraw - Clears the GraphicsWindow and Draws the Ball
'--------------------------------------------------------------------------------------------------------------
Sub Redraw
GraphicsWindow.Clear()
'Draw the ball - centering it on the xPosition/yPosition
circleSize = circleRadius * 2
GraphicsWindow.DrawEllipse(xPosition-circleRadius, yPosition-circleRadius, circleSize, circleSize)
EndSub
'--------------------------------------------------------------------------------------------------------------
'onMouseDown - The mouse button was pressed
'--------------------------------------------------------------------------------------------------------------
Sub onMouseDown
'save the position of the mouse in variables
xOld = GraphicsWindow.MouseX
yOld = GraphicsWindow.MouseY
'move the ball to where the mouse is
xPosition = xOld
yPosition = yOld
EndSub
'--------------------------------------------------------------------------------------------------------------
'onMouseMove - The mouse was moved
'--------------------------------------------------------------------------------------------------------------
Sub onMouseMove
'see if the button is down. If it is, then we're dragging the ball
If Mouse.IsLeftButtonDown Then
'save the position of the mouse in variables
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
'find out how far the mouse moved since the last time we we're here
'this will be the new speed of the ball
xSpeed = x - xOld
ySpeed = y - yOld
'move the ball to where the mouse is
xPosition = x
yPosition = y
'this mouse position is old, save where it is so we can figure out
'the speed next time we're here
xOld = x
yOld = y
EndIf
EndSub
Toefist Productions LLC, Minnetonka, MN - Hello TheToefistJU,
I like your use of physics to make a realistic animation. I feel you could improve on it though if you used Shapes rather than GraphicsWindow.DrawEllipse(). With Shapes you can Move or Animate to a new position without having to erase the old position. This would allow you to add a background that wouldn't get corrupted when the ball moved over it.
I have made slight modifications to your program to illustrate what I mean. I have added a Shapes ball that is Moved to the new position. I have left the original but removed the GraphicsWindow.Clear(). This leaves a trail of the ball position. Notice how the solid ball does not erase the trail as it moves over it.
By the way; if you use Import and Publish (especially for larger files) it helps to follow a thread without a lot of scrolling.
Import HNQ963- 已編輯Stendec解答者Sunday, 26 April, 2009 19:17
By the way; if you use Import and Publish (especially for larger files) it helps to follow a thread without a lot of scrolling.
Pictures are nice too.Surprised someone has not already posted this but how about some classic Snake action?
Code can be imported using the ID WMX007 or seen here: http://smallbasic.com/program/?WMX007
Instructions: Avoid the walls and yourself while eating as many food items as possible and growing in length. Movement is controlled using the left and right arrow keys. Turns are relative to your current direction.
I've tried to keep the code quite clean and flexible, but the game could be improved with the addition of multiple concurrent food items or maybe even walls! Comments welcome.
With regard to Small Basic itself, I'd welcome the ability to set the location of a shape when creating it, unless I am just being blind and missed it! My implementation sometimes flickers snake segments or food items in the top, left corner as they are created before being moved to their correct location.
As an off-topic aside I definitely think the publish button should have a confirmation dialogue box - somethings just shouldn't be published!
Thanks for the consideration, hope it's mildly enjoyable!
Jason.- 已編輯Jason Jacques Sunday, 3 May, 2009 23:11Forgot to include instructions!
- OK, so I realise now that Snake is already a featured example for Small Basic (though unfortunately the featured code doesn't work correctly in v0.4 and I was unable to determine why) - that's what happens when you don't check the second page of the blog!So instead, sticking with the theme of classic games, for your consideration: Asteroids.Code can be imported using the ID QFL408 or seen here: http://smallbasic.com/program/?QFL408Instructions: Destroy all the asteroids, by shooting them, avoiding getting hit yourself. Left and right arrows keys to rotate, forward and backwards arrow keys to adjust ship speed. Space bar to fire. P key to pause/resume.I'm sure the game could benefit from the addition of de-facto standard three lives, some more interesting graphics and maybe even aliens.As before, comments welcome!Again, thanks for the consideration and I hope you enjoy!Jason.
- 已編輯Jason Jacques Friday, 8 May, 2009 19:10Made link clickable.
- Very impressive Asteroids game Jason Jacques. Great job!
I've modified Jason's Asteroids to include images. The new variant can be downloaded as: QFL408-0

- Hi Im new to small basic but have been programming in VB.net for a while I have created a paint like program that can draw staright lines There are four colours to choose from. If you want the code type SBV954 into import.
(Could someon tell me how to upload a photo because I would like to include a screen shot thank you)
- Posting a screen shot
You must upload your image to a third party site (Flicker, your own personal website or some other site), then edit the HTML of your post to include the picture.
<img alt="" src="http://farm4.static.flickr.com/3044/3102500861_398a6a988f.jpg?v=0" /> - Excellent game - nice work Jason!
I altered it slightly to handle the auto-repeat and auto-delay introduced by my OS for key presses that gives some jerky rotations. Also each 'fire' requires a separate press of the space bar with these mods.
QFL408-3 - For the game, maybe we need a maxUserSpeed, because we can go faster than the light, currently :)
It's fun, but only because you can shot all asteroids but one, go the the ligth speed, and wait until the asteroid hit you.
Also, it would be great to have a point lost each time we fire. So, it would be more time-rapporting to shot with precision than with mass.
Fremy - Developer in VB.NET, C# and JScript ... - Feel free to try my extension - It's great to see how into my game everyone is and I'm glad it hasn't been too difficult for you to achieve your modifications - feel free to keep hacking at it!I did notice the issue with the maximum speed, but I was never very good at asteroids so always took it slow - seems not everyone feels the same way! I've updated litdev's modifications with a maximum speed parameter (maxSpeed, found in the player setting sections) and added inertia as would have been found in the original game - you can disable it by setting it to zero if you'd rather not slow down.During development I actually considered taking a point off for each shot, but dismissed it. However, your point about accuracy is well heeded (I like to spin and fire every second or so...) so I've updated the code appropriately. I've also done some general tidying of the code for example removing the now superfluous player and rock colours.Get the new code using the ID QFL408-4 or view online here: http://smallbasic.com/program/?QFL408-4Thanks for your input.Jason.
- QFL408-4 is now promoted to ASTEROIDS. You can import this version using the id: ASTEROIDS
QuickBasic had Gorillas and now Small Basic does too!
Image, Sound, Exe and Source files can be downloaded here
http://code.msdn.microsoft.com/SmallBasicGorillasI made a 21/Black Jack in the textwindow. I'm going to make it in the graphics window soon and will also add betting. I am also working on five card draw and texas hold'em.
Import Code: NFB246There might still be a few bugs, so let me know if you find one.
- I'm sorry, but I just had to correct your instructions. If you wish to use it, import NFB246-0.
In the version of the game that I know you can only have a maximum of five cards. you would also need to check for this. - I have made a minesweeper game in Small Basic.It is very basic. (Pun not intended)Basically all it is missing out on is fancy graphics and the auto thingy. (will explain later)The import code is: WGT176It works the same as the windows minesweeper.Except, when it is a blank square it doesn't auto click all the squares around it.I wasn't sure how to add that feature due to the restrictions in sub routines.If anyone could point me into the right direction or anything for that, that would be nice.It also allows you to change the color schemes and enter cheats. (For debugging purposes)Feedback would be nice~-Simon


