Hi, I have just started learning. Do you have any suggestions on how to improve my code?

positionX = 0
positionY = 0

while true
global positionX
global positionY

println(“X: $positionX”)
println(“Y: $positionY”)

print("Enter command: ")
userInput = readline()

if userInput == “a”
positionX -= 1
elseif userInput == “d”
positionX += 1
elseif userInput == “s”
positionY -= 1
elseif userInput == “w”
positionY += 1

Hi and welcome to Julia :slight_smile: In what sense would you like to improve your code? Have you read the manual? If you are after performance, I can recommend the performance tips?

1 Like

Please quote your code.

Also, it is best to ask a more concrete question. Your code is neither optimal (because it uses globals) nor idiomatic, but may be fine for a trivial task, such as this exercise.

There’s nothing particularly wrong with your code, it’s just very simple.

Something you could do is split the code into functions, for example you would want a function update_position.

To avoid the if else you could try to use a Dictionary (e.g. Dict("a"=>1, "d"=>-1)).

Or better, you could try to introduce some types. For example an Action type and a State type that hold positionX and positionY, you code would then read something like:

actions = [Action("Left","a",-1), Action("Right","d",+1)]

for action in actions
    iskey(action, userInput) && update!(state, action)
1 Like