Question

In: Computer Science

This program should be done in python. This must use the principles of object oriented program....

This program should be done in python. This must use the principles of object oriented program. Create one or more classes to play Four-in-a-Row (also called Connect Four) with a user. It’s similar to tic-tac-toe but the board is of size 7×6 and discs fall straight through so the legal moves are more stringent than tic-tac-toe. The state of the board should be printed to the terminal after each legal move. You can represent the different colored discs as X’s and O’s. The program should take input from the user for the next move, print the new state of the board and make a move of it’s own. The program does not need to implement a winning strategy so a random move would be sufficient. If the user makes an illegal move the program should display a message and prompt the user again. You can read more about this game on https://en.wikipedia.org/wiki/Connect_Four

Solutions

Expert Solution

Connect four game written using python :

#! /usr/bin/env python3

from itertools import groupby, chain

NONE = '.'

RED = 'R'

YELLOW = 'Y'

def diagonalsPos (matrix, cols, rows):

#Get positive diagonals, going from bottom-left to top-right.

for di in ([(j, i - j) for j in range(cols)] for i in range(cols + rows -1)):

yield [matrix[i][j] for i, j in di if i >= 0 and j >= 0 and i < cols and j < rows]

def diagonalsNeg (matrix, cols, rows):

#Get negative diagonals, going from top-left to bottom-right

for di in ([(j, i - cols + j + 1) for j in range(cols)] for i in range(cols + rows - 1)):

yield [matrix[i][j] for i, j in di if i >= 0 and j >= 0 and i < cols and j < rows]

class Game:

def __init__ (self, cols = 7, rows = 6, requiredToWin = 4):

#Create a new game.

self.cols = cols

self.rows = rows

self.win = requiredToWin

self.board = [[NONE] * rows for _ in range(cols)]

def insert (self, column, color):

#Insert the color in the given column.

c = self.board[column]

if c[0] != NONE:

raise Exception('Column is full')

i = -1

while c[i] != NONE:

i -= 1

c[i] = color

self.checkForWin()

def checkForWin (self):

#Check the current board for a winner

w = self.getWinner()

if w:

self.printBoard()

raise Exception(w + ' won!')

def getWinner (self):

#Get the winner on the current board.

lines = (

self.board, # columns

zip(*self.board), # rows

diagonalsPos(self.board, self.cols, self.rows), # positive diagonals

diagonalsNeg(self.board, self.cols, self.rows) # negative diagonals

)

for line in chain(*lines):

for color, group in groupby(line):

if color != NONE and len(list(group)) >= self.win:

return color

def printBoard (self):

#Print the board.

print(' '.join(map(str, range(self.cols))))

for y in range(self.rows):

print(' '.join(str(self.board[x][y]) for x in range(self.cols)))

print()

if __name__ == '__main__':

g = Game()

turn = RED

while True:

g.printBoard()

row = input('{}\'s turn: '.format('Red' if turn == RED else 'Yellow'))

g.insert(int(row), turn)

turn = YELLOW if turn == RED else RED

Sample output :


Related Solutions

Practice object-oriented principles by making two Peanut Butter and Jelly Sandwiches. The program must create two...
Practice object-oriented principles by making two Peanut Butter and Jelly Sandwiches. The program must create two sandwiches based on user input. The sandwich information for both must then print out their details and determine if the two sandwiches are equal. Requirements:   Write a class called Bread with the following Instance Variables Name: The name brand of the bread. o   Calories: The number of calories per slice assumed to be between 50 and 250 inclusively. Type: The kind of bread. This can...
Problem Write a movie management system using object-oriented design principles. The program will read from the...
Problem Write a movie management system using object-oriented design principles. The program will read from the supplied data file into a single array list. The data file (movies.txt) contains information about the movies. Each movie record has the following attributes: - Duration (in minutes) - Title - Year of release Each record in the movies.txt file is formatted as follows: - Duration,Title,Year - e.g.: 91,Gravity,2013 Specifically, you have to create an interactive menu driven application that gives the user the...
Write 5 questions about Object Oriented Programming in Python. Each question should have 7 options. Please...
Write 5 questions about Object Oriented Programming in Python. Each question should have 7 options. Please provide 7 answer options for EACH question and the select answer for EACH question
Program must use Python 3 Your program must have a welcome message for the user. Your...
Program must use Python 3 Your program must have a welcome message for the user. Your program must have one class called CashRegister. Your program will have an instance method called addItem which takes one parameter for price. The method should also keep track of the number of items in your cart. Your program should have two getter methods. getTotal – returns totalPrice getCount – returns the itemCount of the cart Your program must create an instance of the CashRegister...
When should you use and object-oriented language over a procedural language and vice versa?
When should you use and object-oriented language over a procedural language and vice versa?
MUST BE DONE IN C (NOT C++) This program should utilize the basics of strings. First,...
MUST BE DONE IN C (NOT C++) This program should utilize the basics of strings. First, declare and initialize a string. You can name the variable whichever way you want and you can initialize it to whichever value you want. Then, use a for loop to print its characters; one at a time, until you reach the null character. After this, go ahead and declare a second string (since you are not initializing it right away, you will have to...
(MUST BE DONE IN C (NOT C++)) For this program, remember to use feet and inches....
(MUST BE DONE IN C (NOT C++)) For this program, remember to use feet and inches. First, ask the user for the name of students they have in their class. Then, using a loop, you will ask for each student’s height. However, you will have to use two separate variables, one for feet and one for inches. Then, you will have to call two functions. The first function will check if the values entered are valid (check if number of...
Program must be in Python Write a program in Python whose inputs are three integers, and...
Program must be in Python Write a program in Python whose inputs are three integers, and whose output is the smallest of the three values. Input is 7 15 3
What are the object oriented concepts and which all object oriented concepts are used in the...
What are the object oriented concepts and which all object oriented concepts are used in the given program? Consider the following code and explain how each of the object oriented concepts are applied in the given program. (CO1) class Vehicle { string brand; public: void honk(); void honk(int); }; void Vehicle::honk() { cout << "Tuut, tuut! \n" ; } void Vehicle::honk(int x) { for(int i=0;i<x;i++) cout << "Tuut, tuut! \n" ; } int main() { Vehicle V1; V1.honk(); V1.honk(3); }
Why is it more feasible to use Objects and object oriented programming as compared to using...
Why is it more feasible to use Objects and object oriented programming as compared to using method based programs? What are the disadvantages of using only methods in your programs.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT