以下内容为使用Python开发的一些小游戏,仅供参考,谢谢!
猜单词游戏
import random
# 单词列表
words = ['apple', 'banana', 'cherry', 'orange', 'pear', 'watermelon']
# 随机选一个单词
word = random.choice(words)
# 将单词转换为小写字母
word = word.lower()
# 猜测次数限制
max_guesses = 10
# 玩家猜测的次数
guesses = 0
# 玩家猜测的字母集合
letters_guessed = set()
# 游戏是否结束的标志
game_over = False
print('猜单词游戏!')
print('我想了一个单词,这个单词有', len(word), '个字母。')
while not game_over:
# 显示玩家已经猜过的字母
print('你已经猜过的字母:', ' '.join(sorted(letters_guessed)))
# 显示单词中已经猜中的字母
display_word = ''
for letter in word:
if letter in letters_guessed:
display_word += letter
else:
display_word += '_'
print(display_word)
# 等待玩家猜测
guess = input('你猜这个单词是什么?')
# 判断玩家猜测的是字母还是单词
if len(guess) == 1:
# 玩家猜测的是字母
letter = guess.lower()
if letter in letters_guessed:
print('你已经猜过这个字母了,请猜一个新的字母。')
else:
letters_guessed.add(letter)
if letter in word:
print('恭喜你,你猜对了一个字母!')
else:
print('很遗憾,这个字母不在单词中。')
guesses += 1
else:
# 玩家猜测的是单词
if guess.lower() == word:
print('恭喜你,你猜对了整个单词!')
game_over = True
else:
print('很遗憾,你猜错了整个单词。')
guesses += 1
# 判断游戏是否结束
if guesses >= max_guesses:
print('很遗憾,你已经猜测了', max_guesses, '次,游戏结束。')
game_over = True
elif set(word) == letters_guessed:
print('恭喜你,你猜对了整个单词!')
game_over = True
猜数字游戏
import random
number = random.randint(1, 100)
guesses = 0
print('猜数字游戏!')
print('我想了一个 1 到 100 之间的整数。')
while True:
guess = int(input('你猜这个数字是多少?'))
guesses += 1
if guess < number:
print('猜小了!')
elif guess > number:
print('猜大了!')
else:
print('恭喜你猜对了!')
break
print('你总共猜了', guesses, '次。')
黑白棋游戏
# 定义棋盘的大小
BOARD_SIZE = 8
# 定义棋子的颜色
EMPTY = 0
BLACK = 1
WHITE = 2
# 初始化棋盘
board = [[EMPTY for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)]
board[3][3] = WHITE
board[4][4] = WHITE
board[3][4] = BLACK
board[4][3] = BLACK
# 定义可以翻转对手棋子的方向
DIRECTIONS = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
# 定义玩家的颜色
player_color = BLACK
# 定义游戏是否结束的标志
game_over = False
# 统计棋盘上各种颜色的棋子数
def count_pieces(board):
black_count = 0
white_count = 0
for row in board:
for cell in row:
if cell == BLACK:
black_count += 1
elif cell == WHITE:
white_count += 1
return (black_count, white_count)
# 判断落子是否合法
def is_legal_move(board, row, col, color):
if board[row][col] != EMPTY:
return False
for direction in DIRECTIONS:
r, c = row + direction[0], col + direction[1]
if (r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] == EMPTY or board[r][c] == color):
continue
r += direction[0]
c += direction[1]
while (r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] != EMPTY):
if (board[r][c] == color):
return True
r += direction[0]
c += direction[1]
return False
# 翻转对手的棋子
def flip_pieces(board, row, col, color):
for direction in DIRECTIONS:
r, c = row + direction[0], col + direction[1]
if (r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] == EMPTY or board[r][c] == color):
continue
r += direction[0]
c += direction[1]
while (r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] != EMPTY):
if (board[r][c] == color):
r2, c2 = row + direction[0], col + direction[1]
while (r2 != r or c2 != c):
board[r2][c2] = color
r2 += direction[0]
c2 += direction[1]
break
r += direction[0]
c += direction[1]
# 输出棋盘
def print_board(board):
print(' ', end='')
for i in range(BOARD_SIZE):
print(chr(ord('a') + i), end=' ')
print()
print(' +' + '-' * (2 * BOARD_SIZE - 1) + '+')
for i in range(BOARD_SIZE):
print(str(i + 1) + ' |', end='')
for j in range(BOARD_SIZE):
if board[i][j] == EMPTY:
print(' ', end='')
elif board[i][j] == BLACK:
print('●', end='')
elif board[i][j] == WHITE:
print('○', end='')
if j < BOARD_SIZE - 1:
print(' ', end='')
print('| ' + str(i + 1))
print(' +-' + '-' * (2 * BOARD_SIZE - 1) + '-+')
print(' ', end='')
for i in range(BOARD_SIZE):
print(chr(ord('a') + i), end=' ')
print()
# 主循环
while not game_over:
# 输出当前棋盘和玩家的颜色
print_board(board)
if player_color == BLACK:
print("黑方落子")
else:
print("白方落子")
# 等待玩家落子
while True:
move = input("请输入落子位置(例如d3)或输入pass跳过本回合:")
if move.lower() == "pass":
break
col = ord(move[0]) - ord('a')
row = int(move[1:]) - 1
if (col < 0 or col >= BOARD_SIZE or row < 0 or row >= BOARD_SIZE or not is_legal_move(board, row, col, player_color)):
print("无效落子,请重新输入。")
else:
board[row][col] = player_color
flip_pieces(board, row, col, player_color)
break
# 判断游戏是否结束
black_count, white_count = count_pieces(board)
if (black_count == 0 or white_count == 0 or black_count + white_count == BOARD_SIZE * BOARD_SIZE):
game_over = True
# 切换玩家的颜色
if player_color == BLACK:
player_color = WHITE
else:
player_color = BLACK
# 输出最终的棋盘和胜者
print_board(board)
black_count, white_count = count_pieces(board)
if black_count == white_count:
print("平局")
elif black_count > white_count:
print("黑方胜利")
else:
print("白方胜利")
在上面的代码中,我们首先定义了棋盘的大小和棋子的颜色,然后初始化了棋盘和玩家的颜色。游戏的主循环中,我们输出当前棋盘和玩家的颜色,等待玩家落子。如果玩家输入的落子位置合法,我们就将落子放在棋盘上,并翻转对手的一些棋子。然后,我们判断游戏是否结束。如果棋盘上只剩下一种颜色的棋子,或者棋盘上的格子都被占满了,游戏就结束。最后,我们输出最终的棋盘和胜者。
2048
import random
# 定义方格的大小
SIZE = 4
# 初始化方格
board = [[0 for x in range(SIZE)] for y in range(SIZE)]
# 随机生成两个数字块
def init_board():
for i in range(2):
row = random.randint(0, SIZE - 1)
col = random.randint(0, SIZE - 1)
while board[row][col] != 0:
row = random.randint(0, SIZE - 1)
col = random.randint(0, SIZE - 1)
board[row][col] = 2
# 输出方格
def print_board():
for row in board:
for cell in row:
print(cell, end='\t')
print()
print()
# 判断方格是否已满
def is_full():
for row in board:
for cell in row:
if cell == 0:
return False
return True
# 在方格中随机生成一个数字块
def spawn_block():
while True:
row = random.randint(0, SIZE - 1)
col = random.randint(0, SIZE - 1)
if board[row][col] == 0:
board[row][col] = 2 if random.random() < 0.9 else 4
break
# 判断方格是否可以移动
def can_move():
for row in range(SIZE):
for col in range(SIZE):
if board[row][col] == 0:
return True
if col > 0 and board[row][col] == board[row][col - 1]:
return True
if col < SIZE - 1 and board[row][col] == board[row][col + 1]:
return True
if row > 0 and board[row][col] == board[row - 1][col]:
return True
if row < SIZE - 1 and board[row][col] == board[row + 1][col]:
return True
return False
# 合并相同的数字块
def merge_blocks():
for row in range(SIZE):
for col in range(SIZE - 1):
if board[row][col] != 0 and board[row][col] == board[row][col + 1]:
board[row][col] *= 2
board[row][col + 1] = 0
for row in range(SIZE):
for col in range(SIZE - 1, 0, -1):
if board[row][col] == 0:
for i in range(col - 1, -1, -1):
if board[row][i] != 0:
board[row][col], board[row][i] = board[row][i], board[row][col]
break
# 处理玩家移动
def handle_move(move):
if move == 'w':
for col in range(SIZE):
for row in range(SIZE - 1):
if board[row][col] == 0:
for i in range(row + 1, SIZE):
if board[i][col] != 0:
board[row][col], board[i][col] = board[i][col], board[row][col]
break
merge_blocks()
elif move == 's':
for col in range(SIZE):
for row in range(SIZE - 1, 0, -1):
if board[row][col] == 0:
for i in range(row - 1, -1, -1):
if board[i][col] != 0:
board[row][col], board[i][col] = board[i][col], board[row][col]
break
merge_blocks()
elif move == 'a':
for row in range(SIZE):
for col in range(SIZE - 1):
if board[row][col] == 0:
for i in range(col + 1, SIZE):
if board[row][i] != 0:
board[row][col], board[row][i] = board[row][i], board[row][col]
break
merge_blocks()
elif move == 'd':
for row in range(SIZE):
for col in range(SIZE - 1, 0, -1):
if board[row][col] == 0:
for i in range(col - 1, -1, -1):
if board[row][i] != 0:
board[row][col], board[row][i] = board[row][i], board[row][col]
break
merge_blocks()
# 游戏循环
while True:
print_board()
if is_full() and not can_move():
print("Game over!")
break
move = input("Enter move (w/a/s/d): ")
handle_move(move)
spawn_block()
在这个游戏中,玩家可以通过键盘输入 w/a/s/d
来移动数字块,合并相同的数字块,最终得到一个 $2048$ 的方块。游戏循环会一直运行,直到方格被填满且无法再移动,此时游戏结束。
扫雷
import random
# 定义方格的大小
n = 10
m = 10
# 定义地雷数量
num_mines = 10
# 初始化方格
board = [[0 for x in range(m)] for y in range(n)]
# 随机生成地雷位置
def place_mines(num_mines):
for i in range(num_mines):
row = random.randint(0, n - 1)
col = random.randint(0, m - 1)
while board[row][col] == -1:
row = random.randint(0, n - 1)
col = random.randint(0, m - 1)
board[row][col] = -1
# 统计地雷数量
def count_mines(row, col):
count = 0
for i in range(max(row - 1, 0), min(row + 2, n)):
for j in range(max(col - 1, 0), min(col + 2, m)):
if board[i][j] == -1:
count += 1
return count
# 显示方格
def print_board():
for row in board:
for cell in row:
if cell == -1:
print('*', end=' ')
elif cell == 0:
print('.', end=' ')
else:
print(cell, end=' ')
print()
# 处理玩家的选择
def handle_choice(row, col):
if board[row][col] == -1:
return False
board[row][col] = count_mines(row, col)
if board[row][col] == 0:
for i in range(max(row - 1, 0), min(row + 2, n)):
for j in range(max(col - 1, 0), min(col + 2, m)):
if board[i][j] == 0:
handle_choice(i, j)
return True
# 游戏循环
place_mines(num_mines)
while True:
print_board()
if all(all(cell != 0 for cell in row) for row in board):
print("You win!")
break
row = int(input("Enter row: "))
col = int(input("Enter col: "))
if not handle_choice(row, col):
print("You lose!")
break
在这个游戏中,玩家需要在一个 $n\times m$ 的方格中找出所有的地雷,而不触雷。游戏开始时,地雷的位置会被随机生成。玩家通过输入行和列的位置来选择方块,如果选择到的方块是一个地雷,游戏结束,否则会显示该方块周围的地雷数量,并递归地展开周围的方块。如果所有不是地雷的方块都被展开,游戏结束,玩家获胜。
石头剪刀布
# 定义手势
HAND_GESTURES = ['rock', 'paper', 'scissors']
# 定义胜利关系
WIN_CONDITIONS = {
'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'
}
# 定义玩家类
class Player:
def __init__(self, name):
self.name = name
self.score = 0
# 玩家出拳
def play(self):
while True:
gesture = input(f'{self.name}, please enter your gesture (rock/paper/scissors): ')
if gesture in HAND_GESTURES:
return gesture
else:
print('Invalid input, please try again.')
# 玩家获胜
def win(self):
self.score += 1
print(f'{self.name} wins!')
# 玩家平局
def tie(self):
print("It's a tie!")
# 玩家失败
def lose(self):
print(f'{self.name} loses!')
# 定义游戏类
class Game:
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
# 开始游戏
def start(self):
while True:
gesture1 = self.player1.play()
gesture2 = self.player2.play()
if gesture1 == gesture2:
self.player1.tie()
self.player2.tie()
elif WIN_CONDITIONS[gesture1] == gesture2:
self.player1.win()
self.player2.lose()
else:
self.player1.lose()
self.player2.win()
print(f'{self.player1.name}: {self.player1.score}, {self.player2.name}: {self.player2.score}')
if input('Do you want to play again? (y/n)') != 'y':
break
# 创建玩家并开始游戏
player1 = Player('Player 1')
player2 = Player('Player 2')
game = Game(player1, player2)
game.start()
在这个游戏中,两个玩家通过输入手势来比拼胜负,如果两个玩家出的手势相同,则为平局;否则根据胜利关系判断胜负。游戏循环会一直运行,直到玩家选择不再继续游戏。每个玩家都有一个积分,每次胜利可以获得一分,游戏结束时积分高的玩家获胜。
飞机大战
import pygame
import random
# 定义窗口的大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 600
# 初始化 Pygame
pygame.init()
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Plane Fight')
# 加载图片
background_image = pygame.image.load('background.png')
player_image = pygame.image.load('player.png')
enemy_image = pygame.image.load('enemy.png')
bullet_image = pygame.image.load('bullet.png')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.Font(None, 36)
# 定义玩家类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_image
self.rect = self.image.get_rect()
self.rect.centerx = WINDOW_WIDTH // 2
self.rect.bottom = WINDOW_HEIGHT - 10
self.speed = 5
# 移动
def move(self, direction):
if direction == 'left':
self.rect.x -= self.speed
elif direction == 'right':
self.rect.x += self.speed
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > WINDOW_WIDTH:
self.rect.right = WINDOW_WIDTH
# 射击
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# 定义敌机类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_image
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WINDOW_WIDTH - self.rect.width)
self.rect.y = random.randint(-100, -self.rect.height)
self.speed = random.randint(1, 5)
# 移动
def move(self):
self.rect.y += self.speed
if self.rect.top > WINDOW_HEIGHT:
self.kill()
# 定义子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = bullet_image
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speed = -10
# 移动
def move(self):
self.rect.y += self.speed
if self.rect.bottom < 0:
self.kill()
# 创建精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()
# 创建玩家并添加到精灵组
player = Player()
all_sprites.add(player)
# 定义游戏循环
clock = pygame.time.Clock()
score = 0
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.move('left')
elif event.key == pygame.K_RIGHT:
player.move('right')
elif event.key == pygame.K_SPACE:
player.shoot()
# 更新游戏状态
all_sprites.update()
# 生成敌机
if len(enemies) < 10:
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# 检测子弹是否击中敌机
hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
for hit in hits:
score += 10
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# 检测敌机是否撞击玩家
hits = pygame.sprite.spritecollide(player, enemies, False)
if len(hits) > 0:
game_over = True
# 清屏
window.fill(BLACK)
# 绘制背景
window.blit(background_image, (0, 0))
# 绘制精灵组中的所有元素
all_sprites.draw(window)
# 显示得分
score_text = font.render(f'Score: {score}', True, WHITE)
window.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 游戏结束,显示最终得分
game_over_text = font.render('Game Over', True, RED)
score_text = font.render(f'Final Score: {score}', True, WHITE)
window.blit(game_over_text, (WINDOW_WIDTH // 2 - game_over_text.get_width() // 2, WINDOW_HEIGHT // 2 - game_over_text.get_height() // 2 - 30))
window.blit(score_text, (WINDOW_WIDTH // 2 - score_text.get_width() // 2, WINDOW_HEIGHT // 2 - score_text.get_height() // 2 + 30))
pygame.display.flip()
# 等待 3 秒后关闭窗口
pygame.time.wait(3000)
pygame.quit()
在这个游戏中,玩家需要控制飞机躲避敌机的攻击并射击敌机。玩家可以使用左右箭头键来移动飞机,使用空格键发射子弹。游戏中会随机生成敌机,玩家需要尽可能地消灭敌机并获得得分。如果敌机撞击到玩家飞机,游戏结束。
贪吃蛇
import pygame
import random
# 定义窗口的大小和方格的大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 480
CELL_SIZE = 20
# 初始化 Pygame
pygame.init()
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Snake')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义字体
font = pygame.font.Font(None, 36)
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(5, 5), (4, 5), (3, 5)]
self.direction = 'right'
# 移动
def move(self):
head = self.body[0]
if self.direction == 'up':
new_head = (head[0], head[1] - 1)
elif self.direction == 'down':
new_head = (head[0], head[1] + 1)
elif self.direction == 'left':
new_head = (head[0] - 1, head[1])
elif self.direction == 'right':
new_head = (head[0] + 1, head[1])
self.body.insert(0, new_head)
self.body.pop()
# 改变方向
def change_direction(self, direction):
if direction == 'up' and self.direction != 'down':
self.direction = 'up'
elif direction == 'down' and self.direction != 'up':
self.direction = 'down'
elif direction == 'left' and self.direction != 'right':
self.direction = 'left'
elif direction == 'right' and self.direction != 'left':
self.direction = 'right'
# 检查是否吃到食物
def check_eat_food(self, food):
if self.body[0] == food.position:
self.body.append(self.body[-1])
# 定义食物类
class Food:
def __init__(self):
self.position = (random.randint(0, WINDOW_WIDTH // CELL_SIZE - 1), random.randint(0, WINDOW_HEIGHT // CELL_SIZE - 1))
# 重新生成位置
def respawn(self):
self.position = (random.randint(0, WINDOW_WIDTH // CELL_SIZE - 1), random.randint(0, WINDOW_HEIGHT // CELL_SIZE - 1))
# 创建蛇和食物对象
snake = Snake()
food = Food()
# 定义游戏循环
clock = pygame.time.Clock()
score = 0
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction('up')
elif event.key == pygame.K_DOWN:
snake.change_direction('down')
elif event.key == pygame.K_LEFT:
snake.change_direction('left')
elif event.key == pygame.K_RIGHT:
snake.change_direction('right')
# 更新游戏状态
snake.move()
snake.check_eat_food(food)
if snake.body[0][0] < 0 or snake.body[0][0] >= WINDOW_WIDTH // CELL_SIZE or snake.body[0][1] < 0 or snake.body[0][1] >= WINDOW_HEIGHT // CELL_SIZE:
game_over = True
for i in range(1, len(snake.body)):
if snake.body[i] == snake.body[0]:
game_over = True
# 清屏
window.fill(BLACK)
# 绘制蛇
for cell in snake.body:
pygame.draw.rect(window, GREEN, (cell[0] * CELL_SIZE, cell[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
# 绘制食物
pygame.draw.rect(window, RED, (food.position[0] * CELL_SIZE, food.position[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
# 显示得分希望这个示例能够帮助您更好地了解 Python 编程语言。如果您有任何问题,请随时问我。