スライドパズルを作るpythonのコードが分かりません
pythonでスライドパズルが作れると聞き、インターネットで調べてみたところ以下のコードを見つけました。python初心者のため何をどうしようとしているのか理解出来なかった部分があり、意味を解説していただきたいです。
###分からない箇所
54-60行目のempty_spaceに関する処理:ここでの処理がパズルのパネルをどう動かすかに関わっているのでしょうか?もしそうなら、どういう条件付けをしているのか詳しく教えていただきたいです。
piece(i,j)は動かしたい数値の座標だと理解してます。しかしpiece[0]-1のように、マイナスの部分はどこからきたのかが分かりません。
1. 0. import random, sys 2. def board(): 3. '''Make matrix board of random numbers''' 4. list1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] 5. random.shuffle(list1) 6. matrix = [] 7. while list1 !=[]: 8. matrix.append(list1[:4]) 9. list1 = list1[4:] 10. return matrix 11. def zero(board): 12. '''function to find where the zero is''' 13. empty_space = None 14. for x,item in enumerate(board): 15. for y,item in enumerate(board): 16. if board[x][y] == 0: 17. empty_space = (x,y) 18. return empty_space 19. def draw_board(board): 20. '''function to draw the board''' 21. print('\n\t+-------+-------+-------+-------|') 22. for x,item in enumerate(board): 23. for y,item in enumerate(board): 24. if board[x][y] == 0: 25. print('\t| XX' , end='') 26. else: 27. print('\t| ' + '{:02d}' .format(board[x][y]), end=' ') 28. print('\n\t+-------+-------+-------+-------|') 29. def ask_number(board): 30. ''' function to ask for the number to move''' 31. num = input('\nplease type the number of the piece to move : ( q ) to quit ') 32. if num in ['q','Q']: 33. print('\n\ngame over ') 34. sys.exit() 35. num = int(num) 36. piece = () 37. for i,item in enumerate(board): 38. for j,item in enumerate(board): 39. if num == board[i][j]: 40. piece = (i,j) 41. return piece , num 42. def game(): 43. '''Run the game logic''' 44. matrix = board() 45. empty_space = zero(matrix) 46. game_on = True 47. move = 0 48. while game_on: 49. draw_board(matrix) 50. piece,num = ask_number(matrix) 51. if num > 15: 52. print('illegal move , try again ') 53. else: 54. if(empty_space==(piece[0]-1,piece[1]))\ 55. or(empty_space==(piece[0]+1,piece[1]))\ 56. or(empty_space==(piece[0],piece[1]-1))\ 57. or(empty_space==(piece[0],piece[1]+1)): 58. matrix[empty_space[0]][empty_space[1]]=num 59. matrix[piece[0]][piece[1]]=0 60. empty_space=(piece[0],piece[1]) 61. move = move +1 62. print() 63. print('you have made ',move , 'moves so far ') 64. print(2*'\n') 65. else: 66. print('illegal move , try again ') 67. if __name__ == '__main__': 68. game()
コード出典
https://www.daniweb.com/programming/software-development/threads/493259/slide-puzzle-game
このサイトの一番下のコメントから引用させていただきました。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/11 13:56