# 小游戏代码大全
## 1. 猜数字游戏
### 游戏规则
玩家需要猜出程序生成的一个随机数字,程序会根据猜测结果提示玩家是猜大了还是猜小了,直到玩家猜中为止。
### 代码示例
“`python
import random
def guess_number():
target = random.randint(1, 100)
guess = -1
while guess != target:
guess = int(input(”请输入你的猜测数字:”))
if guess > target:
print(”猜大了!”)
elif guess < target:
print("猜小了!")
print("恭喜你,猜对了!")
guess_number()
“`
## 2. 石头剪刀布游戏
### 游戏规则
玩家需要与程序进行石头剪刀布游戏,玩家和程序在每轮中选择石头、剪刀或布,根据游戏规则判断胜负,直到达到预先设定的胜利次数。
### 代码示例
“`python
import random
def rock_paper_scissors():
choices = ["石头", "剪刀", "布"]
win_count = 0
lose_count = 0
while win_count < 3 and lose_count < 3:
player_choice = input("请选择石头、剪刀或布:")
computer_choice = random.choice(choices)
print("电脑选择了:" + computer_choice)
if player_choice == computer_choice:
print("平局!")
elif (player_choice == "石头" and computer_choice == "剪刀") or (player_choice == "剪刀" and computer_choice == "布") or (player_choice == "布" and computer_choice == "石头"):
print("你赢了!")
win_count += 1
else:
print("你输了!")
lose_count += 1
if win_count == 3:
print("恭喜你,你赢得了比赛!")
else:
print("很遗憾,你输了比赛!")
rock_paper_scissors()
“`
## 3. 贪吃蛇游戏
### 游戏规则
玩家需要通过操控贪吃蛇的移动,吃掉地图上的食物,避免与自己的身体或边界相撞,直到蛇的身体填满整个地图或者无法移动为止。
### 代码示例
“`python
import pygame
import random
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 20
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
class SnakeGame:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
self.clock = pygame.time.Clock()
def run(self):
snake = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)]
food = self.generate_food()
dx, dy = 1, 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and dy != 1:
dx, dy = 0, -1
elif keys[pygame.K_DOWN] and dy != -1:
dx, dy = 0, 1
elif keys[pygame.K_LEFT] and dx != 1:
dx, dy = -1, 0
elif keys[pygame.K_RIGHT] and dx != -1:
dx, dy = 1, 0
snake_head = (snake[0][0] + dx * GRID_SIZE, snake[0][1] + dy * GRID_SIZE)
snake.insert(0, snake_head)
if snake_head == food:
food = self.generate_food()
else:
snake.pop()
self.screen.fill((0, 0, 0))
self.draw_snake(snake)
self.draw_food(food)
pygame.display.update()
self.clock.tick(10)
def draw_snake(self, snake):
for segment in snake:
segment_rect = pygame.Rect(segment[0], segment[1], GRID_SIZE, GRID_SIZE)
pygame.draw.rect(self.screen, SNAKE_COLOR, segment_rect)
def draw_food(self, food):
food_rect = pygame.Rect(food[0], food[1], GRID_SIZE, GRID_SIZE)
pygame.draw.rect(self.screen, FOOD_COLOR, food_rect)
def generate_food(self):
x = random.randint(0, SCREEN_WIDTH // GRID_SIZE – 1) * GRID_SIZE
y = random.randint(0, SCREEN_HEIGHT // GRID_SIZE – 1) * GRID_SIZE
return (x, y)
game = SnakeGame()
game.run()
“`
以上是一些常见小游戏的代码示例,您可以根据自己的需要进行修改和扩展,玩得开心!