# Challenge of the Month - September 2012

### General discussion

• Welcome to the monthly SmallBasic Challenge!

These challenges are intended for people who are learning to program for the first time or for those returning to programming who want to start using SmallBasic.  Some will be easy, some will be hard - but they will all make you think, and more importantly be GREAT FUN!

Please post your solutions / partial solutions / questions / feedback etc. into this thread that will remain 'sticky' for the month.  The only rule is that your solution must use standard SmallBasic methods (no extensions).

It would be good if people could post their problems with these challenges so that a discussion can start so that everyone can learn from each other.

Also post feedback on the kind of challenges that you want to see more of in the future.

Basic Challenge 1

Detect any numbers in an input text, for example:

"There are 7 days in a week, 52 weeks in a year, and on average 365.25 days in a year."

Basic Challenge 2

Enter a number and detect if it is odd or even.

Basic Challenge 3

Create program to show 4 pictures downloaded from Flikr in a 2 by 2 grid on the GraphicsWindow.

Basic Challenge 4

Calculate the sum of all integer numbers under 1000 that contain a 3.

Basic Challenge 5

Write the times tables (1 to 12).

Hint: Check out 'TextWindow.CursorLeft' to format it.

Physics Challenge

Create a program to simulate waves.  Quite a general challenge so tackle it how you want - could be a water wave (2D) or a wave along a string (1D).

Maths Challenge 1

Convert an input decimal number to a binary number.

Maths Challenge 2

pi is an irrational number - it cannot be expressed exactly as one integer divided by another (a rational number).  It can however be approximated in this way, for example 22/7 is a good approximation.

The challenge is to find other better rational number (one integer divided by another) approximations to pi.

Maths Challenge 3

Create a program to calculate and plot a Lorentz Strange Attractor (details here).

Graphics Challenge 1

Write a program that types to the GraphicsWindow as you type.

Graphical Challenge 2

Create a 'frogger' game, an example here.

Graphical Challenge 3

Create a graphical tax calculator program.  Assume the following:

• No tax charged on the first 8k (8000).
• 20% tax up to a gross income of 40k (only paid on income above 8k).
• 40% tax up to a gross income of 150k (paid on income between 40k and 150k).
• 50% tax on a gross income over 150k (paid on income over 150k).

Do you have an idea for a future challenge? Please post it here!

Friday, August 31, 2012 7:03 PM

### All replies

• I am gonna get back in the game and tackle Basic Challenge #2.

Also, LitDev, you have a numerical error in Basic Challenge 1. There are approx. 365.25 days a year, not 356.25! Just thought I'd point it out!

'A computer without code is like a car without gasoline.' 'Just as gasoline needs a pump to get it into the car, code needs a person to enter it into a computer... That makes me feel important!'

Friday, August 31, 2012 7:24 PM
• Thanks, I also just spotted that - edited.
Friday, August 31, 2012 7:27 PM
• Basic Challenge 2

Random Number:

http://smallbasic.com/program/?DZJ889

Or User Defined Number:

http://smallbasic.com/program/?FKL590

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Friday, August 31, 2012 7:46 PM
• Good answer and very quick.
Friday, August 31, 2012 7:55 PM
• Thanks!

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Friday, August 31, 2012 7:57 PM
• I have gotten this far, but when I click the button, it always says "It is Even!" even if the number is supposed to be odd.

GraphicsWindow.Title = "Is your number Even or Odd?"
GraphicsWindow.CanResize = "False"
GraphicsWindow.Height = 300
GraphicsWindow.Width = 300
GraphicsWindow.Top = (Desktop.Height - 300)/2
GraphicsWindow.Left = (Desktop.Width - 300)/2

GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.DrawText(70, 0, "Enter Your Number Below")
UsersNumber = Controls.GetTextBoxText(NumberBox)

Controls.ButtonClicked = OnButtonClicked
Sub OnButtonClicked
buttonClicked = Controls.LastClickedButton
EvenOrOdd = Math.Remainder(UsersNumber, 2)
If EvenOrOdd > 0 Or EvenOrOdd < 0 Then
GraphicsWindow.DrawText(125, 150, "It is odd!")
ElseIf EvenOrOdd = 0 Then
GraphicsWindow.DrawText(125, 150, "It is Even!")
EndIf
EndSub

Is it the Math.Remainder set? Or does it have something to do with my button?

'A computer without code is like a car without gasoline.' 'Just as gasoline needs a pump to get it into the car, code needs a person to enter it into a computer... That makes me feel important!'

• Edited by Friday, August 31, 2012 8:22 PM Typo (Oops!)
Friday, August 31, 2012 8:21 PM
• A good interface using events.

A couple of points:

1] Is UsersNumber updated when the button is clicked?

2] Also check the logic of 'If EvenOrOdd > 0 Or EvenOrOdd < 0 Then'  - can EvenOrOdd ever be negative?

3] If you get a different answer (odd or even), then GraphicsWindow.DrawText will overwrite the last answer so its hard to read.

Friday, August 31, 2012 8:31 PM
• Check out my code (VERY simple):

```TextWindow.WriteLine("Please Enter a Number:")
TextWindow.WriteLine(number)
check = Math.Remainder(number, 2)
If check < 0 or check > 0 then
TextWindow.WriteLine("The number is odd.")
ElseIf check = 0 then
TextWindow.WriteLine("The number is even.")
EndIf
TextWindow.WriteLine("----------")```

Please let me know if you need any more help! :)

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Friday, August 31, 2012 8:33 PM
• Basic Challenge 4

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Friday, August 31, 2012 9:22 PM
• Hello ev'ry1! Here's my 1st participation in the 'Challenge of the Month'!!!

By default it is a 2x2 grid, but any dimension is posible by altering tags[] row elements.  ;-)

Import code -> CZH557-1     <--- not working on Silverlight!

Basic Challenge 3 - Flickr in a Grid:

`'################''Flickr in a Grid (v1.1)'Basic Challenge 3'Sep/2012'by GoToLoop'################''CZH557-1'http://social.msdn.microsoft.com/Forums/en-US/smallbasic'/thread/88d814da-7691-4103-9785-6886f5cb9105'________________________________________________________________________________________'GraphicsWindow.Left   = 0GraphicsWindow.Height = 0GraphicsWindow.Width  = 1400GraphicsWindow.Height = 900InitVars()GraphicsWindow.BackgroundColor = "Black"GraphicsWindow.KeyDown = KeyPressed'________________________________________________________________________________________'Loop:GetPics()noKey = "True"While noKey  Program.Delay(200)EndWhileGoto Loop'________________________________________________________________________________________'Sub InitVars    tags[1] = "1=VideoGames;2=Programming;"   ' <--- row #1  tags[2] = "1=Computers;2=MMORPG;"         ' <--- row #2    tagsCols = Array.GetItemCount(tags[1])  tagsRows = Array.GetItemCount(tags)    gw = GraphicsWindow.Width  gh = GraphicsWindow.Height    gwGrid = gw / tagsCols  ghGrid = gh / tagsRows    elements = tagsCols * tagsRows    msg = "Loading Flickr Image:   ("  EndSub'________________________________________________________________________________________'Sub GetPics    For tRow=1 To tagsRows    For tCol=1 To tagsCols            tag = tags[tRow][tCol]      pos = tagsCols*(tRow-1) + tCol            GraphicsWindow.Title =  msg + pos + "/" + elements + ")   [" + tag + "]   ..."            img = Flickr.GetRandomPicture(tag)            GraphicsWindow.DrawResizedImage(img  gwGrid*(tCol-1),ghGrid*(tRow-1)  gwGrid,ghGrid)            Sound.PlayChime()          EndFor  EndFor    GraphicsWindow.Title = "Flickr in a Grid"  EndSub'________________________________________________________________________________________'Sub KeyPressed    noKey = "False"  Sound.PlayClick()    If GraphicsWindow.LastKey = "Escape" Then    Program.End()  EndIf  EndSub'________________________________________________________________________________________'`

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

• Edited by Friday, August 31, 2012 11:09 PM Newer Simpler Version
Friday, August 31, 2012 9:34 PM
• LitDev, could you please elaborate on "Is UsersNumber updated when the button is clicked?" Like how should it be updated?

When I tested Noah's textwindow version with user input, the number, or variable, can be negative, and shows in his source code.

I also realized that it would be hard to read after one try and am working on getting it to clear it after each use.

'A computer without code is like a car without gasoline.' 'Just as gasoline needs a pump to get it into the car, code needs a person to enter it into a computer... That makes me feel important!'

• Edited by Friday, August 31, 2012 10:56 PM because I wanted to add something to make my question a tad clearer.
Friday, August 31, 2012 10:36 PM
• 2nd one! :D

Import code -> MFC568

Graphics Challenge 1 - Type & Tell: <--- Misbehaves on Silverlight when using special keys!

```'################'
'Type & Tell (v1.0)
'Graphics Challenge 1
'Sep/2012
'by GoToLoop
'################'

'_____________________________________________________________________________'
BS  = Text.GetCharacter( 8) ' Backspace
ESC = Text.GetCharacter(27) ' Escape Key

Tell()

GraphicsWindow.Title = "Type & Tell"
GraphicsWindow.BackgroundColor = "Black"GraphicsWindow.TextInput = Type
'_____________________________________________________________________________'
Sub Tell

GraphicsWindow.BrushColor = "Yellow"
GraphicsWindow.FontBold = "True"
GraphicsWindow.FontSize = 16

text = ""

EndSub
'_____________________________________________________________________________'
Sub Type

type = GraphicsWindow.LastText

Sound.PlayClick()

If type = ESC Then
Program.End()
ElseIf type = BS Then
If text <> "" Then
text = Text.GetSubText( text  1,Text.GetLength(text) - 1 )
EndIf
Else
text = text + type
EndIf

Shapes.SetText(tell,text)

EndSub
'_____________________________________________________________________________'```

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Saturday, September 01, 2012 1:52 AM
• Basic Challenge 4:  (Calculate the sum of all integer numbers under 1000 that contain a 3)

121878

```For number=1 To 1000
If Text.IsSubText(number,3) Then
sum = sum + number
EndIf
EndFor

TextWindow.WriteLine(sum)```

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Saturday, September 01, 2012 2:33 AM
• Once more!

Maths Challenge 1:  (Convert an input decimal number to a binary number)

```TextWindow.ForegroundColor = "Red"
TextWindow.WriteLine("Enter number to convert to binary base:")

Convert:

TextWindow.ForegroundColor = "Green"
TextWindow.WriteLine("")
number = Math.Floor( Math.Abs ( TextWindow.ReadNumber() ) )

While number > 0
Stack.PushValue("Bin"  Math.Remainder( number,2 ) )
number = Math.Floor( number / 2 )
EndWhile

bin = ""

While Stack.GetCount("Bin") > 0
bin = Text.Append( bin  Stack.PopValue("Bin") )
EndWhile

TextWindow.ForegroundColor = "Yellow"
TextWindow.WriteLine(bin * 1)

Goto Convert```

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Saturday, September 01, 2012 3:03 AM
• Great program! I just could not seem how to do one digit and move onto the next, but stack seems to work great!

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Saturday, September 01, 2012 3:32 AM
• Nice you liked it, Noah Buscher!

But 1st, sorry I haven't paid attention you already had coded Basic Challenge 4 before doing the same!   *_*

Nevertheless, yours got a bug!

Total = Total + curNum oughta be placed inside the If condition scope likewise my sum = sum + number!  @_@

Anyways, to match the dec -> bin convertor, here's the bin -> dec one, featuring the Stack class as well:      ^_^

```SpecialCharsHeader()

TextWindow.ForegroundColor = "Red"
TextWindow.WriteLine("Enter binary to get back to decimal base:" + LF)

Convert:

TextWindow.ForegroundColor = "Green"
BinInput()

For digit=1 To binLen
Stack.PushValue( "Inv"  Text.GetSubText(bin  digit,1) )
EndFor

stackCount = Stack.GetCount("Inv") - 1
dec = ""

For exp=0 To stackCount
dec = dec + Stack.PopValue("Inv") * Math.Power(2,exp)
EndFor

TextWindow.ForegroundColor = "Yellow"
TextWindow.WriteLine(LF + dec*1 + LF)

Goto Convert

Sub BinInput

bin = ""
key = ""

While key <> CR

binLen = Text.GetLength(bin)

If key = ESC Then
Program.End()
ElseIf key = BS Then
If bin <> "" Then
bin = Text.GetSubText( bin  1, binLen-1 )
Sound.PlayChime()
TextWindow.Write(BS + SPC + BS)
EndIf
ElseIf (key = 0 Or key = 1) And binLen < 79 Then
bin = Text.Append( bin,key )
Sound.PlayClick()
TextWindow.Write(key)
Else
Sound.PlayBellRing()
EndIf

EndWhile

bin = Math.Abs(bin)  ' <--- removes useless zeros on the left  EndSub

BS  = Text.GetCharacter( 8) ' Backspace
TAB = Text.GetCharacter( 9) ' Horizontal Tabulation (HT)
LF  = Text.GetCharacter(10) ' Line-Feed (jumps a line)
CR  = Text.GetCharacter(13) ' Carriage Return
ESC = Text.GetCharacter(27) ' Escape Key
SPC = " "                   ' SPaCe

EndSub```

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Saturday, September 01, 2012 6:59 AM
• 1] The Math.Remainder doesn't ever create a negative answer, even if the input is negative, so both yours and Noah.s don't need this check.

2] When the button is pressed, the event subroutine is called, but UserNumber is not then recalculated so its value doesn't change, put the calculation inside the event subroutine.

Saturday, September 01, 2012 7:25 AM
• Noah, is the this the sum of all numbers below 1000 or just those with a 3 in?
Saturday, September 01, 2012 7:27 AM
• The Math.Remainder(number,2) can only be 0 or 1 , so you have only to check one of the possibilities e.g. if =1 then odd, else even.

Jan [ WhTurner ] The Netherlands

Saturday, September 01, 2012 11:06 AM
• I think with the number 3, but I got a very high number.

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Saturday, September 01, 2012 1:20 PM
• It is the total of all numbers, to just get those with a 3 in, you need to update the total only if a 3 is present - move this inside the if:

```  If search = "True" Then
TextWindow.WriteLine(curNum)
EndIf
Total = Total + curNum
```

To

```  If search = "True" Then
TextWindow.WriteLine(curNum)
Total = Total + curNum
EndIf
```

Saturday, September 01, 2012 1:31 PM
• Oh thanks! Didn't even catch that! :)

-Noah J. Buscher "Nothing is Impossible Until Proven Impossible."

Saturday, September 01, 2012 1:35 PM
• A little tricky Basic Challenge 2 :

```TextWindow.Write("Number ")

Nonki Takahashi

Sunday, September 02, 2012 10:55 AM
• Physics Challenge     waves.  KBL066

Tuesday, September 04, 2012 1:37 AM
• nice wave!
Tuesday, September 04, 2012 8:29 PM
• I'm gonna try to tackle the graphics challenge 2

One thing that is impossible is impossible no matter if it is proven so first.

Tuesday, September 04, 2012 8:50 PM
• Basic challange 2

TextWindow.Write("Enter a number: ")
If Math.Remainder(Num,2) = 0 Then
TextWindow.WriteLine("The number is Even")
Else
TextWindow.WriteLine("The Number is odd")
EndIf

One thing that is impossible is impossible no matter if it is proven so first.

Tuesday, September 04, 2012 8:54 PM
• Maths Challenge 2     PI  Value      RPG714-0

Note :  In case of Power N=3 and N=4 , both results will be  same .

(Because 3195/355=  1017/113=9   These are the values ​​that were nine times. )

Wednesday, September 05, 2012 12:44 AM
• Basic challenge 5 with challenge 2 incorporated for the colors, ZMR377

Wednesday, September 05, 2012 3:05 AM
• NaochanON and JKrueg - another 2 good answers.
Wednesday, September 05, 2012 7:06 PM
• Went after another one, here's the physics challenge, KVZ619. Tap the arrow keys to affect the wave, careful it will go out of control. Any ideas to put in some limits so the wave doesn't fly away?

Here's one a little better, I think.  KVZ619-0

With LitDev's code from below, KVZ619-1. Works nice!

A little side note, when viewing in a browser window, mouse click in the graphic window so the keyboard arrows will work. It would be nice if that window had the focus when the page was loaded.

• Edited by Wednesday, September 12, 2012 12:29 AM
Thursday, September 06, 2012 3:43 AM
• Here is Challenge 5 without 'TextWindow.CursorLeft'.

```For x=1 to 12
For y=1 to 12
value=value+x
TextWindow.Write(value)
For length=Text.GetLength(value) To 3
TextWindow.Write(" ")
endfor
endfor
value=0
TextWindow.WriteLine("")
endfor ```
and with
```For x=1 to 12
For y=1 to 12
value=value+x
TextWindow.Write(value)
TextWindow.CursorLeft=y*4
endfor
value=0
TextWindow.WriteLine("")
endfor```

• Edited by Tuesday, September 11, 2012 1:05 AM
Tuesday, September 11, 2012 12:58 AM
• Nice!

But this will be better???.

For x=1 to 12
For y=1 to 12
value=value+x
For length=Text.GetLength(value) To 3 '  or 4
TextWindow.Write(" ")
endfor
TextWindow.Write(value)
endfor
value=0
TextWindow.WriteLine("")
endfor

Tuesday, September 11, 2012 1:19 AM
• My second Graphics Challenge 1:

```GraphicsWindow.FontName = "Consolas"
GraphicsWindow.FontSize = 14
GraphicsWindow.BrushColor = "Black"
Controls.SetSize(oText, GraphicsWindow.Width, GraphicsWindow.Height)
```

I misunderstood the challenge as follows then I wrote MBW599 at the first.

"Write a program that shows graphics to the GraphicsWindow as you type."

Nonki Takahashi

Tuesday, September 11, 2012 2:31 PM
• Very nice - slow the variations I modified a bit:

```    If Key = "Left" Then
yInc = yInc * .95
ElseIf Key = "Right" Then
yInc = yInc * 1.05
EndIf
If y > yCenter Then
yStep = yStep - yInc
If Key = "Down" Then
yStep = yStep * .95
EndIf
Else
yStep = yStep + yInc
If Key = "Up" Then
yStep = yStep * 1.05
EndIf
EndIf
Key = ""
```

Tuesday, September 11, 2012 6:18 PM
• Here's another wave, import WCD039.  Hit the up and down keys to create a wave.

You can change settings, e.g.

nPoint = 100
damping = 0.0

Tuesday, September 11, 2012 6:25 PM
• Here is Basic Challenge # 1

'Challenge of the Month - September 2012
'Basic Challenge 1

TextWindow.Write("Enter Sentence with numbers: ")
'Input="There are 7 days in a week, 52 weeks in a year, and on average 365.25 days in a year."
IsNum="False"
x=1
for counter = 1 to Text.GetLength(Input)
if text.GetCharacterCode(Text.GetSubText(Input,counter,1)) >=48 And text.GetCharacterCode(Text.GetSubText(Input,counter,1)) <= 57 or isNum="True" and text.GetSubText(Input,counter,1) = "." then
If Text.GetLength(Input) = counter and text.GetSubText(Input,counter,1) = "." then
'Do Nothing
else
Arr[x]=text.Append(Arr[x],text.GetSubText(Input,counter,1))
IsNum="True"
endif
Else
If IsNum = "True" then
x=x+1
IsNum="False"
EndIf
endif
endfor
TextWindow.WriteLine("The Sentence is: ")
TextWindow.WriteLine(Input)
TextWindow.WriteLine("")
TextWindow.WriteLine("Detected Numbers are: ")
TextWindow.WriteLine("")
For x = 1 To Array.GetItemCount(Arr)
TextWindow.WriteLine(Arr[x])
endfor

JR

• Edited by Wednesday, September 12, 2012 2:02 AM Correct Code
Tuesday, September 11, 2012 10:40 PM
• Nice!

One point.  If last word is number, it is not detected.

sample .....  My age is 56.    →   Result is 5 .

So, you'd better change like this.

Tuesday, September 11, 2012 11:44 PM
• Here's another wave, import WCD039.  Hit the up and down keys to create a wave.

You can change settings, e.g.

nPoint = 100
damping = 0.0

I like:

nPoint = 50

damping = 0.005

Absolutely COOL LitDev!

• Edited by Wednesday, September 12, 2012 12:40 AM
Wednesday, September 12, 2012 12:39 AM
• NaochanON,

Good catch!  I didn't test it that way.  I made a change to the code in the original post so that it works OK now.

JR

JR

Wednesday, September 12, 2012 2:05 AM
• Another variant using JKrueg's numbers and using shapes with less flicker, Import JTL347.
Wednesday, September 12, 2012 5:39 PM
• Wave Challenge -- NDC115

One thing that is impossible is impossible no matter if it is proven so first.

Thursday, September 13, 2012 2:40 AM
• I am sorry this is quite a duration between this post and my last, I was busy making a few other programs.

Even though I moved my calculation into my event subroutine, it still turns up "It is Even!" even if I put in a number like 25 or 11.

Here is my updated source code:

GraphicsWindow.Title = "Is your number Even or Odd?"
GraphicsWindow.CanResize = "False"
GraphicsWindow.Height = 300
GraphicsWindow.Width = 300
GraphicsWindow.Top = (Desktop.Height - 300)/2
GraphicsWindow.Left = (Desktop.Width - 300)/2

GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.DrawText(70, 0, "Enter Your Number Below")
UsersNumber = Controls.GetTextBoxText(NumberBox)

Controls.ButtonClicked = OnButtonClicked

Sub OnButtonClicked
If Controls.LastClickedButton = Calculate Then
Number = Math.Remainder(UsersNumber, 2)
If Number = 1 Then
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.DrawText(75, 75, "It is odd!")
UsersNumber = ""
Number = ""
Else
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.DrawText(150, 200, "It is even!")
UsersNumber = ""
Number = ""
EndIf
EndIf
EndSub

Any and all help would be appreciated :)

'A computer without code is like a car without gasoline.' 'Just as gasoline needs a pump to get it into the car, code needs a person to enter it into a computer... That makes me feel important!'

Thursday, September 13, 2012 3:48 AM
• Heyya!

I've kinda re-written your code. But comparing both afterwards, I've noticed the following:

Your line -> UsersNumber = Controls.GetTextBoxText(NumberBox) would only be executed once! So UsersNumber would be always = "" (and it is considered ZERO, an even value, for arithmetic operations), since nothing would be typed inside that TextBox at that moment.

Either way, you would always need to refresh UsersNumber w/ TextBox's current value before any further calculation. Thus UsersNumber = Controls.GetTextBoxText(NumberBox) have to be placed inside Sub OnButtonClicked event!

Import Code -> CCS550

`GraphicsWindow.Title = "Is your number Even or Odd?"GraphicsWindow.CanResize = "False"GraphicsWindow.BackgroundColor = "Black"GraphicsWindow.BrushColor = "Red"GraphicsWindow.FontBold   = "True"GraphicsWindow.Width  = 300GraphicsWindow.Height = 150GraphicsWindow.Left = (Desktop.Width  - GraphicsWindow.Width ) / 2GraphicsWindow.Top  = (Desktop.Height - GraphicsWindow.Height) / 2GraphicsWindow.DrawText(70, 0, "Enter Your Number Below")GraphicsWindow.BrushColor = "Blue"NumberBox = Controls.AddTextBox(35, 50)GraphicsWindow.BrushColor = "Green"Controls.AddButton("Calculate", 200, 48)Controls.ButtonClicked = OnButtonClickedSub OnButtonClicked    Btn = Controls.GetButtonCaption( Controls.LastClickedButton )  Sound.PlayClick()    If Btn = "Calculate" Then        UsersNumber = Controls.GetTextBoxText(NumberBox) * 1    Num = Math.Remainder(UsersNumber, 2)        GraphicsWindow.BrushColor = GraphicsWindow.BackgroundColor    GraphicsWindow.FillRectangle(100,100  200,100)    GraphicsWindow.BrushColor = "Yellow"        If Num = 0 Then      GraphicsWindow.DrawText(100, 100, UsersNumber + " is even!")    Else            GraphicsWindow.DrawText(100, 100, UsersNumber + " is odd!")    EndIf        Controls.SetTextBoxText(NumberBox, "")      EndIfEndSub`

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Thursday, September 13, 2012 11:27 AM
• Basic Challenge 2

Enter a number and detect if it is odd or even.    (  randomnumber creating version  )

GraphicsWindow.Height = 300
GraphicsWindow.Width = 300
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.FontSize=20
Shapes.Move(Smsg,50,200)
GraphicsWindow.BrushColor = "Navy"
Shapes.Move(srndnmb,50,150)

btn= Controls.AddButton("Random number "+Text.GetCharacter(10)+" Odd or Even ?",50,20)

Controls.ButtonClicked = OnButtonClicked

Sub OnButtonClicked
RNDNMB= Math.GetRandomNumber(1000)     '  <---------  create randomnumber
Shapes.SetText(srndnmb,"Number is "+ RNDNMB)
Number = Math.Remainder(RNDNMB, 2)
If Number = 1 Then
Shapes.SetText(Smsg," This is Odd! ")
Else
Shapes.SetText(Smsg," This is Even! ")
EndIf
EndSub

Thursday, September 13, 2012 2:15 PM
• Okay, I got it working!

I used GoToLoop's suggestion and put 'UsersNumber = Controls.GetTextBoxText(NumberBox)' in my 'Sub OnButtonClicked' event.

I also changed it a bit so instead of writing if it is even or odd in the GraphicsWindow, it will show a message.

Here's the import #: PCV768

'A computer without code is like a car without gasoline.' 'Just as gasoline needs a pump to get it into the car, code needs a person to enter it into a computer... That makes me feel important!'

Thursday, September 13, 2012 6:15 PM
• Graphical Challenge 3

Graphical Tax Calculator

'Challenge of the Month-Sept. 2012
'Graphical Challenge 3

'Create a graphical tax calculator program.  Assume the following:
' •No tax charged on the first 8k (8000).
'•20% tax up to a gross income of 40k (only paid on income above 8k).
'•40% tax up to a gross income of 150k (paid on income between 40k and 150k).
'•50% tax on a gross income over 150k (paid on income over 150k).

'Start setting up Graphics Window
GraphicsWindow.Width= 800
GraphicsWindow.Height= 600
GraphicsWindow.KeyDown= OnKeyDown
Initialize()

'Runs the routines and shows the Tax Owed
'Main Loop
While "True"
If NumberEntered = "True" then
TaxableIncome=Controls.GetTextBoxText(TaxIncomeBox)
NumberEntered="False"
TaxableIncome=text.GetSubTextToEnd(taxableIncome,2)
CalculateTax()
TaxOwed2= 0.01 * Math.Round(100*TaxOwed1)
Controls.SetTextBoxText(TaxOwedBox,"\$"+TaxOwed2)
endif
Program.Delay(100)
Endwhile

'Pulls the Taxable Income from Taxable Income Box
Sub OnKeyDown
If controls.lasttypedtextbox=TaxIncomeBox and graphicswindow.lastkey="Return" then
TaxableIncome=Controls.GetTextBoxText(TaxIncomeBox)
NumberEntered="True"
endif
Endsub

'Calculates the Tax Owed Amount
Sub CalculateTax
GraphicsWindow.DrawBoundText(10,220,800,"                                                                                                                                                                                                               ")
If TaxableIncome <= 8000 Then
TaxOwed1=TaxableIncome*0
GraphicsWindow.DrawBoundText(10,220,800,"Your Top Tax Rate is 0%. You do not owe any tax.")
ElseIf TaxableIncome > 8000 and TaxableIncome <=40000 then
TaxOwed1=(TaxableIncome - 8000) * .20
GraphicsWindow.DrawBoundText(10,220,800,"Your Top Tax Rate is 20%.  You do not owe tax on the first \$8000.  You are taxed on \$"+(TaxableIncome-8000)+".")
Elseif TaxableIncome >40000 and TaxableIncome <=150000 then
TaxOwed1=(TaxableIncome - 40000)*.40 + (32000*.20)
GraphicsWindow.DrawBoundText(10,220,800,"Your Top Tax Rate is 40%.  You do not owe tax on the first \$8000.  You are taxed at a 20% rate on the next \$32000. Then at 40% on \$"+(TaxableIncome-8000-32000)+".")
Else
TaxOwed1=(TaxableIncome - 150000)* .50+ (110000*.40)+(32000*.20)
GraphicsWindow.DrawBoundText(10,220,800,"Your in the Top Tax Bracket (50%).  You do not owe tax on the first \$8000.  You are taxed at 20% on the next \$32000. Then 40% on \$110,000. Finally, at 50% on the remaining \$"+(taxableIncome-8000-32000-110000)+".")
endif
EndSub

'Sets the Graphics Window for a calculation
Sub Initialize
GraphicsWindow.Title="Tax Calculator"
GraphicsWindow.Fontsize=18
GraphicsWindow.DrawBoundText(350,50,150,"Tax Calculator")
GraphicsWindow.Fontsize=14
GraphicsWindow.DrawBoundText(100,80,200,"Enter Taxable Income:")
GraphicsWindow.DrawBoundText(100,150,150,"Tax Amount Due:")
Controls.ButtonClicked=OnButtonClicked
Controls.SetTextBoxText(TaxIncomebox,"\$")
x=0
NumberEntered="False"
Controls.SetTextBoxText(TaxOwedBox,"\$")
Endsub

'Clear the Graphics Window for the next calculation
Sub OnButtonClicked
GraphicsWindow.Clear()
Initialize()
Endsub

JR

Friday, September 14, 2012 2:58 AM
• Good answer and well structured code.
Friday, September 14, 2012 7:15 PM
• Graphics Challenge #1

'Graphics Challenge 1
'Write a program that types to the GraphicsWindow as you type.

'Initialize
GraphicsWindow.width=800
GraphicsWindow.Height=600
GraphicsWindow.Title="Typing Tutor!"
GraphicsWindow.DrawText(0,0,"Works with Letters and Numbers only!")
GraphicsWindow.Show()
x=10
y=20
GraphicsWindow.keydown=OnKeyDown

'Main Loop
While "True"
If y >=550 Then
GraphicsWindow.DrawText(10,580"End Of Screen")
GraphicsWindow.ShowMessage("End of Screen. OK to Clear and Continue.","Clear Screen")
Stack.PushValue("Color",GraphicsWindow.BrushColor)
GraphicsWindow.BrushColor="White"
GraphicsWindow.FillRectangle(0,0,800,600)
GraphicsWindow.BrushColor=Stack.PopValue("Color")
GraphicsWindow.DrawText(0,0,"Works with Letters and Numbers only!")
x=10
y=20
endif
Program.Delay(100)
endwhile

'Gets KeyBoard Input
Sub OnKeyDown
Key=GraphicsWindow.LastKey
'Removes the D from the KeyBoard Name
If Text.GetLength(key) = 2 Then
Key=text.GetSubTextToEnd(Key,2)
Endif
GraphicsWindow.DrawBoundText(x,y,13,Key)
x=x+13
If x >= 790 Then
y=y+13
x=10

endif
Key=""
endsub

JR

Sunday, September 16, 2012 12:06 AM
• Basic Challenge 5 in only 8 lines of code : HPD043
Sunday, September 16, 2012 2:32 PM
• Basic Challenge 1

not been on for a while thought i would give this a go

HRB788

Wednesday, September 19, 2012 12:12 AM
• I've been away too, looking at PHP and Javascript.

I realise how important these challenges are though, to keep the creative juices flowing.

Here's my challenge 1:

VCM525

Robin.

Wednesday, September 19, 2012 3:57 PM
• Good answers SkidMark and Robin,

You use a similar approach.

Can you think of a way to print out the 3 numbers in my sample text - the hard bit is to spot the numbers together and also the number with a decimal point in it.

The result should be 3 numbers detected, 7, 52 and 365.25.  To be sure your program detects the numbers properly, also output their sum (all added together, i.e. 424.25

Wednesday, September 19, 2012 6:03 PM
• I tried, and failed. Close but no cigar!

THD601

For some reason, it doesn't append, but moves to the next array element.

Any suggestions?

R

Thursday, September 20, 2012 1:41 PM
• One problem is that you are using the index counter i in the main loop and inside getNumber().  i is a global variable (all variables are global scope in SB), so when you change it in getNumber, it is changed in the main loop.

I changed it to j inside getNumber()

Also, when you do:

```  For j = 48 To 57
If (nextChar = j Or nextChar = 46) Then
numberEnd = "false"
Else
numberEnd = "true"
EndIf
EndFor
```

j keeps looping to the end so only j=57 sets numberEnd!

Also you do:

`numberList[numberListIndex]=Text.Append(numberList[numberListIndex],Text.GetCharacterCode(nextChar))`

Should be

`numberList[numberListIndex]=Text.Append(numberList[numberListIndex],Text.GetCharacter(nextChar))`

There are still problems compiling multi-digit numbers.

At this point I think a reconsider of the algorithm.

The method I use was based on this idea.

0] Set our current number to an empty value ""

1] loop through each character

2] Assume it is a number and append it to the current number and put in a test variable (try)

3] Test if (try) is a number

a) if it is then set the current number to the test value and carry on

b) if it isn't and if our current number is an empty thing then carry on

c) if it isn't and if our current number isn't empty (it is a distinct number) store it and start a new empty current number

To test if a character string is a number, this is a nice trick:

`If (try*1 = try) Then`

where try is a string to test if it is a number.

Thursday, September 20, 2012 6:28 PM
• Sup all!!!

Trying my luck again. Now with the "controversial" Basic Challenge 1.  :P

```'############################################'
'Get Numbers from Text (v1.0)
'Basic Challenge 1
'Sep/2012
'by GoToLoop
'############################################'
' http://social.msdn.microsoft.com/Forums/en-US/smallbasic
'############################################'
'________________________________________________________________'
TextWindow.Title = "Get Numbers from Text"
TextWindow.BackgroundColor = "Yellow"
TextWindow.ForegroundColor = "Black"
TextWindow.Clear()

dot  = Text.GetCharacterCode(".")
neg  = Text.GetCharacterCode("-")

zero = Text.GetCharacterCode(0)
nine = Text.GetCharacterCode(9)

LF   = Text.GetCharacter(10)
'________________________________________________________________'
txt[1] = "There are 7 days in a week, "
txt[2] = "52 weeks in a year and, "
txt[3] = "on average, "
txt[4] = "365.25 days in a year." + LF
txtIdx = Array.GetItemCount(txt)

For idx = 1 to txtIdx
TextWindow.WriteLine( txt[idx] )
str = str + txt[idx]
EndFor

'TextWindow.WriteLine("Type in text to extract numbers:")
'________________________________________________________________'
TextWindow.ForegroundColor = "Blue"

CollectNumbers()
DisplayNumbers()

TextWindow.ForegroundColor = "Magenta"
TextWindow.WriteLine(LF)
'________________________________________________________________'
Sub DisplayNumbers
'  Needs: numbers[]

numIdx = Array.GetItemCount(numbers)

For idx = 1 to numIdx
TextWindow.WriteLine( idx + "-> " + numbers[Idx] )
EndFor

EndSub
'________________________________________________________________'
Sub CollectNumbers
'  Needs:  str
'  Calls:  ExtractChar()
'  Returns:  numbers[], numIdx

numIdx   = 0
moreWork = "True"

While moreWork

num = ""
isSpree = "True"

While isSpree

ExtractChar()

If asc >= zero And asc <= nine Or asc = dot Or asc = neg Then
num = Text.Append( num, Text.GetCharacter(asc) )
Else
isSpree = "False"
EndIf

EndWhile

If num * 1 = num Then
numIdx = numIdx + 1
numbers[numIdx] = num
EndIf

EndWhile

EndSub
'________________________________________________________________'
Sub ExtractChar
'  Needs: str
'  Flags: moreWork
'  Returns: asc

If str <> "" Then
asc = Text.GetCharacterCode(str)   ' Extracts 1st character code outta string
str = Text.GetSubTextToEnd(str, 2) ' And plucks it off from string afterwards
Else
asc = ""
moreWork = "False"
EndIf

EndSub
'________________________________________________________________'```

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Thursday, September 20, 2012 8:12 PM
• That works well, here was mine with less pretty output.

`txt = "There are 7 days in a week, 52 weeks in a year, and on average 365.25 days in a year."result = ""For i = 1 To Text.GetLength(txt)  char = Text.GetSubText(txt,i,1)  try = Text.Append(result,char)   If (try*1 = try) Then    result = try  ElseIf (result <> "") Then    TextWindow.WriteLine(result)    result = ""  EndIfEndFor`

Thursday, September 20, 2012 8:21 PM
• Wow! Über compact!!!

You accumulate characters in result until SB's primitive number evaluator flags it's not a valid number anymore!

Click on "Propose As Answer" if some post solves your problem or "Vote As Helpful" if some post has been useful to you! (^_^)

Thursday, September 20, 2012 9:12 PM
• Very impressive bit of "coding poetry." I'm inspired as well as jealous. Should I go and dig potatoes instead?

R.

Friday, September 21, 2012 8:42 AM
• Math Challenge1  -  RXT665                                                                                                                                                            Chooses if the number is Unsigned or Signed.                                                                                                                                    Also has pretty colors.

• Edited by Sunday, September 23, 2012 3:15 AM
Sunday, September 23, 2012 3:10 AM
• Here's my Graphics challenge # 1.

BTW, how can I paste code without getting all the extra whitespace? If I go via notepad, I lose the colors, like below, but thatseems better than seemingly random formatting if I paste straight from SB, or go via Word.

'Graphics Challenge #1 Sept 2012
'Robin Andrews
'
GraphicsWindow.FontSize = 20
distance = GraphicsWindow.FontSize + 4
x = 0
y = 0
graphicswindow.KeyDown = keyDownEvent
'
Sub keyDownEvent
char = GraphicsWindow.lastkey
If char = "Space" Then
char = " "
Endif
If (x>GraphicsWindow.width - distance) Then
y = y + distance
x = 0
EndIf
GraphicsWindow.DrawText(x,y,char)
x = x + distance
EndSub

Sunday, September 23, 2012 11:00 AM
• Your code for the challenge is good and works well.  To past code, copy it from SmallBasic using the 'Inset Code Block' option at the top of the post window.

Sunday, September 23, 2012 12:39 PM
• argh cant do this
Monday, September 24, 2012 12:38 PM
• Can't do what?
Monday, September 24, 2012 5:51 PM
• Good answers SkidMark and Robin,

You use a similar approach.

Can you think of a way to print out the 3 numbers in my sample text - the hard bit is to spot the numbers together and also the number with a decimal point in it.

The result should be 3 numbers detected, 7, 52 and 365.25.  To be sure your program detects the numbers properly, also output their sum (all added together, i.e. 424.25

sorry.  Cant get my head round this :-(

Tuesday, September 25, 2012 6:32 AM
• Thanks litdev. Good feedback is encouraging. And thanks to everyone who puts time and energy into this forum.

(smiley)

Tuesday, September 25, 2012 3:21 PM
• See some of the solutions above.  Feel free to ask any questions on the solutions given.
Tuesday, September 25, 2012 6:28 PM
• Math Challenge 1

Import TGG480

Doesn't work for numbers less than 1, yet.

• Edited by Wednesday, September 26, 2012 2:52 AM
Wednesday, September 26, 2012 2:34 AM
• Graphics challange1:

GraphicsWindow.KeyDown = OnKeyDown
GraphicsWindow.BrushColor = "Black"
Alpha = "1=A;2=B;3=C;4=D;5=E;6=F;7=G;8=H;9=I;10=J;11=K;12=L;13=M;14=N;15=O;16=P;17=Q;18=R;19=S;20=T;21=U;22=V;23=W;24=X;25=Y;26=Z"
Sub OnKeyDown
If GraphicsWindow.LastKey = "Space" Then
Text = Text + " "
Else
For i = 1 To 26
If GraphicsWindow.LastKey = Alpha[i] Then
Text = Text + GraphicsWindow.LastKey
EndIf
EndFor
EndIf

GraphicsWindow.Clear()

GraphicsWindow.DrawBoundText(10,10,GraphicsWindow.Width - 10,Text)
EndSub

One thing that is impossible is impossible no matter if it is proven so first.

• Edited by Wednesday, September 26, 2012 7:00 PM
Wednesday, September 26, 2012 6:59 PM
• Zock77,

`GraphicsWindow.KeyDown = OnKeyDownGraphicsWindow.BrushColor = "Black"Alpha = "1=A;2=B;3=C;4=D;5=E;6=F;7=G;8=H;9=I;10=J;11=K;12=L;13=M;14=N;15=O;16=P;17=Q;18=R;19=S;20=T;21=U;22=V;23=W;24=X;25=Y;26=Z"Sub OnKeyDown   If GraphicsWindow.LastKey = "Space" Then     Text = Text + " "   ElseIf GraphicsWindow.LastKey = "Back" Then     Text = Text.GetSubText(Text,1,Text.GetLength(Text)-1)   ElseIf GraphicsWindow.LastKey = "Return" Then     Text  = Text+Text.GetCharacter(10)   Else      For i = 1 To 26 If GraphicsWindow.LastKey = Alpha[i] Then      Text = Text + GraphicsWindow.LastKey    EndIf    EndFor   EndIf  GraphicsWindow.Clear()   GraphicsWindow.DrawBoundText(10,10,GraphicsWindow.Width - 10,Text)  EndSub`

• Edited by Wednesday, September 26, 2012 9:10 PM
Wednesday, September 26, 2012 9:06 PM
• This is an idea for a future challenge :

Write a program to find the divisors of a given number.

Nonki Takahashi

Thursday, September 27, 2012 12:31 AM
• Idea for future challenge:

Write a program to calculate the area of a crescent.

Saturday, September 29, 2012 12:32 AM
• Couldn't resist:

BZX012

Any feedback on code appreciated - I want to start programming properly, so even tiny details welcome.

Suggestion for further challenge: extent to allow negative numbers?

Robin.

Saturday, September 29, 2012 10:55 AM
• Robin,

Good code.  I like to unify style such as A = 1 or A=1.  I prefer A = 1.

Nonki Takahashi

Saturday, September 29, 2012 2:48 PM