import random
import tkinter as tk

class WumpusWorldGame:
    def __init__(self):
        self.grid_size = 8
        self.agent_position = [1, 1]
        self.agent_direction = "right"
        self.gold_position = self.generate_random_position()
        self.wumpus_position = self.generate_random_position()
        self.pit_positions = self.generate_random_pit_positions()
        self.score = 100
        self.lives = 3

    def generate_random_position(self):
        x = random.randint(1, self.grid_size)
        y = random.randint(1, self.grid_size)
        return [x, y]

    def generate_random_pit_positions(self):
        pit_positions = []
        for i in range(1, self.grid_size + 1):
            for j in range(1, self.grid_size + 1):
                if [i, j] != self.agent_position and [i, j] != self.gold_position:
                    if random.random() < 0.2:  # Adjust the probability here (0.2 means 20% chance)
                        pit_positions.append([i, j])
        return pit_positions

    def get_percept(self):
        percept = ["None", "None", "None", "None", "None"]
        if self.agent_position == self.gold_position:
            percept[2] = "Glitter"
        if self.agent_position in self.pit_positions:
            percept[1] = "Breeze"
            percept[4] = "Pit"
        if self.agent_position == self.wumpus_position:
            percept[0] = "Stench"
        
        # Check if the agent is one block away from a pit
        x, y = self.agent_position
        if (x + 1 <= self.grid_size and [x + 1, y] in self.pit_positions) or \
           (x - 1 >= 1 and [x - 1, y] in self.pit_positions) or \
           (y + 1 <= self.grid_size and [x, y + 1] in self.pit_positions) or \
           (y - 1 >= 1 and [x, y - 1] in self.pit_positions):
            percept[1] = "Breeze"
        
        # Check if the agent is one block away from the Wumpus
        if (x + 1 <= self.grid_size and [x + 1, y] == self.wumpus_position) or \
           (x - 1 >= 1 and [x - 1, y] == self.wumpus_position) or \
           (y + 1 <= self.grid_size and [x, y + 1] == self.wumpus_position) or \
           (y - 1 >= 1 and [x, y - 1] == self.wumpus_position):
            percept[0] = "Stench"
        
        return percept

    def move_forward(self):
        x, y = self.agent_position
        if self.agent_direction == "right" and x < self.grid_size:
            self.agent_position = [x + 1, y]
        elif self.agent_direction == "left" and x > 1:
            self.agent_position = [x - 1, y]
        elif self.agent_direction == "up" and y < self.grid_size:
            self.agent_position = [x, y + 1]
        elif self.agent_direction == "down" and y > 1:
            self.agent_position = [x, y - 1]

    def turn_left(self):
        directions = ["right", "up", "left", "down"]
        current_index = directions.index(self.agent_direction)
        self.agent_direction = directions[(current_index + 3) % 4]

    def turn_right(self):
        directions = ["right", "down", "left", "up"]
        current_index = directions.index(self.agent_direction)
        self.agent_direction = directions[(current_index + 1) % 4]

    def grab(self):
        if self.agent_position == self.gold_position:
            self.score += 100
            return True
        return False

    def release(self):
        pass

    def shoot(self):
        x, y = self.agent_position
        if (self.agent_direction == "right" and x < self.grid_size) or \
           (self.agent_direction == "left" and x > 1) or \
           (self.agent_direction == "up" and y < self.grid_size) or \
           (self.agent_direction == "down" and y > 1):
            if self.wumpus_position == [x + 1, y] and self.agent_direction == "right":
                self.score -= 10
                return True
            elif self.wumpus_position == [x - 1, y] and self.agent_direction == "left":
                self.score -= 10
                return True
            elif self.wumpus_position == [x, y + 1] and self.agent_direction == "up":
                self.score -= 10
                return True
            elif self.wumpus_position == [x, y - 1] and self.agent_direction == "down":
                self.score -= 10
                return True
        return False

    def play_game(self):
        while True:
            percept = self.get_percept()
            print("Percept:", percept)
            print("Score:", self.score)
            print("Lives:", self.lives)
            action = input("Enter action: ")
            if action == "left":
                self.turn_left()
            elif action == "right":
                self.turn_right()
            elif action == "forward":
                self.move_forward()
            elif action == "grab":
                if self.grab():
                    print("You found the gold! You win!")
                    break
            elif action == "release":
                self.release()
            elif action == "shoot":
                if self.shoot():
                    print("You killed the Wumpus!")
                    # Deduct score for shooting
                    # Add code to display a message box or update GUI accordingly
                else:
                    print("No Wumpus nearby.")
                    # Add code to display a message box or update GUI accordingly
            else:
                print("Invalid action. Try again.")

            if self.agent_position in self.pit_positions:
                print("You fell into a pit! Game over.")
                self.score -= 10
                self.lives -= 1
                if self.lives <= 0:
                    print("Out of lives. Game over.")
                    break
                else:
                    self.reset_game()
            elif self.agent_position == self.wumpus_position:
                print("You were eaten by the Wumpus! Game over.")
                self.lives -= 1
                if self.lives <= 0:
                    print("Out of lives. Game over.")
                    break
                else:
                    self.reset_game()

    def reset_game(self):
        self.agent_position = [1, 1]
        self.agent_direction = "right"
        self.gold_position = self.generate_random_position()
        self.wumpus_position = self.generate_random_position()
        self.pit_positions = self.generate_random_pit_positions()

# Create the game instance
game = WumpusWorldGame()
game.play_game()

# GUI implementation
class WumpusWorldGUI(tk.Tk):
    def _init_(self, game):
        super()._init_()
        self.title("Wumpus World Game")
        self.game = game
        
        # Create grid buttons
        self.grid_buttons = []
        for i in range(game.grid_size):
            row_buttons = []
            for j in range(game.grid_size):
                button = tk.Button(self, width=10, height=5)
                button.grid(row=i, column=j)
                row_buttons.append(button)
            self.grid_buttons.append(row_buttons)
        
        # Create action buttons
        self.action_buttons = []
        actions = ["left", "right", "forward", "grab", "release", "shoot"]
        for action in actions:
            button = tk.Button(self, text=action.capitalize(), width=10)
            button.grid(row=game.grid_size + 1, column=actions.index(action))
            self.action_buttons.append(button)
        
        # Bind action buttons to corresponding functions
        self.action_buttons[0].config(command=self.turn_left)
        self.action_buttons[1].config(command=self.turn_right)
        self.action_buttons[2].config(command=self.move_forward)
        self.action_buttons[3].config(command=self.grab_gold)
        self.action_buttons[4].config(command=self.release_gold)
        self.action_buttons[5].config(command=self.shoot_arrow)

    def update_grid(self):
        percept = self.game.get_percept()
        for i in range(self.game.grid_size):
            for j in range(self.game.grid_size):
                if [i+1, j+1] == self.game.agent_position:
                    text = "Agent"
                elif [i+1, j+1] == self.game.gold_position:
                    text = "Gold"
                elif [i+1, j+1] == self.game.wumpus_position:
                    text = "Wumpus"
                elif [i+1, j+1] in self.game.pit_positions:
                    text = "Pit"
                else:
                    text = ""
                
                if percept[0] == "Stench" and [i+1, j+1] != self.game.agent_position:
                    text += "\nStench"
                if percept[1] == "Breeze" and [i+1, j+1] != self.game.agent_position:
                    text += "\nBreeze"
                if percept[2] == "Glitter" and [i+1, j+1] == self.game.agent_position:
                    text += "\nGlitter"
                
                self.grid_buttons[i][j].config(text=text)

    def turn_left(self):
        self.game.turn_left()
        self.update_grid()

    def turn_right(self):
        self.game.turn_right()
        self.update_grid()

    def move_forward(self):
        self.game.move_forward()
        self.update_grid()

    def grab_gold(self):
        if self.game.grab():
            print("You found the gold! You win!")
            # Add code to display a message box or update GUI accordingly
        else:
            print("No gold here.")
            # Add code to display a message box or update GUI accordingly

    def release_gold(self):
        self.game.release()
        # Add code to display a message box or update GUI accordingly

    def shoot_arrow(self):
        if self.game.shoot():
            print("You killed the Wumpus!")
            # Deduct score for shooting
            # Add code to display a message box or update GUI accordingly
        else:
            print("No Wumpus nearby.")
            # Add code to display a message box or update GUI accordingly

# Create and run the GUI
game = WumpusWorldGame()
gui = WumpusWorldGUI(game)
gui.update_grid()
gui.mainloop() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling