1. 猜数字游戏
import random
def guess_number():
random_number = random.randint(1, 100)
attempts = 0
while True:
user_guess = int(input("请输入一个1到100之间的数字:"))
attempts += 1
if user_guess > random_number:
print("太大了,请再试一次!")
elif user_guess < random_number:
print("太小了,请再试一次!")
else:
print(f"恭喜你,猜对了!你用了{attempts}次尝试。")
break
guess_number()这个猜数字游戏的规则很简单,程序随机生成一个1到100之间的数字,然后玩家通过输入猜测的数字来与随机数进行比较。如果猜测的数字大于或小于随机数,程序会给出相应的提示。直到玩家猜对为止,程序会显示恭喜消息,并告诉玩家猜对所用的尝试次数。
2. 石头、剪刀、布游戏
import random
def rock_paper_scissors():
choices = ['石头', '剪刀', '布']
while True:
user_choice = input("请选择(石头、剪刀、布):")
if user_choice not in choices:
print("无效的选择,请重新输入!")
continue
computer_choice = random.choice(choices)
print(f"你选择了:{user_choice}")
print(f"电脑选择了:{computer_choice}")
if user_choice == computer_choice:
print("平局!")
elif (user_choice == '石头' and computer_choice == '剪刀') or \
(user_choice == '剪刀' and computer_choice == '布') or \
(user_choice == '布' and computer_choice == '石头'):
print("恭喜你,你赢了!")
else:
print("很遗憾,你输了!")
play_again = input("再玩一局?(是/否)")
if play_again.lower() != "是" and play_again.lower() != "yes":
print("游戏结束。")
break
rock_paper_scissors()
3.扫雷游戏import random
# 定义游戏矩阵的大小
ROW_NUM = 5
COL_NUM = 5
# 定义雷的数量
BOMBS_NUM = 10
# 定义游戏矩阵
board = [[0 for _ in range(COL_NUM)] for _ in range(ROW_NUM)]
# 定义雷的列表
bombs = []
# 初始化游戏矩阵
for i in range(BOMBS_NUM):
row = random.randint(0, ROW_NUM - 1)
col = random.randint(0, COL_NUM - 1)
while (row, col) in bombs:
row = random.randint(0, ROW_NUM - 1)
col = random.randint(0, COL_NUM - 1) bombs.append((row, col))
board[row][col] = 'B'
# 打印游戏矩阵
print(" " + ("|" * COL_NUM))for i in range(ROW_NUM):
print("{:2d}|".format(i + 1) + ("_" * COL_NUM))
print(" " + ("|" * COL_NUM))
for i in range(ROW_NUM):
print("{:2d}|".format(i + 1), end="")
for j in range(COL_NUM):
if board[i][j] == 'B':
print(" X
else:
print("
print("|")
print(" " + ("|" * COL_NUM))
# 游戏循环
while True:
# 获取用户输入的行和列
row = int(input("Enter row number: ")) - 1
col = int(input("Enter column number: ")) - 1
# 检查输入是否合法
if row < 0 or row >= ROW_NUM or col < 0 or col >= COL_NUM:
print("Invalid input.")
continueif board[row][col] == 'B':
print("Game over!")
break
if board[row][col] == '0':
print("0")
continue
count = 0
for i in range(ROW_NUM):
for j in range(COL_NUM):
if (i, j) != (row, col) and board[i][j] != 'B' and board[i][j] != '0':
if (i - row) ** 2 + (j - col) ** 2 == 0 or (i - row) ** 2 + (j - col) ** 2 == 1 or (i - row) ** 2 + (j - col) ** 2 == 3:
count += 1
print(count)
这个代码实现了一个基本的扫雷游戏,用户可以输入行号和列号来猜测雷的位置。如果猜对了,游戏结束;如果猜错了,就会显示周围八个格子中雷的数量。
4.黑白棋游戏
# 创建棋盘
def create_board():
board = [[' ' for _ in range(8)] for _ in range(8)]board[3][3] = 'W'
board[3][4] = 'B'
board[4][3] = 'B'
board[4][4] = 'W'
return board
# 显示棋盘
def display_board(board):
print(' 0 1 2 3 4 5 6 7')
print('-----------------')
for row in range(8):
print(f'{row}|', end='')
for col in range(8):
print(board[row][col] + '|', end='')
print('\\n-----------------')
# 检查是否合法落子
def is_valid_move(board, player, row, col):
if board[row][col] != ' ':
return False
other_player = 'B' if player == 'W' else 'W'
directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]
for dx, dy in directions:
x, y = row, col
x += dx
y += dy
if x >= 0 and x < 8 and y >= 0 and y < 8 and
board[x][y] == other_player:
x += dx
y += dy
while x >= 0 and x < 8 and y >= 0 and y < 8 and board[x][y] == other_player:
x += dx
y += dy
if x >= 0 and x < 8 and y >= 0 and y < 8 and board[x][y] == player:
return True
return False
# 执行落子
def make_move(board, player, row, col):
directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]board[row][col] = player
for dx, dy in directions:
x, y = row, col
x += dx
y += dy
if x >= 0 and x < 8 and y >= 0 and y < 8 and
board[x][y] != player and board[x][y] != ' ':
temp_x, temp_y = x, y
while x >= 0 and x < 8 and y >= 0 and y < 8 and board[x][y] != player and board[x][y] != ' ':
x += dx
y += dy
if x >= 0 and x < 8 and y >= 0 and y < 8 and board[x][y] == player:
while temp_x != x or temp_y != y:
board[temp_x][temp_y] = player
temp_x += dx
temp_y += dy
# 检查游戏结束
def is_game_over(board):for row in range(8):
for col in range(8):
if board[row][col] == ' ':
return False
return True
# 统计棋盘上黑白棋子数目
def count_pieces(board):
black_count = 0
white_count = 0
for row in range(8):
for col in range(8):
if board[row][col] == 'B':
black_count += 1
elif board[row][col] == 'W':
white_count += 1 return black_count, white_count
# 游戏主函数
def play_game():
board = create_board()
player = 'B'
display_board(board)while not is_game_over(board):
valid_moves = []
for row in range(8):
for col in range(8):
if is_valid_move(board, player, row, col):
valid_moves.append((row, col))
if len(valid_moves) == 0:
print(f"当前无有效落子位置,轮到对方({ '白色' if player == 'B' else '黑色' })落子。")
player = 'W' if player == 'B' else 'B'
continue
print(f"轮到{ '黑色' if player == 'B' else '白色' } 落子。")
row, col = map(int, input("请输入落子位置(行列):").split())
if (row, col) not in valid_moves:
print("无效的落子位置,请重新输入!")
continuemake_move(board, player, row, col)
display_board(board)
player = 'W' if player == 'B' else 'B'
black_count, white_count = count_pieces(board)
print(f"游戏结束。黑色棋子数:{black_count},白色棋子数:{white_count}。")
if black_count > white_count:
print("黑色获胜!")
elif white_count > black_count:
print("白色获胜!")
else:
print("平局!")
play_game()
这个示例代码实现了一个基本的黑白棋游戏。在游戏中,玩家通过输入落子位置来选择棋盘上的行和列,程序会检查该位置是否为合法落子,并执行相应的翻转操作,然后显示更新后的棋盘状态。
5.2048游戏
import random
class Game:
def __init__(self):
self.board = [[0 for _ in range(4)] for _ in range(4)]self.scores = 0
self.moves = 0
self.new_tile()
def new_tile(self):
while True:
x = random.randint(0, 3)
y = random.randint(0, 3)
if self.board[x][y] == 0:
self.board[x][y] = 2
return
def print_board(self):
for row in self.board:
print(" ".join(str(cell) for cell in row))
print("Scores:
print("Moves:
def move_up(self):
self.moves += 1
self.board = [[self.board[j][i] for j in range(4)] for i in range(4)]
self.merge()
self.new_tile()
self.print_board()
def move_down(self):
self.moves += 1
self.board = [[self.board[j][i] for j in range(4, 0, -1)] for i in range(4)]
self.merge()
self.new_tile()
self.print_board()
def move_left(self):
self.moves += 1
self.board = [[self.board[i][j] for j in range(4)] for i in range(4)]
self.merge()
self.new_tile()
self.print_board()
def move_right(self):
self.moves += 1
self.board = [[self.board[i][j] for j in range(4, 0, -1)] for i in range(4)]
self.merge()
self.new_tile()
self.print_board()
def merge(self):for i in range(2):
for j in range(2):
if self.board[i][j] != 0 and self.board[i+1][j] != 0 and self.board[i][j] == self.board[i+1][j]:
self.board[i][j] *= 2
self.scores += self.board[i][j] * 2**2 # 2^2 because we merged two tiles into one
self.board[i+1][j] = 0 # Remove the duplicate tile after merging
这个代码实现了一个基本的2048游戏,可以通过调用`move_up`、`move_down`、`move_left`和`move_right`方法来移动方块。当两个相同的方块相遇时,它们会合并成一个更大的方块,并且玩家的分数会增加。下载本文