Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- from qiskit import QuantumCircuit, Aer, execute, transpile
- import tkinter as tk
- import random
- # Define the size of the grid (10x10 grid using 100 qubits)
- grid_size = 100 # 10x10 grid
- qc = QuantumCircuit(grid_size, grid_size)
- # Player snake body, represented as a list of positions (initially just the head)
- snake_body = [0] # Start with the snake having just one segment (head)
- direction = "Right" # Default direction
- # Food (red block) initial random position
- food_position = random.randint(0, grid_size - 1)
- # Counter for food eaten
- food_eaten_count = 0 # Start with zero food eaten
- # Random toggle state
- random_enabled = False # Start with randomness disabled
- # Noise simulation state
- simulate_noise = False # Start with noise simulation disabled
- # Function to toggle randomness on and off
- def toggle_randomness(event):
- global random_enabled
- random_enabled = not random_enabled # Toggle between True and False
- if random_enabled:
- print("Randomness Enabled")
- else:
- print("Randomness Disabled")
- # Function to toggle noise simulation on and off
- def toggle_noise_simulation(event):
- global simulate_noise
- simulate_noise = not simulate_noise
- if simulate_noise:
- print("Noise Simulation Enabled")
- log_noise_event("Noise Simulation Enabled")
- else:
- print("Noise Simulation Disabled")
- log_noise_event("Noise Simulation Disabled")
- # Function to apply quantum noise simulation
- def apply_quantum_noise():
- if simulate_noise:
- # 10% chance of random direction change
- if random.random() < 0.1:
- new_direction = random.choice(["Left", "Right", "Up", "Down"])
- event_message = f"Quantum Noise! Random direction change to {new_direction}."
- print(event_message)
- log_noise_event(event_message) # Log the event
- return new_direction
- # 5% chance of teleporting snake to a random grid position (quantum glitch!)
- if random.random() < 0.05:
- event_message = "Quantum Glitch! Snake teleported."
- print(event_message)
- log_noise_event(event_message) # Log the event
- return 'teleport'
- return None
- # Function to clear the grid
- def clear_grid(circuit):
- """Clears the entire grid by resetting all qubits to 0."""
- for qubit in range(grid_size):
- circuit.reset(qubit) # Reset all qubits to |0⟩ state
- # Function to move the snake
- def move_snake(circuit, direction):
- global snake_body, food_position, food_eaten_count
- # Calculate the new head position based on the direction
- head = snake_body[0]
- if direction == 'Right' and head % 10 != 9:
- new_head = head + 1
- elif direction == 'Left' and head % 10 != 0:
- new_head = head - 1
- elif direction == 'Up' and head >= 10:
- new_head = head - 10
- elif direction == 'Down' and head < 90:
- new_head = head + 10
- else:
- # Snake has hit the wall, end the game
- print("Game Over! Hit the wall.")
- root.quit()
- return
- # Check for collision with itself
- if new_head in snake_body:
- print("Game Over! Hit itself.")
- root.quit()
- return
- # Move the snake: add new head and remove the tail unless it just ate food
- snake_body.insert(0, new_head)
- if new_head == food_position:
- # Snake has eaten the food
- food_position = random.randint(0, grid_size - 1)
- food_eaten_count += 1
- food_counter_label.config(text=f"Food Eaten: {food_eaten_count}")
- else:
- # Remove the last segment (tail) if no food was eaten
- snake_body.pop()
- # Update the quantum circuit to reflect the new snake position
- update_grid(circuit)
- # Function to randomly change direction with 70% probability
- def random_change_direction():
- if random_enabled and random.random() < 0.7: # 70% chance to change direction randomly
- return random.choice(["Left", "Right", "Up", "Down"])
- else:
- return None # No change if randomness is disabled
- # Function to log noise events to the secondary window
- def log_noise_event(event):
- log_textbox.insert(tk.END, event + '\n') # Insert event into the text box
- log_textbox.see(tk.END) # Scroll to the end to always show the latest event
- # Set up the main game GUI to visualize the grid
- root = tk.Tk()
- root.title("Quantum Snake Game with Food Eaten Counter and Grid State")
- # Define grid dimensions (10x10)
- rows = 10
- cols = 10
- cell_size = 50 # Size of each cell in pixels
- # Create a canvas to draw the grid
- canvas = tk.Canvas(root, width=cols * cell_size, height=rows * cell_size)
- canvas.pack()
- # Create a label to display the grid state
- grid_state_label = tk.Label(root, text="Grid State: ")
- grid_state_label.pack()
- # Create a label to display the food eaten counter
- food_counter_label = tk.Label(root, text=f"Food Eaten: {food_eaten_count}")
- food_counter_label.pack()
- # Draw the grid on the canvas
- cells = []
- for row in range(rows):
- row_cells = []
- for col in range(cols):
- x1 = col * cell_size
- y1 = row * cell_size
- x2 = x1 + cell_size
- y2 = y1 + cell_size
- cell = canvas.create_rectangle(x1, y1, x2, y2, fill="white")
- row_cells.append(cell)
- cells.append(row_cells)
- # Create the secondary window for logging quantum noise events
- log_window = tk.Toplevel(root)
- log_window.title("Quantum Noise Log")
- log_textbox = tk.Text(log_window, width=50, height=10)
- log_textbox.pack()
- # Function to update the grid based on the quantum circuit results
- def update_grid(circuit):
- clear_grid(circuit) # Clear the quantum circuit grid
- # Draw the snake body (blue)
- for segment in snake_body:
- circuit.x(segment)
- # Draw the food block (red)
- circuit.x(food_position)
- # Measure all qubits to see the final state of the grid
- qc.measure([i for i in range(grid_size)], [i for i in range(grid_size)])
- # Use the QASM simulator to run the circuit
- simulator = Aer.get_backend('qasm_simulator')
- job = execute(qc, simulator, shots=1) # One shot to measure the final state
- result = job.result()
- # Get the results
- counts = result.get_counts(qc)
- bitstring = list(counts.keys())[0] # Get the measured bitstring (grid state)
- # Update the GUI grid based on the bitstring
- for i, bit in enumerate(bitstring):
- row = i // 10
- col = i % 10
- if i in snake_body:
- canvas.itemconfig(cells[row][col], fill="blue") # Snake (blue)
- elif i == food_position:
- canvas.itemconfig(cells[row][col], fill="red") # Food (red)
- else:
- canvas.itemconfig(cells[row][col], fill="white") # Empty cell
- # Update the label with the current grid state (bitstring)
- grid_state_label.config(text=f"Grid State: {bitstring}")
- # Print the grid state to the console (optional)
- print(f"Grid State: {bitstring}")
- # Function to automatically move the snake in the current direction
- def auto_move():
- global direction
- # Apply noise simulation to see if a random event occurs
- noise_event = apply_quantum_noise()
- if noise_event == 'teleport':
- # Quantum glitch: teleport the snake's head to a random grid position
- snake_body[0] = random.randint(0, grid_size - 1)
- elif noise_event:
- # Apply random direction change due to noise
- direction = noise_event
- # Randomly change direction with a 70% chance if randomness is enabled
- new_direction = random_change_direction()
- if new_direction:
- direction = new_direction # Update direction to a random one
- move_snake(qc, direction) # Move the snake according to the current direction
- root.after(500, auto_move) # Repeat every 500ms to keep moving
- # Keyboard event handlers to change direction
- def on_key_press(event):
- global direction
- if event.keysym == 'Right':
- direction = 'Right'
- elif event.keysym == 'Left':
- direction = 'Left'
- elif event.keysym == 'Up':
- direction = 'Up'
- elif event.keysym == 'Down':
- direction = 'Down'
- # Bind the spacebar to toggle randomness
- root.bind("<space>", toggle_randomness)
- # Bind 'n' key to toggle noise simulation
- root.bind("<n>", toggle_noise_simulation)
- # Bind arrow keys to change the snake movement direction
- root.bind("<KeyPress>", on_key_press)
- # Initialize the snake on the grid and start the auto-move loop
- update_grid(qc) # Display the initial grid
- auto_move() # Start the automatic movement
- # Run the Tkinter main loop
- root.mainloop()
- # Transpile the circuit for optimization and inspection
- transpiled_circuit = transpile(qc, optimization_level=1)
- # Get the number of qubits and gates
- num_qubits = transpiled_circuit.num_qubits
- num_gates = transpiled_circuit.size()
- # Print out the number of qubits and the number of gates in the terminal
- print(f"Number of qubits: {num_qubits}")
- print(f"Number of gates: {num_gates}")
- # Get the text representation of the quantum circuit as a string
- circuit_text_representation = transpiled_circuit.draw(output='text').__str__() # Convert to string
- # Save the quantum circuit, qubit, and gate info to a text file
- file_path = './quantum_circuit_diagram.txt' # Specify the file path
- with open(file_path, 'w') as file:
- # Write the qubit and gate information at the top of the file
- file.write(f"Number of qubits: {num_qubits}\n")
- file.write(f"Number of gates: {num_gates}\n\n")
- # Write the circuit diagram to the file
- file.write(circuit_text_representation)
- print(f"Quantum circuit diagram and stats saved to {file_path}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement