finalised code that works with moves while loop