如何排除指定元素值获取随机数组索引及AI随机可行落子实现
Alright, let's break down your two requirements and tackle them one by one with practical, easy-to-follow code examples.
The core idea here is straightforward: first, we collect all indices where the element doesn't match the value we want to exclude, then pick a random one from that list.
Here's a Python implementation that works for any one-dimensional array:
import random def get_random_valid_index(arr, exclude_value): # Step 1: Filter out indices where the element equals the excluded value valid_indices = [idx for idx, val in enumerate(arr) if val != exclude_value] # Step 2: Return a random valid index if any exist; else return None return random.choice(valid_indices) if valid_indices else None
How it works:
enumerate(arr)lets us loop through both the index and value of each element in the array.- The list comprehension builds a list of indices only for elements that don't match
exclude_value. random.choice()picks a random element from the valid indices list. We add a check to avoid errors if there are no valid indices left.
Example usage:
test_array = [True, False, False, True, False] print(get_random_valid_index(test_array, True)) # Will return 1, 2, or 4 randomly
For this scenario, we need to maintain the game state (board with available/occupied spots), track move history, and let the AI pick a random available spot each time it moves. Using a class helps keep everything organized.
Here's a Python implementation for a 2D board (easily adaptable to 1D if needed):
import random class GoLikeGame: def __init__(self, board_size): # Initialize board: all spots are False (available) self.board = [[False for _ in range(board_size)] for _ in range(board_size)] # Track all moves made (stores (row, column) tuples) self.move_history = [] def _get_available_spots(self): # Helper method to collect all available (False) positions available = [] for row_idx, row in enumerate(self.board): for col_idx, is_occupied in enumerate(row): if not is_occupied: available.append((row_idx, col_idx)) return available def ai_move(self): # AI picks a random available spot and updates the game state available_spots = self._get_available_spots() if not available_spots: print("No available spots left! Game over.") return None # Randomly select an available spot selected = random.choice(available_spots) row, col = selected # Mark the spot as occupied (True) self.board[row][col] = True # Record the move self.move_history.append(selected) print(f"AI placed a stone at ({row}, {col})") return selected
How it works:
__init__sets up a square board of the specified size, with all spots initially available (False), and initializes a list to track move history._get_available_spotsis an internal helper that scans the entire board and collects coordinates of all unoccupied spots.ai_movehandles the AI's turn: it checks for available spots, picks one at random, updates the board to mark the spot as occupied, and logs the move.
Example usage:
# Start a game with an 8x8 board game = GoLikeGame(8) # First AI move game.ai_move() # Second AI move (uses the updated board state) game.ai_move() # Check the move history print("All moves made so far:", game.move_history)
If you need a 1D board instead, just modify the __init__ and _get_available_spots methods to use a single list instead of a 2D list— the core logic of filtering available spots and picking randomly stays exactly the same.
内容的提问来源于stack exchange,提问作者Umaro

