请用python写一个贪食蛇小游戏
时间: 2023-02-23 19:11:05 浏览: 97
贪食蛇_C++_wild73t_小游戏_贪食蛇小程序_
下面是一个简单的 Python 贪吃蛇小游戏,它使用 Pygame 模块实现。
```python
import pygame
import sys
import random
# Initialize game engine
pygame.init()
# Set up window
WIDTH = 800
HEIGHT = 600
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Snake block size
block_size = 10
# FPS
fps = pygame.time.Clock()
# Set up window
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇")
# Game over function
def game_over():
font = pygame.font.SysFont(None, 25)
text = font.render("游戏结束,按 Q 退出游戏", True, RED)
window.blit(text, [WIDTH/2-50, HEIGHT/2])
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Clear the screen
window.fill(WHITE)
# Draw the snake
# ...
# Draw the food
# ...
# Update screen
pygame.display.update()
# FPS
fps.tick(10)
# Check for collision with food
# ...
# Check for collision with walls or snake body
# ...
# Check if game over
# ...
```
这是一个基础的游戏框架,您可以根据自己的需求扩展它。例如,您可以使用键盘事件处理玩家的控制,并在每帧中更新蛇的位置。
希望对您有所帮助!
阅读全文