Python编写的20个小游戏完整版
【摘要】 猜数字游戏pythonimport randomnumber = random.randint(1, 100)guess = int(input('请猜一个1到100之间的数字:'))while guess != number: if guess > number: print('猜大了') else: print('猜小了') guess = ...
- 猜数字游戏
python
import random
number = random.randint(1, 100)
guess = int(input('请猜一个1到100之间的数字:'))
while guess != number:
if guess > number:
print('猜大了')
else:
print('猜小了')
guess = int(input('请重新猜一个1到100之间的数字:'))
print('恭喜你,猜对了!')
- 石头剪刀布游戏
python
import random
options = ['石头', '剪刀', '布']
computer_choice = random.choice(options)
user_choice = input('请出拳(石头、剪刀、布):')
print('你出了', user_choice)
print('电脑出了', 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('你输了')
- 猜单词游戏
python
import random
words = ['apple', 'banana', 'cherry', 'orange', 'pear']
word = random.choice(words)
letters = set(word)
correct_guesses = set()
incorrect_guesses = set()
tries = 6
while tries > 0 and letters != correct_guesses:
print('可用次数:', tries)
print('已猜对的字母:', ' '.join(correct_guesses))
print('已猜错的字母:', ' '.join(incorrect_guesses))
guess = input('请猜一个字母:')
if guess in letters:
correct_guesses.add(guess)
else:
incorrect_guesses.add(guess)
tries -= 1
if letters == correct_guesses:
print('恭喜你,猜对了!单词是', word)
else:
print('很遗憾,你没有猜对。单词是', word)
- 猜词游戏
python
import random
words = ['apple', 'banana', 'cherry', 'orange', 'pear']
word = random.choice(words)
shuffle_word = list(word)
random.shuffle(shuffle_word)
print('请猜这个单词:', ''.join(shuffle_word))
guess = input('请输入你的答案:')
if guess == word:
print('恭喜你,猜对了!')
else:
print('很遗憾,你没有猜对。正确答案是', word)
5.数字连连看游戏
python
import random
numbers = list(range(1, 9)) * 2
random.shuffle(numbers)
def display_board():
for i in range(0, 16, 4):
print(numbers[i:i+4])
def remove_numbers(x1, y1, x2, y2):
global numbers
numbers[x1*4+y1] = 0
numbers[x2*4+y2] = 0
def is_valid_move(x1, y1, x2, y2):
if x1 == x2 and abs(y1-y2) == 1:
return True
if y1 == y2 and abs(x1-x2) == 1:
return True
return False
display_board()
while True:
x1 = int(input('请输入第一个数字的行号(0-3):'))
y1 = int(input('请输入第一个数字的列号(0-3):'))
x2 = int(input('请输入第二个数字的行号(0-3):'))
y2 = int(input('请输入第二个数字的列号(0-3):'))
if is_valid_move(x1, y1, x2, y2) and numbers[x1*4+y1] == numbers[x2*4+y2]:
remove_numbers(x1, y1, x2, y2)
display_board()
if all(num == 0 for num in numbers):
print('恭喜你,游戏结束!')
break
else:
print('无效的移动,请重新输入。')
- 猜单词游戏(升级版)
python
import random
words = ['apple', 'banana', 'cherry', 'orange', 'pear']
word = random.choice(words)
letters = set(word)
correct_guesses = set()
incorrect_guesses = set()
tries = 6
while tries > 0 and letters != correct_guesses:
print('可用次数:', tries)
print('已猜对的字母:', ' '.join(correct_guesses))
print('已猜错的字母:', ' '.join(incorrect_guesses))
guess = input('请猜一个字母或整个单词:')
if len(guess) == 1:
if guess in letters:
correct_guesses.add(guess)
else:
incorrect_guesses.add(guess)
tries -= 1
else:
if guess == word:
correct_guesses = letters
else:
incorrect_guesses.add(guess)
tries -= 1
if letters == correct_guesses:
print('恭喜你,猜对了!单词是', word)
else:
print('很遗憾,你没有猜对。正确答案是', word)
- 猜数字游戏(升级版)
python
import random
number = random.randint(1, 100)
guesses = []
while len(guesses) < 10:
guess = int(input('请猜一个1到100之间的数字:'))
if guess in guesses:
print('你已经猜过这个数字了,请重新输入。')
continue
guesses.append(guess)
if guess == number:
print('恭喜你,猜对了!你用了', len(guesses), '次猜中了这个数字。')
break
elif guess < number:
print('猜小了')
else:
print('猜大了')
else:
print('很遗憾,你没有在规定次数内猜对。正确答案是', number)
这个游戏中,玩家需要在10次之内猜出一个1到100之间的随机数字。每次猜测后,程序会告诉玩家猜的数字是偏大还是偏小,直到玩家猜中这个数字或者用完所有的猜测次数为止。如果玩家在规定次数内猜中了这个数字,则游戏胜利;否则游戏失败。
- 猜拳游戏(升级版)
python
import random
options = ['石头', '剪刀', '布']
wins = {'石头': '剪刀', '剪刀': '布', '布': '石头'}
computer_score = 0
player_score = 0
while True:
computer_choice = random.choice(options)
player_choice = input('请出拳(石头、剪刀、布):')
print('你出了', player_choice)
print('电脑出了', computer_choice)
if player_choice == computer_choice:
print('平局')
elif wins[player_choice] == computer_choice:
print('你赢了')
player_score += 1
else:
print('你输了')
computer_score += 1
print('当前得分:电脑', computer_score, ', 玩家', player_score)
if computer_score == 3 or player_score == 3:
break
if computer_score > player_score:
print('很遗憾,你输了。')
else:
print('恭喜你,你赢了!')
这个游戏中,玩家和电脑进行猜拳比赛,先达到3分的一方获胜。玩家每次可以选择石头、剪刀或布中的一种,电脑也会随机选择其中的一种。根据石头、剪刀、布之间的胜负关系,程序会判断哪一方获胜,并更新双方的得分。当有一方的得分达到3分时,游戏结束,获得3分的一方获胜。
9.俄罗斯方块
# 导入必要的库
import pygame
import random
# 初始化pygame
pygame.init()
# 定义常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
FONT_SIZE = 36
FPS = 60
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 定义方块形状
SHAPES = [
[[1, 1, 1], [0, 1, 0]],
[[2, 2], [2, 2]],
[[0, 3, 3], [3, 3, 0]],
[[4, 4, 0], [0, 4, 4]],
[[5, 5, 5, 5]],
[[6, 6, 6], [0, 0, 6]],
[[7, 7, 7], [7, 0, 0]],
]
# 定义方块颜色
COLORS = [
BLUE,
YELLOW,
GREEN,
RED,
WHITE,
(255, 165, 0),
(128, 0, 128),
]
# 定义方块类
class Block:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = COLORS[SHAPES.index(shape)]
self.rotation = 0
def rotate(self):
self.rotation = (self.rotation + 1) % len(self.shape)
def get_matrix(self):
return self.shape[self.rotation]
def get_size(self):
return len(self.get_matrix()), len(self.get_matrix()[0])
def get_color(self):
return self.color
# 定义游戏类
class Game:
def __init__(self):
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
self.clock = pygame.time.Clock()
self.font = pygame.font.Font(None, FONT_SIZE)
self.score = 0
self.board = [[0] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
self.current_block = Block(3, 0, random.choice(SHAPES))
self.next_block = Block(0, 0, random.choice(SHAPES))
self.game_over = False
def draw_block(self, x, y, color):
pygame.draw.rect(self.screen, color, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
def draw_board(self):
for y, row in enumerate(self.board):
for x, val in enumerate(row):
if val > 0:
self.draw_block(x, y, COLORS[val - 1])
def draw_current_block(self):
matrix = self.current_block.get_matrix()
size_x, size_y = self.current_block.get_size()
for y in range(size_y):
for x in range(size_x):
if matrix[y][x] > 0:
self.draw_block(self.current_block.x + x, self.current_block.y + y, self.current_block.get_color())
def draw_next_block(self):
matrix = self.next_block.get_matrix()
size_x, size_y = self.next_block.get_size()
for y in range(size_y):
for x in range(size_x):
if matrix[y][x] > 0:
self.draw_block(x + SCREEN_WIDTH // BLOCK_SIZE + 2, y + SCREEN_HEIGHT // BLOCK_SIZE // 2, self.next_block.get_color())
def draw_score(self):
score_text = self.font.render("Score: {}".format(self.score), True, WHITE)
self.screen.blit(score_text, (10, 10))
def check_collision(self, block, dx=0, dy=0):
matrix = block.get_matrix()
size_x, size_y = block.get_size()
for y in range(size_y):
for x in range(size_x):
if matrix[y][x] > 0:
if block.x + x + dx < 0 or block.x + x + dx >= SCREEN_WIDTH // BLOCK_SIZE:
return True
if block.y + y + dy >= SCREEN_HEIGHT // BLOCK_SIZE:
return True
if self.board[block.y + y + dy][block.x + x + dx] > 0:
return True
return False
def merge_block(self, block):
matrix = block.get_matrix()
size_x, size_y = block.get_size()
for y in range(size_y):
for x in range(size_x):
if matrix[y][x] > 0:
self.board[block.y + y][block.x + x] = matrix[y][x]
def remove_lines(self):
lines_removed = 0
y = SCREEN_HEIGHT // BLOCK_SIZE - 1
while y >= 0:
if all(self.board[y]):
lines_removed += 1
for y2 in range(y, 0, -1):
self.board[y2] = self.board[y2 - 1][:]
self.board[0] = [0] * (SCREEN_WIDTH // BLOCK_SIZE)
else:
y -= 1
self.score += lines_removed * 100
def update(self):
if not self.check_collision(self.current_block, dy=1):
self.current_block.y += 1
else:
self.merge_block(self.current_block)
self.remove_lines()
self.current_block = self.next_block
self.next_block = Block(0, 0, random.choice(SHAPES))
if self.check_collision(self.current_block):
self.game_over = True
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and not self.check_collision(self.current_block, dx=-1):
self.current_block.x -= 1
if event.key == pygame.K_RIGHT and not self.check_collision(self.current_block, dx=1):
self.current_block.x += 1
if event.key == pygame.K_UP:
self.current_block.rotate()
if self.check_collision(self.current_block):
self.current_block.rotate()
self.current_block.rotate()
self.current_block.rotate()
if event.key == pygame.K_DOWN and not self.check_collision(self.current_block, dy=1):
self.current_block.y += 1
def run(self):
while not self.game_over:
self.screen.fill(BLACK)
self.draw_board()
self.draw_current_block()
self.draw_next_block()
self.draw_score()
pygame.display.update()
self.handle_events()
self.update()
self.clock.tick(FPS)
pygame.quit()
if __name__ == "__main__":
game = Game()
game.run()
10贪吃蛇代码
# 导入必要的库
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = SCREEN_WIDTH / 2
snake_y = SCREEN_HEIGHT / 2
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, SCREEN_WIDTH - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - food_block_size) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义分数
score = 0
# 定义游戏结束函数
def game_over():
message = font_style.render("游戏结束", True, RED)
screen.blit(message, [SCREEN_WIDTH / 3, SCREEN_HEIGHT / 3])
pygame.display.update()
pygame.time.delay(2000)
# 游戏循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
# 控制蛇的移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block_size
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block_size
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block_size
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block_size
snake_x_change = 0
# 控制蛇的移动
snake_x += snake_x_change
snake_y += snake_y_change
# 判断蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, SCREEN_WIDTH - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - food_block_size) / 10.0) * 10.0
snake_length += 1
score += 10
# 绘制食物
pygame.draw.rect(screen, GREEN, [food_x, food_y, food_block_size, food_block_size])
# 绘制蛇
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over_flag = True
for x in snake_list:
pygame.draw.rect(screen, BLUE, [x[0], x[1], snake_block_size, snake_block_size])
# 绘制分数
score_message = font_style.render("分数: " + str(score), True, BLACK)
screen.blit(score_message, [0, 0])
# 更新屏幕
pygame.display.update()
# 判断蛇是否撞墙
if snake_x >= SCREEN_WIDTH or snake_x < 0 or snake_y >= SCREEN_HEIGHT or snake_y < 0:
game_over_flag = True
# 控制游戏速度
pygame.time.delay(snake_speed)
# 结束pygame
pygame.quit()
这里需要补充一下 snake_x += snake_x_change snake_y += snake_y_change的初始化
11雷霆战机(待编写)
import pygame
import random
# Initialize Pygame
pygame.init()
# Set the screen size
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# Set the window title
pygame.display.set_caption("Thunder Plane")
# Load the background image
background = pygame.image.load("images/background.png")
# Load the player image
player = pygame.image.load("images/me1.png")
# Set the player's initial position
player_rect = player.get_rect()
player_rect.left = (screen_width - player_rect.width) // 2
player_rect.top = screen_height - player_rect.height - 60
# Set the player's movement speed
player_speed = 10
# Load the enemy images
enemy1 = pygame.image.load("images/enemy1.png")
enemy2 = pygame.image.load("images/enemy2.png")
enemy3 = pygame.image.load("images/enemy3.png")
# Set the enemy's initial position and movement speed
enemies = []
enemy_speed = 2
for i in range(5):
enemy_rect = enemy1.get_rect()
enemy_rect.left = random.randint(0, screen_width - enemy_rect.width)
enemy_rect.top = random.randint(-5 * enemy_rect.height, -enemy_rect.height)
enemies.append({"rect": enemy_rect, "image": enemy1})
# Set the game clock
clock = pygame.time.Clock()
# Set the score
score = 0
# Set the font
font = pygame.font.Font(None, 36)
# Set the game over flag
game_over = False
# Start the game loop
while not game_over:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Move the player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.left -= player_speed
if keys[pygame.K_RIGHT]:
player_rect.left += player_speed
if keys[pygame.K_UP]:
player_rect.top -= player_speed
if keys[pygame.K_DOWN]:
player_rect.top += player_speed
# Keep the player within the screen bounds
if player_rect.left < 0:
player_rect.left = 0
if player_rect.right > screen_width:
player_rect.right = screen_width
if player_rect.top < 0:
player_rect.top = 0
if player_rect.bottom > screen_height:
player_rect.bottom = screen_height
# Move the enemies
for enemy in enemies:
enemy["rect"].top += enemy_speed
if enemy["rect"].top > screen_height:
enemy["rect"].left = random.randint(0, screen_width - enemy["rect"].width)
enemy["rect"].top = random.randint(-5 * enemy["rect"].height, -enemy["rect"].height)
# Check for collisions
for enemy in enemies:
if player_rect.colliderect(enemy["rect"]):
game_over = True
# Draw the background
screen.blit(background, (0, 0))
# Draw the player
screen.blit(player, player_rect)
# Draw the enemies
for enemy in enemies:
screen.blit(enemy["image"], enemy["rect"])
# Draw the score
score_text = font.render("Score: {}".format(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# Update the screen
pygame.display.update()
# Set the game clock
clock.tick(60)
# Quit Pygame
pygame.quit()
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)