猜数字游戏
游戏描述:编写一个程序,随机生成一个数字,玩家通过输入猜测的数字来猜测正确数字。程序要给予相应的提示,直到玩家猜对为止。
编程语言:Python
示例代码:
```python
import random
secret_number = random.randint(1, 100)
attempts = 0
while True:
try:
guess = int(input("请输入你的猜测: "))
attempts += 1
if guess == secret_number:
print(f"恭喜你猜对了!这个数字是{secret_number}。你一共用了{attempts}次尝试。")
break
elif guess < secret_number:
print("你的猜测小了。")
else:
print("你的猜测大了。")
except ValueError:
print("请输入一个整数。")
```
井字棋游戏
游戏描述:在一个3×3的棋盘上,两名玩家轮流放置自己的棋子。编程实现这个游戏可以使用二维数组和循环结构来表示和操作棋盘。
编程语言:Python
示例代码:
```python
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board, player):
for row in board:
if all(x == player for x in row):
return True
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
current_player = 0
while True:
print_board(board)
row = int(input(f"玩家{players[current_player]},请输入行(0-2): "))
col = int(input(f"玩家{players[current_player]},请输入列(0-2): "))
if board[row][col] != " ":
print("该位置已有棋子,请重新输入。")
continue
board[row][col] = players[current_player]
if check_winner(board, players[current_player]):
print_board(board)
print(f"玩家{players[current_player]}获胜!")
break
current_player = 1 - current_player
```
打飞机游戏
游戏描述:编写一个简单的2D飞机射击游戏,玩家控制一个飞机消灭敌机。
编程语言:Pygame(Python)
示例代码: