Friday 2 October 2020

Part Two: Exercise 3: A Rudimentary Car Game

 In this exercise, we create a simple car game that takes in user input. The game would give instructions to the user. If the user inputs ‘start’ the game would tell the user that the car has started.

When the user inputs ‘stop’ the game will tell the user that the car has stopped.
The game would also tell the user that the car has already started if the user inputs ‘start’ while the car is already started and would also tell the user the car has already stopped if the user inputs ‘stop’ while the car is already stopped.
When the user inputs ‘quit’, the game would end.
 
We would require a while loop.
 
You can compare with my solution below:
 
    print('WELCOME TO CAR GAME')
    print()
    print('These are the instructions')
    print()
    print('Type "start" at the prompt to start the car')
    print('Type "stop" at prompt at the prompt to stop the car')
    print('Print "quit" at the prompt to end game')
    print()
    game = ' '
    started = False
    while game:
        game = input('Enter your option>>')
        if game.lower() == 'start':
            if started:
                print('Car already started')
            else:
                started = True
                print('Car is starting...')
                print('Car started')

        elif game.lower() == 'stop':
            if not started:
                print('Car already stopped')
            else:
                started = False

                print('Car is stopping...')
                print('Car has stopped')

        elif game.lower() == 'quit':
            print('Quitting Game...')
            print('Thanks for playing')
            exit(0)
 
First we print the title of the game, then followed by the instructions. Before starting our while loop, we declare and empty string called game, similar to how we create empty lists.
In the while loop we state that the variable, game, would be provided by the user. If the user enters ‘start’ the car will start but if the user enters ‘start’ again he is told the game has already started.
When the user enters ‘stop’ the car would stop and if he enters ‘stop’ again the game tells him the car has already stopped.
If he enters quit the game ends
The command exit(0) ensures that the program ends and exists the while loop.

No comments:

Post a Comment