簡體   English   中英

python中的遞歸游戲問題

[英]Recursive Game issue in python

我正在使用python創建Minesweeper的版本,並且遇到了一個小問題。 在這段代碼中:

if winGame(mines):
        printWorld(gameMap)
        print 'You Win!'
        answer = raw_input('Would you like to play again?')
        if answer == 'y':
            minesweeper()
        else:
            print 'Thanks for playing!'
            break

它再次調用minesweeper函數,從而重新開始游戲。 這段代碼位於True:循環以及游戲代碼的其余部分內。 唯一的問題是,如果游戲重新開始然后贏了,並且說您不想再玩,它不會中斷循環。 我認為這與我使用遞歸再次調用該函數有關。 目前唯一可行的方法是使用sys.exit(),但如果可行的話,我希望有一個更合理的解決方案。

這是完整的代碼:

#Minesweeper Game

#difficulty levels
#make it look better text based

from random import *
import sys

gameMap = '''
#123456789#
1?????????1
2?????????2
3?????????3
4?????????4
#123456789#'''

row = 0
col = 0
coord = []
response = ''
numMines = 5
mines = []
answer = ''


#This runs the game
def minesweeper():

    global gameMap
    global row
    global col
    global coord
    global mines
    global response
    global answer

    #resets the gameboard after replaying.
    gameMap = '''
#123456789#
1?????????1
2?????????2
3?????????3
4?????????4
#123456789#'''

    #generates the mines
    generateMines()

    #converts the world into a list of lists. exception is for when playing again since
    #it would try to convert it to a list of lists again
    try:
        initWorld()
    except Exception, e:
        pass

    #main loop of the game.
    while True:                      

        #checks to see if you won the game
        if winGame(mines):
            printWorld(gameMap)
            print 'You Win!'
            answer = raw_input('Would you like to play again?')
            if answer == 'y':
                minesweeper()
            else:
                print 'Thanks for playing!'
                break

        #joins the list together so it can be printed
        printWorld(gameMap)
        print mines

        #gets user input and converts it to an int, then adds coords to a list
        getCoord()        

        #asks user what they want to do
        clearOrFlag()

        if response.lower() == 'c':
            if isMine(mines):
                answer = raw_input('Would you like to play again?')
                if answer == 'y':
                    minesweeper()
                else:
                    print 'Thanks for playing!'
                    break
            else:
                clearSpace(mines)
                print '\n'
        elif response.lower() == 'f':
            flagSpace()
            print '\n'

#randomly generates the mines and checks for duplicates
def generateMines():
    global numMines
    global mines
    i = 0
    mines = []

    while i < numMines:
        mines.append([randint(1,4),randint(1,9)])
        i += 1

    if checkDuplicateMines(mines):
        generateMines()

#gets coordinates from the user
def getCoord():

    global row
    global col
    global coord
    global gameMap

    row = 0
    col = 0
    coord = []

    try:
        row = raw_input('Enter an Row: ')
        row = int(row)
        col = raw_input('Enter a Column: ')
        col = int(col)
    except ValueError:
        print 'Invalid Coordinates \n'
        getCoord()

    coord.append(row)
    coord.append(col)

def isMine(mines):

    global coord
    global gameMap

    for x in mines:
            if coord == x:
                showSolution(mines, gameMap)
                return True

#asks user if they want to clear or flag a space
def clearOrFlag():

    global response

    response = raw_input("Clear (c), Flag/Unflag (f)")

#clears a space. if it's a mine, the player loses. If not it will write the
#number of surrounding mines to the space. Might break this up later.
def clearSpace(mines):

    #checks to see if selected square is a ? (playable). 
    global gameMap
    global row
    global col
    global coord

    if gameMap[row][col] == '?' or gameMap[row][col] == 'F':                       
        gameMap[row][col] = str(countMines(mines))

#flags a space, or unflags it if already flagged.
def flagSpace():

    global gameMap
    global row
    global col

    try:
        if gameMap[row][col] == '?' :
            gameMap[row][col] = 'F'
        elif gameMap[row][col] == 'F':
            gameMap[row][col] = '?'
    except Exception, OutOfBounds:
        print 'Invalid Coordinates \n'

#Prints the world
def printWorld(gameMap):

    #just prints spaces to keep things tidy
    print '\n' * 100 

    for row in gameMap:
        print ' '.join(row)
        print '\n'

    print '\n'

#initializes the world so it can be printed
def initWorld():

    global gameMap

    # convert the gamemap into a list of lists
    gameMap = gameMap.split('\n')
    del gameMap[0]

    for index in range(0, len(gameMap)):
        gameMap[index] = list(gameMap[index])

#prints the gameBoard with all of the mines visible
def showSolution(mines, gameMap):

    for x in mines:
        gameMap[x[0]][x[1]] = 'M' 


    printWorld(gameMap)
    print 'You Lose'

#counts the number of surrounding mines in a space
def countMines(mines):
    global row
    global col
    count = 0

    #theres probably a much better way to do this    
    for x in mines:
        if [row+1,col] == x:
            count += 1
        if [row-1,col] == x:
            count += 1
        if [row,col+1] == x:
            count += 1
        if [row,col-1] == x:
            count += 1
        if [row+1,col+1] == x:
            count += 1
        if [row+1,col-1] == x:
            count += 1
        if [row-1,col+1] == x:
            count += 1
        if [row-1,col-1] == x:
            count += 1

    return count

#counts the number of flags on the board
def countFlags(mines):

    global gameMap
    numFlags = 0

    for i in range (0, len(gameMap)):
        for j in range (1, len(gameMap[0])-1):
            if gameMap[i][j]=='F':
                numFlags += 1

    if numFlags == len(mines):
        return True
    else:
        return False

#counts the number of mines flagged
def minesFlagged(mines):

    global gameMap
    count = 0

    for x in mines:
        if gameMap[x[0]][x[1]] == 'F':
            count += 1

    if count == numMines:
        return True
    else:
        return False

#checks to see if there were duplicate mines generated
def checkDuplicateMines(mines):

    mines.sort()

    for x in range(0, len(mines)-1):
        if mines[x] == mines[x+1]:
            return True
        x += 1

    return False

#checks to see if player won the game
def winGame(mines):

    if countFlags(mines):
        if minesFlagged(mines):
            return True
    else:
        return False

minesweeper()

如果要使用遞歸,請返回函數調用,而不僅僅是調用它。

if winGame(mines):
        printWorld(gameMap)
        print 'You Win!'
        answer = raw_input('Would you like to play again?')
        if answer == 'y':
            return minesweeper()
        else:
            print 'Thanks for playing!'
            return

這樣,當您的一個遞歸函數結束時,它向上一個函數返回None ,然后又向上一個函數返回None ,依此None ,直到最后一個調用return ,從而結束了整個遞歸循環。

它可能不是解決此問題的最佳解決方案(請看MathieuW的答案,基本上也是如此),但它適用於任何情況,並且主要用於遞歸函數。

如果您不回答“ y”,它確實會打破循環。

但是,如果您玩了N個游戲,它只會中斷第N個游戲的循環,您將返回第(N-1)個函數調用的循環。

對於實際的解決方案,我同意您已經實施的AshRj評論。

這是仍然使用您以前的設計(但不太正確)的另一種解決方案,只是移動中斷。

if winGame(mines):
        printWorld(gameMap)
        print 'You Win!'
        answer = raw_input('Would you like to play again?')
        if answer == 'y':
            minesweeper()
        else:
            print 'Thanks for playing!'
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM