In: Computer Science
This is a Python project and I´m wondering if anyone has a simple solution for this?
Write a program, move.py, which asks the user for the position of a virtual character on the x-axis in a coordinate system and then allows the user to move the virtual character to the right or left, indicated by the characters 'r' or 'l'. The user should be able to move the virtual character as often as he/she wishes, but if the input is neither 'r' nor 'l' the program quits. Instructions for the user are written out at the beginning, but the position of the virtual character (denoted by 'o') is shown in each iteration.
The valid range on the x-axis, which the virtual character can traverse, is from 1 to 10 and you can assume that at the beginning the user inputs a number in this range. If the virtual character is positioned at either end of the range it will not move when the user tries to move it out of the range.
In your solution, you should only use methods/material discussed in the first five chapters in the textbook. This means, for example, that you are not allowed to use lists.
Make sure that your code is very readable (see, for example, this thread).
Note the following:
Example input/output:
Input a position between 1 and 10: 7 xxxxxxoxxx l - for moving left r - for moving right Any other letter for quitting Input your choice: r xxxxxxxoxx Input your choice: r xxxxxxxxox Input your choice: r xxxxxxxxxo Input your choice: r xxxxxxxxxo Input your choice: l xxxxxxxxox Input your choice: l xxxxxxxoxx Input your choice: l xxxxxxoxxx Input your choice: l xxxxxoxxxx Input your choice: q xxxxxoxxxx
The program is as below
# define constant for the start and end position range
START=1
END=10
virtual_chr = "o"
position = int(input("Input a position between %s and %s:
"%(START,END)))
print_str = 'x'*(position-START) + virtual_chr +
'x'*(END-position)
# print the string
print(print_str)
print("l - for moving left")
print("r - for moving right")
print("Any other letter for quitting")
# loop of the game
while True:
move = input("Input your choice: ")
# If 'l' is entered
if move == 'l' :
if position != START:
position = position - 1
# If 'r' is entered
elif move == 'r':
if position != END:
position = position + 1
# need to quit game
else:
# print the string before quit
print(print_str)
break
# set new print_str
print_str = 'x'*(position-START) + virtual_chr +
'x'*(END-position)
# print the string
print(print_str)
Here is the program output:
Input a position between 1 and 10: 7
xxxxxxoxxx
l - for moving left
r - for moving right
Any other letter for quitting
Input your choice: r
xxxxxxxoxx
Input your choice: r
xxxxxxxxox
Input your choice: r
xxxxxxxxxo
Input your choice: r
xxxxxxxxxo
Input your choice: l
xxxxxxxxox
Input your choice: l
xxxxxxxoxx
Input your choice: l
xxxxxxoxxx
Input your choice: l
xxxxxoxxxx
Input your choice: q
xxxxxoxxxx