A Worked Example - Controller

Finally, we now can start working on our controller. This is where the program actually comes together and becomes useful. While a program such as Connect Four may seem quite complex, using MVC architecture can make it quite easy to work with. Let’s check it out!


The ConnectController class just contains a single main() method:

from ConnectModel import *
from ConnectView import *
import sys

class ConnectController:
  def main(args):
    model = ConnectModel(6, 7)
    view = ConnectView()
    while True:
        if model.make_move(view.show_menu()):
          if model.check_win() or model.check_draw():
      except Exception as e:
    if model.check_win():

# main guard
if __name__ == "__main__":

This method uses methods in the view and model classes to get the game to work. For example, if we start inside of the while loop, we see the following steps:

  1. The game prints the current board to the screen.
  2. The game prints a message for the current user.
  3. The game then asks the user for input, and uses that input to make a move.
    1. If the move is successful, it checks to see if the game is over. If so, it exits the loop.
    2. If the move is unsuccessful, an exception is thrown and then caught and handled. The program repeats so the user has another opportunity to move.
  4. Finally, once the program exits the loop, it will print a message giving the outcome of the game.

That’s all there is to it! Once again, our main() method ends up being an outline of our program. In this case, almost every line of code is calling a method in both the model and the view, combining them in such a way as to make the program work seamlessly.

We can use the terminal to see how it works.