写一个打地鼠代码
时间: 2023-07-10 11:23:09 浏览: 75
好的,以下是一个简单的打地鼠游戏的代码示例:
```python
import random
# 游戏配置
ROWS = 3
COLS = 3
HOLE_SYMBOL = 'O'
MOLE_SYMBOL = 'M'
BLANK_SYMBOL = '-'
NUM_MOLES = 3
TIME_LIMIT = 30
# 初始化游戏板
board = [[HOLE_SYMBOL for j in range(COLS)] for i in range(ROWS)]
# 创建地鼠
moles = []
for i in range(NUM_MOLES):
row = random.randint(0, ROWS-1)
col = random.randint(0, COLS-1)
while board[row][col] == MOLE_SYMBOL:
row = random.randint(0, ROWS-1)
col = random.randint(0, COLS-1)
board[row][col] = MOLE_SYMBOL
moles.append((row, col))
# 打印游戏板
def print_board(board):
for row in board:
print(' '.join(row))
print()
# 游戏循环
hits = 0
misses = 0
time_left = TIME_LIMIT
while time_left > 0:
print_board(board)
print('Time left:', time_left)
print('Hits:', hits)
print('Misses:', misses)
row = int(input('Row: '))
col = int(input('Col: '))
if row < 0 or row >= ROWS or col < 0 or col >= COLS:
print('Invalid input!')
continue
if board[row][col] == MOLE_SYMBOL:
board[row][col] = BLANK_SYMBOL
hits += 1
print('Hit!')
else:
misses += 1
print('Miss!')
time_left -= 1
# 游戏结束
print('Time is up!')
print('Hits:', hits)
print('Misses:', misses)
print('Score:', hits - misses)
```
该代码使用二维列表表示游戏板,随机创建若干个地鼠,然后在游戏循环中允许玩家输入行和列,判断玩家是否击中地鼠。最后计算得分并输出。
阅读全文