General Description

please please please help

please code in python3

let me know if any extra information is needed

You have been chosen to create a version of connect 4. In this version, there can be forbidden positions, or places that neither x nor o can play. However, connecting four together is still the way to win, and this can be done vertically, horizontally, diagonally (or anti-diagonally if you distinguish between the backward diagonal).

Required Features

You must implement two new game options, one for two players, and one for x player vs computer.

The player is always x and the computer is always o in that case.

Player one and two alternate turns.

Players cannot overwrite each other's moves.

Players cannot play on forbidden places, and forbidden places do not count for victory.

At the start of each game:

Ask the player what game board they want to load.

Then start with the x player, and alternate.

Check for victory after each move, not after each pair of moves.

Players may enter a move, two integers separated by a space, or the words "load game" or "save game" which will either load or save over the current game.

You must implement a load game feature.

Ask for the file name and load that file. If a game is currently in progress, overwrite that game and immediately start on the loaded game.

You must implement a save game feature.

Ask for the name that you wish to save to, and save the file to that name.

Detect when one or the other player has adjoined the spheres (connected four).

Display a message with the winning player.

End that game.

Go back to the main menu.

If the board is full, then that is a tie.

Design Document

There is no design document for this project. It has been replaced with a testing script. Any questions about design documents will be ignored.

Required names and Interface

Your project should be in proj2.py

The design of project 2 is mostly up to you, but we will require that your project create a class:

class AdjoinTheSpheres:

This must have a method whose definition is:

def main_menu(self):

Recommended – Creating the proj2 Directory

During the semester, you’ll want to keep your different Python programs organized, organizing them in appropriately named folders (also known as directories).

You should create a directory in which to store your Project 2 files. We recommend calling it proj2, and creating it inside your Projects directory inside the cmsc201 directory.

Refer to earlier assignments about proper use of mkdir.

Board Files

Board files are made in this way:

5 7

x

x..o*xx

x..o.*.

..o.*..

xo.ooo.

x.xx...

The first line of the file has two numbers separated by whitespace, they represent the number of rows (height) and columns (width) of the board.

The next line is whose turn it is next.

The next lines are the board, where:

x represents the player x move

o represents the player o move

  • represents a forbidden position, where neither player can move and doesn't count for the making of a line of four.

period (.) or space ( ) represents an empty (unfilled space).

You should be able to load with both the periods and spaces, though you should pick one format to save as.

If you are using a program that may mess with your whitespace, i.e. change a number of spaces to a tab, or back to spaces, and generally cause havoc, then use periods instead of spaces.

Sample board files can be found at: (please remember the cp command!)

/afs/umbc.edu/users/e/r/eric8/pub/cs201/spring20/proj2/game_1.m

here is whats inside game_1.m:

gl.umbc.edu - PuTTY File Edit Options Buffers Tools ObjC Help 5 7 -UU- (DOS) ----Fi game 1.m All 14 (Objc//1 Abbrev) --

/afs/umbc.edu/users/e/r/eric8/pub/cs201/spring20/proj2/game_2.m

here is whats inside game_2.m:

/afs/umbc.edu/users/e/r/eric8/pub/cs201/spring20/proj2/game_3.m

here is whats inside game_3.m:

1 gl.umbc.edu - PuTTY File Edit Options Buffers Tools ObjC Help 5 7 x 0 X ox -UU- (DOS) ----F1 game 3.m All L1 (Objc//1 Abbre

/afs/umbc.edu/users/e/r/eric8/pub/cs201/spring20/proj2/game_4.m

here is whats inside game_4.m:

HIPPO - O X glumbc.edu - PuTTY File Edit Options Buffers Tools Objc Help 57 x x oxx O xo ooo X XX -UU- (DOS) ----F1 game 4.m

Coding Standards

Prior to this assignment, you should be familiar with the entirety of the Coding Standards,

For the coding standards:

https://docs.google.com/document/d/1hxv3Lp1TT4xe1HTm3nGBN7EXfq0pMjP40-yfrN4rKRI/edit?usp=sharing

For the forbidden magic:

https://docs.google.com/document/d/1IoMhl8Y1y9ZYFEQly7s2aKgAy9DOt_bG7XlhyJKihlo/edit?usp=sharing

You should be commenting your code, and using constants in your code (not magic numbers or strings).

Any strings with a meaning should be constants!

Any numbers other than 0 or 1 are magic numbers!

You will lose major points if you do not follow the 201 coding standards.

If you have questions about commenting, whitespace, or any other coding standards, please come to office hours.

TIP: This would be a very good time to use incremental development! Incremental development is when you are only working on a small piece of the code at a time, and testing that the piece of code works before moving on to the next piece. This makes it a lot easier to fix any mistakes.

Other Specifications

For this assignment, your class must have at least six methods (functions).

You may not import any libraries or use any library functions aside from the one below.

The only input you are permitted is to use the line:

from random import randint

You can use the randint function to get random integers for the computer's moves.

Input Validation

On the main menu, the only possible thing which will be entered is an integer. It may be a menu option, or maybe it will be garbage (-2, 1801), but we won't enter incorrect types (strings where you are going to be casting to int).

You can assume that during the game, only the following user input will be given:

Two numbers separated by a space

"load game" should just check it with .lower() and not worry about case.

"save game" with the same thing about case insensitivity.

Turn flow

A turn is comprised of the following:

The board is displayed.

The user is prompted for a move, or 'load game' or 'save game'

The user inputs or computer gives us the move

The move is entered on the board

End game conditions are checked.

The turn control swaps to the other player.

Steps 1-6 are repeated until the game ends.

Testing Script

The testing script will count for 15 / 80 of the project points.

The testing script is a new way for us to get you to think about your project and to code up tests before you even code the actual project.

For 4 of your functions, you should write five tests each. A test is:

Setting some conditions (setting a board or move conditions).

Call your functions

Check the return values for what is expected.

Display whether the test has passed or failed.

At the top of your test script you should use the following line of code to import your project code:

from proj2 import AdjoinTheSpheres

That will ensure that your proj2_test file has access to the class that you will create.

Because you will not have written your project yet, you will probably have to modify your project test file even after you submit it. This is completely expected.

However, if you don't test a function that loads the board, and your eventual project's board loading code doesn't work well or has bugs, or checking for victory has bugs but no tests were written, then you will lose points for not testing functionality.

It is better to write tests that fail on your code than to write no tests for code that is broken.

For an example of how testing files should look, I'll post some examples that you can copy from GL/github:

https://github.com/UMBC-CMSC-Hamilton/CMSC201-Spring2020/blob/master/Exam%20II%20Review/debug_practice.py

Sample Output

Here is the sample output for the project.

https://docs.google.com/document/d/1kau7GcFP-rpqcxEZBwISjsQsUn_F26s3abNuK0iY8VI/edit?usp=sharing

Extra Credit (5 points)

If you have done all of the rest of the things for the project, then you can get yourself a few extra points by implementing one last piece of functionality for the computer player.

When there are three dots or x's in a row, whichever player is up next should try to fill in the three and make four. Either they will fill in their opponent's shape to prevent them from winning.

If there are multiple examples of three winning and losing conditions, then fill in any of them.

For example, either x wants to move in the yellow or red squares to win, or o wants to move in at least one of these spaces to prevent x from winning or move in the green space to win.

x

x

x

o

x

o

x

x

o

ution... Items - Binding of ... Math Attendance First Run AdjoinTheSpheres Main Menu 1) New Game (2 player) 2) New Game (1 pl

4 11111 5 IIIII Player x What move do you want to make? Answer as row (vertical column (horizontal) or save game or load game

3 xxx 5 LT1 Player o What move do you want to make? Answer as row (verti column (horizontal) or save game or load game 5 6 11

Second Run AdjoinTheSpheres Main Menu 1) New Game (2 player) 2) New Game (1 player vs computer) 3) Exit Game Select Option fr

3 11 x 4 111111 5 III III Player x What move do you want to make? Answer as row (vertical) column (horizontal) or save game o

5 LITT 1121314151617 1 1x10 10 2 x 1111 3 I x To 4 IIIIII 5111111 Player x What move do you want to make? Answer as row (vert

Player x What move do you want to make? Answer as row (vertical) column (horizontal) or save game or load game 3 6 1121314151

Third Run AdjoinTheSpheres Main Menu 1) New Game (2 player) 2) New Game (1 player vs computer) 3) Exit Game Select option fro

30 TL 4 x10101010101 5 xl xxl AdjoinTheSpheres Main Menu 1) New Game (2 player) 2) New Game (1 player vs computer) 3) Exit Ga

Recommended Answers

All 6 Replies

You gave us a big project to do but you haven’t shared what you’ve done so far, what errors you’re getting, or where you’re stuck.

We will definitely help you learn so you can complete your project. But why would we take hours and hours just to do your homework for you?

commented: I couldnt figure out how to edit my question but I added a comment under this post. Sorry for the confusion +0

So far I have:

from random import randint

def initialiseBoard():

print('Following is the board and the respective positions.\nEnter the row and column separated by a space to play.')

board=[['' for x in range(3)] for y in range(3)]

for i in range(3):

for j in range(3):

print('[{0},{1}] '.format(i+1,j+1),end='')

print()

return board

def inputBoard(board,turn,play):

print()

if play=='player':

if turn%2==0:

print('Player X What move do you want to make? Answer as row (vertical) column (horizontal) or save game or load game ')

else:

print("Player O What move do you want to make? Answer as row (vertical) column (horizontal) or save game or load game ")

x,y = map(int, input().split(' '))

if x>3 or y>3 or x<1 or y<1:

print("Enter valid position")

return True

if play=='ai':

print('Computer entered its position ')

while True:

x=randint(1,3)

y=randint(1,3)

if board[x-1][y-1]=='':

break

i=x-1

j=y-1

if board[i][j]!='':

print("Enter row and column that hasnt already been chosen.")

return True

if turn%2==0:

board[i][j]='X'

else:

board[i][j]='O'

return

def checkWin(board,ch,play):

for i in range(3):

if board[i][0]==ch and board[i][1]==ch and board[i][2]==ch:

if play=='player':

print('Player ',ch,' Wins!')

return True

if play=='ai':

print('Computer wins!')

return True

for i in range(3):

if board[0][i]==ch and board[1][i]==ch and board[2][i]==ch:

if play=='player':

print('Player ',ch,' Wins!')

return True

if play=='ai':

print('Computer wins!')

return True

if (board[0][0]==ch and board[1][1]==ch and board[2][2]==ch) or (board[0][2]==ch and board[1][1]==ch and board[2][0]==ch):

if play=='player':

print('Player ',ch,' Wins!')

return True

if play=='ai':

print('Computer wins!')

return True

return False

print('AdjoinTheSpheres Main Menu')

while 1:

print("1) New Game (2 player)")

print("2) New Game (1 player vs computer)")

print("3) Exit Game")

choice=input("Select Option from the Menu: ")

if choice not in ['1','2','3']:

print("Please enter valid option")

continue

else:

break

while(choice!='3'):

while True:

board=initialiseBoard()

print("X plays first")

turn=0

while turn<9:

if choice=='1':

if(inputBoard(board,turn,'player')):

continue

elif choice=='2' and turn%2==0:

if(inputBoard(board,turn,'player')):

continue

elif choice=='2' and turn%2==1:

if(inputBoard(board,turn,'ai')):

continue

for i in range(3):

for j in range(3):

if board[i][j]=='':

print('[ ]',' ',end='')

else:

print('[',board[i][j],']',' ',end='')

print()

if turn%2==0:

if(checkWin(board,'X','player')):

break

if turn%2==1 and choice=='1':

if(checkWin(board,'O','player')):

break

if turn%2==1 and choice=='2':

if(checkWin(board,'O','ai')):

break

turn=turn+1

if turn==9:

print("Its a draw! Everybody sucks!")

x=input("Want to play again? Press 1 for yes, anything else to exit out.")

if x=='1':

break

else:

print("Thank you for playing!")

exit()

choice=input("Select option\n1)Play against another player\n2)Play against computer\n3)Exit\n")
However I made this as a simplified version and I cant figure out how to make the code read the map files provided (https://drive.google.com/open?id=18HfhB8R21OlYiR0HlPVxoyVqaI-UMtZa) to run from

You need to use the code tool </> to insert blocks of code. What you posted is not posted as code and without proper indentation it is meaningless.

commented: Thank you Ill do that +0

This is what I have so far for the map file

from random import randint
class AdjoinTheSpheres:
    def load_map(file_name):
    read_file = open(file_name, 'r')
    lines = read_file.read()
    for line in lines:
        print(line, end = '')
x = input('file:')
load_map(x)

This is my sample code I made with a simplified board (doesnt work)

def initialiseBoard():
    print('Following is the board and the respective positions.\nEnter the row and column separated by a space to play.')
    board = [['' for x in range(3)] for y in range(3)]
    for i in range(3):
        for j in range(3):
            print('[{0},{1}] '.format(i + 1, j + 1), end='')
        print()
    return board
def inputBoard(board, turn, play):
    print()
    if play == 'player':
        if turn % 2 == 0:
            print('Player X What move do you want to make? Answer as row (vertical) column (horizontal) or save game or load game ')
        else:
            print("Player O What move do you want to make? Answer as row (vertical) column (horizontal) or save game or load game ")

        x, y = map(int, input().split(' '))

        if x > 3 or y > 3 or x < 1 or y < 1:
            print("Enter valid position")
            return True
    if play == 'ai':
# print('Computer entered its position ')
        while True:
            x = randint(1, 3)
            y = randint(1, 3)
            if board[x - 1][y - 1] == '':
                break
    i = x - 1
    j = y - 1
    if board[i][j] != '':
        print("Enter row and column that hasnt already been chosen.")
        return True
    if turn % 2 == 0:
        board[i][j] = 'X'
    else:
        board[i][j] = 'O'
    return
def checkWin(board, ch, play):
    for i in range(3):
        if board[i][0] == ch and board[i][1] == ch and board[i][2] == ch:
            if play == 'player':
                print('Player ', ch, ' Wins!')
                return True
            if play == 'ai':
                print('Computer wins!')
                return True
    for i in range(3):
        if board[0][i] == ch and board[1][i] == ch and board[2][i] == ch:
            if play == 'player':
                print('Player ', ch, ' Wins!')
                return True
            if play == 'ai':
                print('Computer wins!')
                return True

    if (board[0][0] == ch and board[1][1] == ch and board[2][2] == ch) or (
        board[0][2] == ch and board[1][1] == ch and board[2][0] == ch):
        if play == 'player':
            print('Player ', ch, ' Wins!')
            return True
        if play == 'ai':
            print('Computer wins!')
            return True
    return False
print('AdjoinTheSpheres Main Menu')

while 1:
    print("1) New Game (2 player)")
    print("2) New Game (1 player vs computer)")
    print("3) Exit Game")
    choice = input("Select Option from the Menu: ")
    if choice not in ['1', '2', '3']:
        print("Please enter valid option")
        continue
    else:
        break

while (choice != '3'):
    while True:
        board = initialiseBoard()
# print("X plays first")
        turn = 0
        while turn < 9:
            if choice == '1':
                if (inputBoard(board, turn, 'player')):
                    continue
                elif choice == '2' and turn % 2 == 0:
                    if (inputBoard(board, turn, 'player')):
                        continue
                elif choice == '2' and turn % 2 == 1:
                    if (inputBoard(board, turn, 'ai')):
                        continue
                for i in range(3):
                    for j in range(3):
                        if board[i][j] == '':
                            print('[ ]', ' ', end='')
                        else:
                            print('[', board[i][j], ']', ' ', end='')
                        print()
                    if turn % 2 == 0:
                        if (checkWin(board, 'X', 'player')):
                            break
                    if turn % 2 == 1 and choice == '1':
                        if (checkWin(board, 'O', 'player')):
                            break
                        if turn % 2 == 1 and choice == '2':
                            if (checkWin(board, 'O', 'ai')):
                                break
                    turn = turn + 1
                    if turn == 9:
                        print("Its a draw! Everybody sucks!")
                x = input("Want to play again? Press 1 for yes, anything else to exit out.")
                if x == '1':
                    break
                else:
                    print("Thank you for playing!")
                    exit()
                choice = input("Select option\n1)Play against another player\n2)Play against computer\n3)Exit\n")

Update I have tweaked the load_board function a little bit:

   def load_map(self, the_board):
        board = []
        for i in range(self.height)
            board.append(['.']*self.width)
        for self.height in board:
            print(' '.join(self.height))
        self.game_board.append(board)
        return self.game_board
        pass
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.