python pygame 蛇吃豆代码
时间: 2024-03-18 07:37:35 浏览: 122
Python Pygame是一个用于开发2D游戏的库,而蛇吃豆代码是一个经典的游戏示例。下面是一个简单的Python Pygame蛇吃豆代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")
# 定义蛇的初始位置和大小
snake_block_size = 20
snake_speed = 15
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
# 定义豆子的初始位置和大小
food_block_size = 20
food_x = round(random.randrange(0, screen_width - food_block_size) / 20) * 20
food_y = round(random.randrange(0, screen_height - food_block_size) / 20) * 20
clock = pygame.time.Clock()
# 定义蛇的移动函数
def snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block_size, snake_block_size])
# 游戏主循环
def game_loop():
game_over = False
game_close = False
# 蛇的初始长度
snake_list = []
length_of_snake = 1
while not game_over:
while game_close == True:
screen.fill(BLACK)
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("Game Over! Press Q-Quit or C-Play Again", True, RED)
screen.blit(message, [screen_width / 6, screen_height / 3])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断蛇是否撞到墙壁
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [food_x, food_y, food_block_size, food_block_size])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
# 判断蛇是否吃到豆子
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
snake(snake_block_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到豆子,如果吃到,则长度加1,并重新生成豆子
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, screen_width - food_block_size) / 20) * 20
food_y = round(random.randrange(0, screen_height - food_block_size) / 20) * 20
length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# 启动游戏循环
game_loop()
```
阅读全文