用PY做个贪吃蛇小游戏
时间: 2023-08-29 15:09:11 浏览: 81
当然可以!以下是一个简单的贪吃蛇小游戏的Python代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏窗口尺寸
window_width = 800
window_height = 600
# 蛇头和食物的大小
block_size = 20
# 设置游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 游戏时钟
clock = pygame.time.Clock()
# 设置蛇的初始位置和移动速度
snake_speed = 15
direction = "right"
def game_loop():
game_over = False
game_close = False
# 蛇的初始位置
x1 = window_width / 2
y1 = window_height / 2
# 蛇的移动速度
x1_change = 0
y1_change = 0
# 定义食物初始位置
food_x = round(random.randrange(0, window_width - block_size) / block_size) * block_size
food_y = round(random.randrange(0, window_height - block_size) / block_size) * block_size
while not game_over:
while game_close:
# 游戏结束时显示得分和重新开始选项
window.fill(black)
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("Game Over! Press Q-Quit or C-Play Again", True, white)
window.blit(message, [window_width / 6, window_height / 3])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
game_close = False
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 = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 判断蛇是否撞到边界
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
window.fill(black)
pygame.draw.rect(window, white, [food_x, food_y, block_size, block_size])
pygame.draw.rect(window, red, [x1, y1, block_size, block_size])
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, window_width - block_size) / block_size) * block_size
food_y = round(random.randrange(0, window_height - block_size) / block_size) * block_size
clock.tick(snake_speed)
pygame.quit()
# 运行游戏
game_loop()
```
这只是一个简单的贪吃蛇游戏示例,你可以根据自己的需要进行修改和扩展。希望对你有帮助!
阅读全文