一、2048
要求:4*4格子,可在命令行完美显示,实现上下左右的位移、相加操作。
功能:
- 前期很无聊,不如程序自动执行N步,使用贪心算法来进行前期快速移动;
- 增添最多7步的回溯功能,输入R即可回溯一步;
- 退出按'q'。
import random
import copy
def move_left(grid):
new_grid = []
merged = []
for row in grid:
# 压缩
compacted = [num for num in row if num != 0]
# 合并
merged_row = []
skip_next = False
for i in range(len(compacted)):
if skip_next:
skip_next = False
continue
if i + 1 < len(compacted) and compacted[i] == compacted[i + 1]:
merged_row.append(compacted[i] * 2)
skip_next = True
else:
merged_row.append(compacted[i])
# 填充
merged_row += [0] * (len(row) - len(merged_row))
new_grid.append(merged_row)
merged.append(skip_next)
return new_grid, merged
def add_new_tile(grid):
empty_cells = [(r, c) for r in range(4) for c in range(4) if grid[r][c] == 0]
if empty_cells:
rc = random.choice(empty_cells)
grid[rc[0]][rc[1]] = 2 if random.random() < 0.9 else 4
return grid
def print_grid(grid):
for row in grid:
for i, num in enumerate(row):
if i == 3:
print(" ", num)
else:
print(" ", num, end="\t|")
print("-" * 33)
def cannot_move(grid):
for row in grid:
for i in range(1, 4):
if row[i] == row[i-1]:
return False
for col in zip(*grid):
for i in range(1, 4):
if col[i] == col[i-1]:
return False
return True
def evaluate(last_grid, grid):
# 评估函数:考虑空格数量和平滑度
score = 0
for row in last_grid:
run_length = 0
for i in range(1, 4):
if row[i] == row[i - 1]:
run_length += 1
else:
score += run_length * 10
run_length = 0
score += run_length * 10
if last_grid == grid:
return 0
return score + sum(1 for row in last_grid for cell in row if cell == 0) * 100
def simulate_move(grid, direction):
if direction == 'W':
grid = [list(row) for row in zip(*grid)] # Transpose
grid, _ = move_left(grid)
grid = [list(row) for row in zip(*grid)] # Transpose back
elif direction == 'S':
grid = [list(row) for row in zip(*grid)] # Transpose
grid = [list(reversed(row)) for row in grid]
grid, _ = move_left(grid)
grid = [list(reversed(row)) for row in grid]
grid = [list(row) for row in zip(*grid)] # Transpose back
elif direction == 'A':
grid, _ = move_left(grid)
elif direction == 'D':
grid = [list(reversed(row)) for row in grid]
grid, _ = move_left(grid)
grid = [list(reversed(row)) for row in grid]
return grid
def auto_play(grid):
best_score = -float('inf')
best_move = None
for move in ['W', 'A', 'S', 'D']:
temp_grid = [row[:] for row in grid]
temp_grid = simulate_move(temp_grid, move)
score = evaluate(temp_grid, grid)
if score > best_score:
best_score = score
best_move = move
return best_move
def main():
grid = [[0 for _ in range(4)] for _ in range(4)]
grid[random.randint(0, 3)][random.randint(0, 3)] = 2
count = 0
last_grid = [copy.deepcopy(grid)]
while True:
if count > 400:
print_grid(grid)
move = input("Enter your move (W/A/S/D): ").upper()
else:
move = auto_play(grid)
count += 1
if move == "Q":
break
old_grid = [row[:] for row in grid]
grid = simulate_move(grid, move)
if move == 'R':
if len(last_grid) >= 2:
del last_grid[-1]
grid = copy.deepcopy(last_grid[-1])
else:
print("You've already withdrawn enough!")
elif old_grid != grid:
grid = add_new_tile(grid)
a = copy.deepcopy(grid)
last_grid.append(a)
if len(last_grid) > 8:
del last_grid[0]
if not any(0 in row for row in grid):
if cannot_move(grid):
print_grid(grid)
print('Moving Steps are: ', count)
print('Game Over!')
break
if __name__ == "__main__":
main()
二、 Hangman
英文猜词游戏,难点主要是题库。
import random
# 单词及其提示
word_list = {
'apple': 'A common fruit that can be red, green, or yellow.',
'banana': 'A long curved fruit that grows in clusters and has a yellow skin.',
'cherry': 'Small, round fruit that is usually bright red or dark purple.',
'date': 'Sweet fruit with a seed inside that grows on palm trees.',
'elderberry': 'Small berries that grow in clusters and are often used in food and medicine.',
'fig': 'Sweet fruit with soft flesh that grows on a tree.',
'grape': 'Small, round fruit that grows in bunches and can be eaten fresh or made into wine.',
'orange': 'Round citrus fruit that is usually orange in color.',
'peach': 'Fruit with fuzzy skin and a single large seed inside.',
'quince': 'Pear-shaped fruit with a sweet and tart flavor when cooked.',
'raspberry': 'Small, red or black berry with a sweet taste.',
'strawberry': 'Red, heart-shaped fruit that is very sweet.',
'tomato': 'Red fruit that is used in many dishes and sauces.',
'watermelon': 'Large, round fruit with a green rind and sweet red or yellow flesh.',
'zebra': 'Striped African mammal that looks like a horse.',
'elephant': 'Large gray mammal with a long trunk and big ears.',
'giraffe': 'Tall African mammal with a long neck and spots.',
'hippopotamus': 'Large, semi-aquatic mammal with a wide mouth.',
'jaguar': 'Big cat with golden fur and black spots.',
'koala': 'Small, furry animal from Australia that eats eucalyptus leaves.',
'leopard': 'Big cat with golden fur and black spots.',
'monkey': 'Primate known for its ability to climb and swing.',
'nightingale': 'Small bird known for its beautiful song.',
'octopus': 'Sea creature with eight arms and a beak.',
'penguin': 'Flightless bird that lives in cold climates.',
'quokka': 'Small marsupial native to Western Australia.',
'rhinoceros': 'Large mammal with one or two horns on its nose.',
'sheep': 'Domesticated animal raised for wool, meat, and milk.',
'tiger': 'Big cat with orange fur and black stripes.',
'unicorn': 'Mythical creature with a single horn on its forehead.',
'vulture': 'Large bird known for eating carrion.',
'walrus': 'Large marine mammal with tusks.',
'xylophone': 'Musical instrument consisting of wooden bars struck with mallets.',
'yak': 'Large, hairy bovine native to Central Asia.',
'zebu': 'Cattle breed with a hump on their back.',
'airport': 'Facility where aircraft take off and land.',
'balloon': 'Inflatable object that can rise into the air.',
'castle': 'Large fortified building or group of buildings.',
'dinosaur': 'Extinct reptiles that lived millions of years ago.',
'elevator': 'Machine that moves people or goods between floors of a building.',
'fountain': 'Structure that shoots water into the air for decoration.',
'garden': 'Area where plants are grown.',
'house': 'Building where people live.',
'igloo': 'Dome-shaped shelter built with snow blocks.',
'jail': 'Place where people are held as punishment or awaiting trial.',
'kingdom': 'Territory ruled by a king or queen.',
'library': 'Building where books and other materials are stored and made available to the public.',
'mansion': 'Large, luxurious house.',
'observatory': 'Building equipped with telescopes for astronomical observations.',
'pyramid': 'Triangular structure used as tombs in ancient Egypt.',
'quay': 'Structure where ships dock.',
'railway': 'Track used for trains.',
'spaceship': 'Vehicle designed for travel in space.',
'temple': 'Building dedicated to worship or religious activities.',
'umbrella': 'Device used to protect oneself from rain or sun.',
'volcano': 'Mountain that opens periodically to discharge lava, steam, and gas.',
'warehouse': 'Building used for storage of goods.',
'xray': 'Type of electromagnetic radiation used in medical imaging.',
'yacht': 'Recreational boat or ship.',
'zoo': 'Facility where animals are kept for public viewing.',
'adventure': 'Exciting or unusual experience.',
'balance': 'State of equilibrium or equal distribution.',
'challenge': 'Task that tests someone\'s abilities.',
'dream': 'Sequence of thoughts, images, and sensations occurring in a sleeping person\'s mind.',
'energy': 'Strength and vitality required for sustained physical or mental activity.',
'freedom': 'Power or right to act, speak, or think as one wants.',
'glory': 'Praise, honor, or admiration directed toward a person or thing.',
'harmony': 'Pleasing combination of elements.',
'imagination': 'Ability to form new ideas or concepts.',
'journey': 'Long trip or voyage.',
'knowledge': 'Understanding of facts, information, and skills acquired through experience or education.',
'laughter': 'Sound made by humans to express amusement or joy.',
'magic': 'Supernatural power or influence.',
'nature': 'Physical world and everything in it.',
'ocean': 'Large body of salt water covering most of the Earth\'s surface.',
'peace': 'State of tranquility or quiet.',
'quiet': 'Free from disturbance; calm.',
'rainbow': 'Multicolored arc seen in the sky when sunlight is refracted through raindrops.',
'sunshine': 'Light from the sun.',
'treasure': 'Valuable objects or wealth.',
'universe': 'All matter and energy, including Earth, stars, and galaxies.',
'vacation': 'Period of time away from work or school spent traveling or relaxing.',
'wonder': 'Feeling of surprise mingled with admiration, caused by something beautiful, sublime, or extraordinary.',
'xenophobia': 'Intense or irrational fear of foreigners or strangers.',
'yearning': 'Strong desire or longing.',
'zen': 'Japanese sect of Buddhism emphasizing meditation.'
}
def get_word():
"""随机选择一个单词列表中的单词作为谜底"""
word, hint = random.choice(list(word_list.items()))
return word, hint
def display_hangman(incorrect_guesses):
"""根据错误次数显示不同的绞刑架状态"""
stages = [
"""
--------
| |
| O
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
"""
--------
| |
| O
| \\|/
| |
|
-
""",
"""
--------
| |
| O
| \\|
| |
|
-
""",
"""
--------
| |
| O
| |
| |
|
-
""",
"""
--------
| |
| O
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[incorrect_guesses]
def play_game():
word, hint = get_word()
word_completion = '_' * len(word)
guessed = False
guessed_letters = []
tries = 6
print("Let's play Hangman!")
print(f"Hint: {hint}")
while not guessed and tries > 0:
print(display_hangman(6 - tries))
print(word_completion)
guess = input("Guess a letter: ").lower()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("You already guessed the letter", guess)
elif guess in word:
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
else:
guessed_letters.append(guess)
tries -= 1
else:
print("Not a valid guess.")
if guessed:
print(display_hangman(6 - tries))
print(word_completion)
print("Congratulations, you found the word!")
else:
print(display_hangman(6 - tries))
print("Sorry, you ran out of tries. The word was " + word)
if __name__ == "__main__":
play_game()
三、扫雷
import random
class Minesweeper:
def __init__(self, width=8, height=8, mines=10):
self.width = width
self.height = height
self.mines = mines
self.board = [[' ' for _ in range(width)] for _ in range(height)]
self.revealed = [[False for _ in range(width)] for _ in range(height)]
self.place_mines()
self.calculate_numbers()
def place_mines(self):
mine_count = 0
while mine_count < self.mines:
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if self.board[y][x] != '*':
self.board[y][x] = '*'
mine_count += 1
def calculate_numbers(self):
for y in range(self.height):
for x in range(self.width):
if self.board[y][x] == '*':
continue
count = sum(
self.board[n_y][n_x] == '*' for n_y in range(max(0, y - 1), min(y + 2, self.height))
for n_x in range(max(0, x - 1), min(x + 2, self.width))
)
self.board[y][x] = str(count)
def reveal_square(self, x, y):
if self.revealed[y][x]:
return
self.revealed[y][x] = True
if self.board[y][x] == '0':
for n_y in range(max(0, y - 1), min(y + 2, self.height)):
for n_x in range(max(0, x - 1), min(x + 2, self.width)):
self.reveal_square(n_x, n_y)
def display_board(self):
print("列号:\n ", " ".join(str(i) for i in range(self.width)))
for y in range(self.height):
row = str(y) + ": "
for x in range(self.width):
if self.revealed[y][x]:
row += self.board[y][x] + " "
else:
row += "? "
print(row)
def is_game_over(self):
for y in range(self.height):
for x in range(self.width):
if not self.revealed[y][x] and self.board[y][x] != '*':
return False
return True
def safe_input(prompt, validator, message):
while True:
value = input(prompt)
try:
value = validator(value)
return value
except ValueError:
print(message)
def main():
game = Minesweeper()
game.display_board()
while not game.is_game_over():
x = safe_input(f"输入要揭示的列号(0 到 {game.width - 1}): ",
lambda x: int(x) if 0 <= int(x) < game.width else -1,
"无效输入,请输入一个有效的列号!")
y = safe_input(f"输入要揭示的行号(0 到 {game.height - 1}): ",
lambda y: int(y) if 0 <= int(y) < game.height else -1,
"无效输入,请输入一个有效的行号!")
if game.board[y][x] == '*':
print("你踩到地雷了!游戏结束。")
break
game.reveal_square(x, y)
game.display_board()
else:
print("恭喜你,你成功揭示了所有非雷区域!")
if __name__ == "__main__":
main()