用PYTHON写一个贪吃蛇的游戏
时间: 2023-05-25 11:03:53 浏览: 59
很抱歉,作为AI语言模型,我无法提供编程文件,但我可以为您提供一个基本的贪吃蛇游戏框架源代码,供您参考和学习:
```python
import pygame
import random
WIDTH = 800 # 窗口宽度
HEIGHT = 600 # 窗口高度
GRID_SIZE = 20 # 格子大小(即蛇头和蛇身的大小)
BG_COLOR = (169, 169, 169) # 背景颜色
SNAKE_COLOR = (0, 128, 0) # 蛇的颜色
FOOD_COLOR = (255, 0, 0) # 食物的颜色
class Snake:
def __init__(self):
self.body = [(3 * GRID_SIZE, 3 * GRID_SIZE), (2 * GRID_SIZE, 3 * GRID_SIZE), (GRID_SIZE, 3 * GRID_SIZE)] # 蛇身的坐标列表
self.direction = "right" # 蛇的方向
def move(self):
if self.direction == "up":
new_head = (self.body[0][0], self.body[0][1] - GRID_SIZE)
elif self.direction == "down":
new_head = (self.body[0][0], self.body[0][1] + GRID_SIZE)
elif self.direction == "left":
new_head = (self.body[0][0] - GRID_SIZE, self.body[0][1])
elif self.direction == "right":
new_head = (self.body[0][0] + GRID_SIZE, self.body[0][1])
self.body.insert(0, new_head)
self.body.pop()
def eat(self):
self.body.append(self.body[-1])
def draw(self, surface):
for i, segment in enumerate(self.body):
if i == 0:
segment_color = SNAKE_COLOR
else:
segment_color = (0, 255 - i * 20, 0)
pygame.draw.rect(surface, segment_color, pygame.Rect(segment[0], segment[1], GRID_SIZE, GRID_SIZE))
class Food:
def __init__(self):
self.position = (random.randint(0, WIDTH // GRID_SIZE - 1) * GRID_SIZE, random.randint(0, HEIGHT // GRID_SIZE - 1) * GRID_SIZE) # 食物的坐标
def reset_position(self):
self.position = (random.randint(0, WIDTH // GRID_SIZE - 1) * GRID_SIZE, random.randint(0, HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
def draw(self, surface):
pygame.draw.rect(surface, FOOD_COLOR, pygame.Rect(self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 24)
snake = Snake()
food = Food()
score = 0
running = True
while running:
clock.tick(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction != "down":
snake.direction = "up"
elif event.key == pygame.K_DOWN and snake.direction != "up":
snake.direction = "down"
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
elif event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
if snake.body[0][0] < 0 or snake.body[0][0] > WIDTH - GRID_SIZE or snake.body[0][1] < 0 or snake.body[0][1] > HEIGHT - GRID_SIZE:
running = False
for segment in snake.body[1:]:
if snake.body[0] == segment:
running = False
if snake.body[0] == food.position:
snake.eat()
food.reset_position()
score += 10
screen.fill(BG_COLOR)
snake.move()
snake.draw(screen)
food.draw(screen)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
```
这只是一个基本的贪吃蛇游戏框架,您可以根据这个基础代码进行修改和完善,实现更多的游戏功能和特效。