iT邦幫忙

0

(for-break 問題詢問) 使用了break但是卻無法停止for迴圈。我在條件判斷式裡用了一個break,但是當條件判斷為True,進到裡面後,程式像是忽略break依樣,繼續下一個數字。

ImQQ 2019-05-02 20:34:502347 瀏覽
  • 分享至 

  • twitterImage

( 謝謝留言幫我優化程式以及教學 太感謝了>< )
根據下面的回答 再檢查一下自己的程式 我知道我錯哪了 ....-.-a
錯在turn一直等於0 然後沒跳出while a() 迴圈.....
我真的找好久....
謝謝前面的回答 >
<
感激 >_<
(下次會用正確的方式貼程式碼 :D )

( getcopy(nb)、isWin(copy,computerLetter、isTie(copy)、 drawBoard(nb) 是前面自己定義的function ,因為怕太長所以只放了覺得有問題的區塊 )
nn='mm'

      for i in [0,1,2,3,4,5,6,7,8,9]:
          if nn!='gg':
             copy=getCopy(nb)
             if copy[i]==' ':
                copy[i]=computerLetter
                
                if isWin(copy,computerLetter):
                   int(i) 
                   nb[i]=computerLetter
                   drawBoard(nb)
                   print('The AI is win~')
                   print('============')
                   print(i)
                   print('=============')
                   nn='gg'                      
                   break #<<<這個break只是結束掉for這個迴圈
                   
                      
                  

                else :
                      if isTie(copy):
                         print('It is tie!!!')
                         drawBoard(nb)
                         nn='gg'
                         break #<<<這個break只是結束掉for這個迴圈

https://ithelp.ithome.com.tw/upload/images/20190502/201173451ahKMjIa0L.png
以上是 isWin 是True後印出的....QQ (可能跟其他區塊有關嗎....我真的找很久了(用print的方式)..)

(這是小時候玩 'x' 'o' 的遊戲,先連成一條線就贏了。我是先看了別人寫的tic tac toe 然後再自己寫一遍的,但是就在那裏卡住了@@(書本裡的邏輯跟我不一樣,所以寫的也不一樣,無法從中找出錯在哪...QQ))

下面是完整的程式碼:
https://ithelp.ithome.com.tw/upload/images/20190502/20117345RA73iFNE7N.png

下面的 return(b[1]==L....b[7]==L)是一整行,因為拍照拍不進去所以把它弄成一行一行@@
https://ithelp.ithome.com.tw/upload/images/20190502/20117345sjHP730b5Z.png

下面的 last check() 後面沒有用到,應該沒影響,但是為了完整還是放上來@@

https://ithelp.ithome.com.tw/upload/images/20190502/20117345KFTftcIUKU.png

從下面開始是主程式 ( 會有重複的部分 因為python 是用縮行來決定內外迴圈@@ 怕會不知道哪個迴圈在外或內 所以重複拍@@)
https://ithelp.ithome.com.tw/upload/images/20190502/20117345Cg5y1UA5By.png
https://ithelp.ithome.com.tw/upload/images/20190502/2011734549prH1i8Pu.png
https://ithelp.ithome.com.tw/upload/images/20190502/20117345a5SGUrDJNV.png
https://ithelp.ithome.com.tw/upload/images/20190502/20117345Nep7N6ASxH.png
https://ithelp.ithome.com.tw/upload/images/20190502/20117345ECPSGfNr6X.png

寫的有點雜....QQ
然後謝謝前面的回復 >_<

ccutmis iT邦高手 2 級 ‧ 2019-05-02 21:14:36 檢舉
很簡單 就是 isWin(copy,computerLetter) 跟 isTie(copy) 一直沒有為 True 而已,
舉個例:
for i in [0,1,2,3,4,5,6,7,8,9]:
 if i>5: break
 print(i)
結果會印出 0,1,2,3,4,5 break不會沒有作用...
善用print列出自訂函式返回值去抓原因吧
ccutmis iT邦高手 2 級 ‧ 2019-05-02 22:40:55 檢舉
恩...那不然你就把完整的代碼貼上來吧,你這樣問真的沒人能幫你,1)邏輯部份可能有問題 2)自訂函式返回值是什麼沒人知道
ccutmis iT邦高手 2 級 ‧ 2019-05-03 10:11:55 檢舉
老實說那些代碼看起來令人有點頭暈 還好你解決了^^"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
ccutmis
iT邦高手 2 級 ‧ 2019-05-03 15:47:40
最佳解答

依照樓主要寫的遊戲,我用自己想的邏輯加上一些樓主寫好的函式,做出來的功能應該是差不多的東西,有些寫法可以再優化不過已經比樓主貼上來的程式碼少了三分之一左右,貼上來給樓主參考,寫程式能簡化的儘量簡化,能用一個陣列解決的,就不要用到第二個陣列...

import os,random

def drawBoard(board):
	print("┌──┬──┬──┐")
	print("│  "+board[0]+" │  "+board[1]+" │  "+board[2]+" │")
	print("├──┼──┼──┤")
	print("│  "+board[3]+" │  "+board[4]+" │  "+board[5]+" │")
	print("├──┼──┼──┤")
	print("│  "+board[6]+" │  "+board[7]+" │  "+board[8]+" │")
	print("└──┴──┴──┘")

def whoGo1st():
	a=random.randint(0,1)
	if a==0:
		print('You go 1st.')
		return 0
	else:
		print('Com go 1st.')
		return 1

def isWin(b,L):
	return (b[1]==L and b[2]==L and b[0]==L) or (b[4]==L and b[5]==L and b[3]==L) or (b[7]==L and b[8]==L and b[6]==L) or (b[0]==L and b[3]==L and b[6]==L) or (b[1]==L and b[4]==L and b[7]==L) or (b[2]==L and b[5]==L and b[8]==L) or (b[0]==L and b[4]==L and b[8]==L) or (b[2]==L and b[4]==L and b[6]==L)

def change_player():
	global c_flag
	c_flag = 1 if c_flag==0 else 0

def check_moves(arg):
	global my_arr,my_choice,c_flag,com_choice,steps
	if arg>9 or arg<1:
		return False
	elif my_arr[arg-1]=='O' or my_arr[arg-1]=='X':
		return False
	else:
		if c_flag==0:
			my_arr[arg-1]=my_choice
		else:
			my_arr[arg-1]=com_choice
		steps=steps+1
		return True

def do_move(player):
	while 1:
		print('You['+my_choice+']  Com:['+com_choice+']')
		if player==0:
			tmp_input=input('Input a number to choose the place:(1-9)')
			if tmp_input.upper()=='Q': exit()
		else:
			tmp_input=random.randint(0, 9)
		if check_moves(int(tmp_input)):
			break

def do_my_choice():
	global my_choice,com_choice
	while 1:
		my_choice=input("Do you want 'O' or 'X'?").upper()
		if my_choice=='O' or  my_choice=='X': 
			com_choice= 'X' if my_choice=='O' else 'O'
			break
		if my_choice=='Q': exit()

def cls(): os.system("cls")

def game_init():
	global my_arr,my_choice,com_choice,c_flag,steps
	my_arr=['1','2','3','4','5','6','7','8','9']
	my_choice=''
	com_choice=''
	steps=0
	c_flag=-1
def game_start():
	global c_flag,my_arr,my_choice,com_choice,steps
	game_init()
	cls()
	print('Welcome to Tic Tac Toe!!!')
	c_flag=whoGo1st()
	do_my_choice()
	while 1:
		cls()
		drawBoard(my_arr)
		if isWin(my_arr,my_choice):
			print("U WIN")
			break
		elif isWin(my_arr,com_choice):
			print("Com WIN")
			break
		elif steps==9:
			print("DRAWN GAME!")
			break
		do_move(c_flag)
		change_player()

def ask_play_again():
	return True if input("PLAY AGAIN?( Y or N )...").upper()=='Y' else False

if __name__ == '__main__':
	while 1:
		game_start()
		if ask_play_again()==False:
			print("Bye!!!")
			break

https://ithelp.ithome.com.tw/upload/images/20190503/20028574r2lhE1H9Ga.png

0
小魚
iT邦大師 1 級 ‧ 2019-05-02 23:02:11

你的程式碼不完整,
所以有可能問題不是如你寫的那樣,
另外break只能跳出一個迴圈,
如果你有兩層迴圈,
break只會跳出裡面那層,
而外面那層還是會繼續進行.

小魚 iT邦大師 1 級 ‧ 2019-05-03 09:08:12 檢舉

程式碼不要貼圖,
請用一開始那種程式碼標籤,
貼文字內容上來.

我要發表回答

立即登入回答