Question

I'm working on the following:

Write a python program:

1. Write the definition of the function displaySubMenu that displays the following menu; this function doesn't collect the user's input; only display the following menu.:

      [S]top – Press 'S' to stop. 

2. Write the definition of the function setNextGenList that creates a pattern of next generation (tempGen) based on the current generation (currentGen); modify the tempGen based on the currentGen by applying the rules of Game of Life.

Conway's Game of Life Rules:

- The neighbors of a given cell are the cells that touch it vertically, horizontally, or diagonally.
- Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
- Any live cell with two or three live neighbours lives on to the next generation.
- Any live cell with more than three live neighbours dies, as if by overpopulation.
- Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

3. Create a loop to generate and next pattern automatically.

When executing your program, the following should happen:
a. Print the menu using the displayMenu function.
b. Initialize the tempGen using the setZeroList function.
c. Set the ‘U’ pattern in the tempGen using the setInitialPatternList function.
d. Copy the tempGen to the currentGen using the copyList function.
e. Print the currentGen using the displayList function.
f. When the user presses ‘P’, loop the following steps:
1). Print the menu using the displaySubMenu function.
2). Generate a next pattern using the setNextGenList function.
3). Copy the tempGen to the currentGen using the copyList function.
4). Print the currentGen using the displayList function.
g. When the user presses ‘S’, it will terminate the loop in step f, and reset the screen to the 'U' pattern.
h. When the user presses ‘Q’, it will terminate the program.

Examples of Outputs:

Press P to play. [P]lay [Q]uit Press Q to exit. ө000000000000 0000OOOOOOO0000OOOOOOOOO0000OOO ө00000000о0о0000OOOOOOOө000

Press S to stop [S]top ө0000 eө000OOOOOOO0000ODOOO00000 e000000e ө0000 eө000OOOOOOO0000ODOOO00000 e000000e ө0000 eө000OOOOO

Press S to stop. [S]top Ө00000000000000OOOOOOO000000OOOOOO000000OOOOOOӨ00000OOOOOO0 Ө00000000000000OOOOOOO000000OOOOOO00000

I'm stuck on creating a break from the loop using the 'S' key specifically without using input() as that would wait for the user to type it in. I'm trying to make it so that the loop continues until the user presses the specified key. This is what I have so far:

import random
import os
import time
import msvcrt

MAX_ROW = 30 #total number of rows
MAX_COL = 60 #total number of cols

currentGen = [[0]*MAX_COL for i in range(MAX_ROW)] #values to 0 using row*col
tempGen = [[0]*MAX_COL for i in range(MAX_ROW)] #values to 0 using row*col

def displayMenu(): #menu at top
    print("[P]lay - Press 'P' to play.\n[Q]uit - Press 'Q' to exit.\n")
  
def setZeroList(tempGen): #initializes list to 0
    for rows in range(MAX_ROW):
        for cols in range(MAX_COL):
            tempGen[rows][cols] = 0

def setInitialPatternList(tempGen): #creates random U shape
    row=random.randint(0,MAX_ROW-6)
    col=random.randint(0,MAX_COL-6)
    for iRow in range(row,row+6):
        tempGen[iRow][col] = tempGen[iRow][col+6] = 1 #left and right col of ones
    for iRow in range(col,col+7):
        tempGen[row+5][iRow] = 1 #bottom row of ones
  
def copyList(currentGen,tempGen): #copies tempList to currentList
    for iRow in range(MAX_ROW):
        for jCol in range(MAX_COL):
            currentGen[iRow][jCol] = tempGen[iRow][jCol]

def displayList(currentGen): #displays within limits with no spaces
    for iRow in range(MAX_ROW):
        for jCol in range(MAX_COL):
            print(currentGen[iRow][jCol], end='')
        print()

def displaySubMenu():
    print("[S]top - Press 'S' to stop\n")

def setNextGenList(nextGen,currentGen):
    RowIndex=[0,0,1,1,1,-1,-1,-1]
    ColIndex=[1,-1,-1,0,1,-1,0,1]
    copyList(currentGen,nextGen)
    neighborsCount = 0
    for iRow in range(MAX_ROW):
        for jCol in range(MAX_COL):
            neighborsCount=0
            for kNeighbors in range(8):
                neighborRow = iRow + RowIndex[kNeighbors]
                neighborCol = jCol + ColIndex[kNeighbors]
                if ((neighborRow >= 0) and (neighborRow < MAX_ROW)) and ((neighborCol >= 0) and (neighborCol < MAX_COL)):
                    if currentGen[neighborRow][neighborCol]==1:
                        neighborsCount+=1
            #Game of Life Rules:
            if currentGen[iRow][jCol]==1:   #live
                if neighborsCount<2:            #die by underpopulation
                    nextGen[iRow][jCol]=0
                elif neighborsCount<=3:          #survive
                    nextGen[iRow][jCol]=1
                else:                           #die by overpopulation
                    nextGen[iRow][jCol]=0
            else:                           #dead
                if neighborsCount==3:           #live by reproduction
                    nextGen[iRow][jCol]=1
    copyList(currentGen,nextGen)

def main():
    firstResponse = 'P'
    while True:
        os.system('cls')
        displayMenu()
        setZeroList(tempGen)
        setInitialPatternList(tempGen)
        copyList(currentGen,tempGen)
        displayList(currentGen)
        firstResponse=input().upper()
      
        while True and firstResponse=='P':
            os.system('cls')
            displaySubMenu()
            setNextGenList(tempGen,currentGen)
            displayList(currentGen)
            time.sleep(0.5)

            if (msvcrt.kbhit()):
                stopKey = ord(msvcrt.getch())
                if stopKey == 83:
                    break

        if firstResponse=='Q':
            exit()
          
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# do comment if any problem arises
# Code

#Your code has only one bug which is highlighted below


import random
import os
import time
import msvcrt

MAX_ROW = 30 # total number of rows
MAX_COL = 60 # total number of cols

currentGen = [[0]*MAX_COL for i in range(MAX_ROW)] # values to 0 using row*col
tempGen = [[0]*MAX_COL for i in range(MAX_ROW)] # values to 0 using row*col


def displayMenu(): # menu at top
print("[P]lay - Press 'P' to play.\n[Q]uit - Press 'Q' to exit.\n")


def setZeroList(tempGen): # initializes list to 0
for rows in range(MAX_ROW):
for cols in range(MAX_COL):
tempGen[rows][cols] = 0


def setInitialPatternList(tempGen): # creates random U shape
row = random.randint(0, MAX_ROW-6)
col = random.randint(0, MAX_COL-6)
for iRow in range(row, row+6):
# left and right col of ones
tempGen[iRow][col] = tempGen[iRow][col+6] = 1
for iRow in range(col, col+7):
tempGen[row+5][iRow] = 1 # bottom row of ones


def copyList(currentGen, tempGen): # copies tempList to currentList
for iRow in range(MAX_ROW):
for jCol in range(MAX_COL):
currentGen[iRow][jCol] = tempGen[iRow][jCol]


def displayList(currentGen): # displays within limits with no spaces
for iRow in range(MAX_ROW):
for jCol in range(MAX_COL):
print(currentGen[iRow][jCol], end='')
print()


def displaySubMenu():
print("[S]top - Press 'S' to stop\n")


def setNextGenList(nextGen, currentGen):
RowIndex = [0, 0, 1, 1, 1, -1, -1, -1]
ColIndex = [1, -1, -1, 0, 1, -1, 0, 1]
copyList(currentGen, nextGen)
neighborsCount = 0
for iRow in range(MAX_ROW):
for jCol in range(MAX_COL):
neighborsCount = 0
for kNeighbors in range(8):
neighborRow = iRow + RowIndex[kNeighbors]
neighborCol = jCol + ColIndex[kNeighbors]
if ((neighborRow >= 0) and (neighborRow < MAX_ROW)) and ((neighborCol >= 0) and (neighborCol < MAX_COL)):
if currentGen[neighborRow][neighborCol] == 1:
neighborsCount += 1
# Game of Life Rules:
if currentGen[iRow][jCol] == 1: # live
if neighborsCount < 2: # die by underpopulation
nextGen[iRow][jCol] = 0
elif neighborsCount <= 3: # survive
nextGen[iRow][jCol] = 1
else: # die by overpopulation
nextGen[iRow][jCol] = 0
else: # dead
if neighborsCount == 3: # live by reproduction
nextGen[iRow][jCol] = 1
copyList(currentGen, nextGen)


def main():
firstResponse = 'P'
while True:
os.system('cls')
displayMenu()
setZeroList(tempGen)
setInitialPatternList(tempGen)
copyList(currentGen, tempGen)
displayList(currentGen)
firstResponse = input().upper()

while True and firstResponse == 'P':
time.sleep(.5)

#When this sleep called before msvrt.kbhit() user enters s within this .5 s time due to which your program is not working

os.system('cls')
displaySubMenu()
setNextGenList(tempGen, currentGen)
displayList(currentGen)
if (msvcrt.kbhit()):
stopKey = ord(msvcrt.getch())
if stopKey == 83 or stopKey == 115:
break

if firstResponse == 'Q':
exit()


main()

Output:

[P]lay - Press P to play. [Q]uit - Press Q to exit. 000000000000000000000000000000000000000000000000000000000000 00000000

Add a comment
Know the answer?
Add Answer to:
I'm working on the following: Write a python program: 1. Write the definition of the function...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • Write in Python This program: 1. Correct the compute_cells_state function which receives as parameter an array...

    Write in Python This program: 1. Correct the compute_cells_state function which receives as parameter an array of 2-dimensional booleans. The table is indexed online then in column.    A cell is called "alive" if the Boolean is true otherwise it is said that it is "dead".    Each cell to 8 "neighbors" (the 4 adjacent cells and the 4 cells diagonally)    The function modifies each cell according to the following rule:      - if the cell has 2 or 3 living neighbors she...

  • The following function computes by summing the Taylor series expansion to n terms. Write a program...

    The following function computes by summing the Taylor series expansion to n terms. Write a program to print a table of using both this function and the exp() function from the math library, for x = 0 to 1 in steps of 0.1. The program should ask the user what value of n to use. (PLEASE WRITE IN PYTHON) def taylor(x, n): sum = 1 term = 1 for i in range(1, n): term = term * x / i...

  • USE THE PYTHON ONLY Sudoku Game Check Please write a Python program to check a Sudoku...

    USE THE PYTHON ONLY Sudoku Game Check Please write a Python program to check a Sudoku game and show its result in detail. This is an application program of using 2-dimensional arrays or lists. Each array or list is a game board of 9 x 9. Your program must check the 9 x 9 game board, and report all the problems among 9 rows, 9 columns, and 9 squares. As you can see, you must pre-load the following four games...

  • Python 3: Please follow the respective rubric for the following function definition. Rubric: Rectangle Shape You...

    Python 3: Please follow the respective rubric for the following function definition. Rubric: Rectangle Shape You should implement the following functions to print a rectangle shape. • print_rectangle(length, width, fillChar, hollow). This function will use draw_shape_line() function to print a rectangle shape with the given length and width, If the hollow is true, the shape will be hollow rectangle, otherwise a filled rectangle. This function must not interact with the user. For example, the call print_rectangle(5, 10, '*', False) should...

  • how to make my code of python work probely my q is how to write a...

    how to make my code of python work probely my q is how to write a code to find the average actual water level, average error by using python and my program should be flexible where user can select the column no. If you can see in the main program, it asked which column to know the maximum or average, the column number is passed to the function. The function should look which column to do. #THIS PROGRAMMING IS ABLE...

  • You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people....

    You will create a PYTHON program for Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player is X and the other player is O. Players take turns placing their X or O. If a player gets three of his/her marks on the board in a row, column, or diagonal, he/she wins. When the board fills up with neither player winning, the game ends in a draw 1) Player 1 VS Player 2: Two players are playing the game...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT