Artificial Intelligence-Puzzle Game

Puzzle Game in Python -Artificial Intelligence

 

Puzzle Game in Python with Source code. We can develop the puzzle game using depth first search in an Artificial Intelligence manner.In this code we can evaluate the steps of the user that in how much steps user reached to the desired destination and shows the output in how many steps he reached the final destination.

 

 

Tools & Technologies:

  1. Use the following code and just paste it in the compile like idle and Anaconda.
  2. Take care of the indentation of the code asĀ  python requires the indentation of its code.

 

Source Code:

# -*- coding: utf-8 -*-
“””
Created on Wed Oct 10 10:30:35 2018

@author: hp
“””
def id_dfs(puzzle, goal, get_moves):
import itertools

def dfs(route, depth):
if depth == 0:
return
if route[-1] == goal:
return route
for move in get_moves(route[-1]):
if move not in route:
next_route = dfs(route + [move], depth – 1)
if next_route:
return next_route

for depth in itertools.count():
route = dfs([puzzle], depth)
if route:
return route

def num_matrix(rows, cols, steps=25):
import random

nums = list(range(1, rows * cols)) + [0]
goal = [ nums[i:i+rows] for i in range(0, len(nums), rows) ]

get_moves = num_moves(rows, cols)
puzzle = goal
for steps in range(steps):
puzzle = random.choice(get_moves(puzzle))

return puzzle, goal

def num_moves(rows, cols):
def get_moves(subject):
moves = []

zrow, zcol = next((r, c)
for r, l in enumerate(subject)
for c, v in enumerate(l) if v == 0)

def swap(row, col):
import copy
s = copy.deepcopy(subject)
s[zrow][zcol], s[row][col] = s[row][col], s[zrow][zcol]

return s

# north
if zrow > 0:
moves.append(swap(zrow – 1, zcol))
# east
if zcol < cols – 1:
moves.append(swap(zrow, zcol + 1))
# south
if zrow < rows – 1:
moves.append(swap(zrow + 1, zcol))
# west
if zcol > 0:
moves.append(swap(zrow, zcol – 1))

return moves
return get_moves

puzzle, goal = num_matrix(3, 3) # ([[1, 5, 2], [4, 8, 0], [7, 6, 3]], [[1, 2, 3], [4, 5, 6], [7, 8, 0]])
solution = id_dfs(puzzle, goal, num_moves(3, 3))
moves=0;
for s in solution:
for data in s:
print(data)
print(“”)
moves+=1
print(“Total Moves In game”, moves)

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *