Microsoft Small Basic

Program Listing: JXB040
' Math_CartesianToPolar Test Program
' Version 0.2
' Copyright © 2016-2017 Nonki Takahashi. The MIT License.

GraphicsWindow.Title = "Test - Cartesian to Polar"
gw = 598
gh = 428
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
color = "LightGray"
dx = 10
dy = 10
x1 = Math.Remainder(gw / 2, dx) - dx
x2 = gw - x1
y1 = Math.Remainder(gh / 2, dy) - dy
y2 = gh - y1
DrawGrid()
color = "Gray"
dx = 100
dy = 100
x1 = Math.Remainder(gw / 2, dx) - dx
x2 = gw - x1
y1 = Math.Remainder(gh / 2, dy) - dy
y2 = gh - y1
DrawGrid()
GraphicsWindow.BrushColor = "Black"
xText = Shapes.AddText("")
Shapes.Move(xText, 10, 20)
yText = Shapes.AddText("")
Shapes.Move(yText, 10, 40)
rText = Shapes.AddText("")
Shapes.Move(rText, 10, 60)
aText = Shapes.AddText("")
Shapes.Move(aText, 10, 80)
x2Text = Shapes.AddText("")
Shapes.Move(x2Text, 10, 100)
y2Text = Shapes.AddText("")
Shapes.Move(y2Text, 10, 120)
GraphicsWindow.MouseMove = OnMouseMove
While "True"
If mouseMove Then
x = mx - gw / 2
y = my - gh / 2
Math_CartesianToPolar()
Shapes.SetText(xText, "x=" + x)
Shapes.SetText(yText, "y=" + y)
Shapes.SetText(aText, "a=" + a)
Shapes.SetText(rText, "r=" + r)
Math_PolarToCartesian()
Shapes.SetText(x2Text, "x=" + x)
Shapes.SetText(y2Text, "y=" + y)
If mx <> mxLast Or my <> myLast Then
If line <> "" Then
Shapes.Remove(line)
EndIf
GraphicsWindow.PenColor = "Red"
line = Shapes.AddLine(gw / 2, gh / 2, mx, my)
mxLast = mx
myLast = my
EndIf
EndIf
EndWhile

Sub OnMouseMove
mx = GraphicsWindow.MouseX
my = GraphicsWindow.MouseY
mouseMove = "True"
EndSub

Sub DrawGrid
' param x1, x2 - x range
' param dx - delta x
' param y1, y2 - y range
' param dy - delta y
' param color - color for grid
GraphicsWindow.PenColor = color
For x = x1 To x2 Step dx
GraphicsWindow.DrawLine(x, y1, x, y2)
EndFor
For y = y1 To y2 Step dy
GraphicsWindow.DrawLine(x1, y, x2, y)
EndFor
EndSub

Sub Math_PolarToCartesian
' Math | convert polar coodinate to Cartesian coordinate
' param r, a - polar Coordinate
' return x, y - Cartesian coordinate
_a = Math.GetRadians(a)
x = r * Math.Cos(_a)
y = r * Math.Sin(_a)
EndSub

Sub Math_CartesianToPolar
' Math | convert Cartesian coodinate to polar coordinate
' param x, y - Cartesian coordinate
' return r, a - polar Coordinate (0<=a<360)
r = Math.SquareRoot(x * x + y * y)
If x = 0 And y > 0 Then
a = 90 ' [degree]
ElseIf x = 0 And y < 0 Then
a = -90
ElseIf x = 0 And y = 0 Then
a = 0
Else
a = Math.ArcTan(y / x) * 180 / Math.Pi
EndIf
' at this point -90<=a<=90
If x < 0 Then
a = a + 180
ElseIf x >= 0 And y < 0 Then
a = a + 360
EndIf
' at this point 0<=a<360
EndSub