DevLabs >
DevLabs Forums
>
Small Basic
>
Post your sample source code here and get featured on our blogs!
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
All Replies
- 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 - Edited byGeorge BirbilisMVPFriday, October 24, 2008 9:31 PMremoved 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- Edited byVijaye RajiMSFT, OwnerSaturday, November 01, 2008 7:49 PMadded 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()
- Edited bydanteembermage Saturday, October 25, 2008 2:19 PMforgot 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()
- Edited bycarolingian Sunday, October 26, 2008 1:10 AM
' -------------------------------------------------------------------------------- ' 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!
- Edited byChristian Jacob Sunday, October 26, 2008 3:39 PMAdded suggestions
- Edited byChristian Jacob Sunday, October 26, 2008 3:08 PMAdded screenshot
- Edited byChristian Jacob Sunday, October 26, 2008 3:27 PMMinor 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
- Edited bysoloman817 Wednesday, October 29, 2008 8:31 PM
- Edited bysoloman817 Wednesday, October 29, 2008 8:32 PM
- 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
- Edited bycarolingian Sunday, November 02, 2008 3:13 AM
- Edited bycarolingian Sunday, November 02, 2008 2:50 AM
- 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- Edited byGeorge BirbilisMVPMonday, November 03, 2008 4:44 PM
- 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 :-)
- Edited byJeff Sidlosky Sunday, November 09, 2008 12:33 AM
- Edited byJeff Sidlosky Sunday, November 09, 2008 12:39 AM
- Edited byJeff Sidlosky Sunday, November 09, 2008 12:37 AM
- 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() - Edited byRichard Gautier Sunday, November 09, 2008 3:54 AM
- 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 - Edited byxhable Sunday, November 09, 2008 11:33 AMTook 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- Edited byGeorge BirbilisMVPMonday, November 10, 2008 10:05 AM
- 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- Edited byGeorge BirbilisMVPMonday, November 10, 2008 10:09 AM
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?- Edited byB0ff1n Tuesday, November 11, 2008 4:03 PM
- 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 - Edited byVijaye RajiMSFT, OwnerThursday, November 27, 2008 12:17 AMFixed some typos
- Edited byPath_drc Monday, December 01, 2008 5:58 PMedited 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.- Edited byPath_drc Thursday, November 27, 2008 6:55 PMcorrect 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


