python贪吃蛇游戏
时间: 2023-07-09 18:53:20 浏览: 52
好的,下面给你提供一个简单的Python贪吃蛇游戏示例代码,你可以在此基础上进行修改和完善:
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义方块大小和速度
BLOCK_SIZE = 20
SPEED = 10
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("贪吃蛇")
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(random.randint(0, 39) * BLOCK_SIZE, random.randint(0, 29) * BLOCK_SIZE)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x * BLOCK_SIZE)), (cur[1] + (y * BLOCK_SIZE)))
if new in self.positions[2:]:
raise Exception("撞到自己了!")
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(random.randint(0, 39) * BLOCK_SIZE, random.randint(0, 29) * BLOCK_SIZE)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义食物类
class Food:
def __init__(self):
x = random.randint(0, 39) * BLOCK_SIZE
y = random.randint(0, 29) * BLOCK_SIZE
self.position = (x, y)
self.color = RED
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义游戏主循环
def game():
snake = Snake()
food = Food()
score = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
elif event.key == pygame.K_UP:
snake.turn((0, -1))
elif event.key == pygame.K_DOWN:
snake.turn((0, 1))
elif event.key == pygame.K_LEFT:
snake.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
snake.turn((1, 0))
screen.fill(WHITE)
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
score += 10
food = Food()
snake.draw(screen)
food.draw(screen)
text = font.render("得分: " + str(score), True, BLACK)
screen.blit(text, [0, 0])
pygame.display.update()
if snake.get_head_position()[0] < 0 or snake.get_head_position()[0] > 780:
snake.reset()
score = 0
if snake.get_head_position()[1] < 0 or snake.get_head_position()[1] > 580:
snake.reset()
score = 0
pygame.time.Clock().tick(SPEED)
# 启动游戏
game()
```
这是一个基本的贪吃蛇游戏,你可以根据自己的需求进行修改和添加新的功能。