用python写一个贪吃蛇
时间: 2023-07-01 20:09:26 浏览: 109
使用Python写一个贪吃蛇游戏实例代码
好的,下面是一个简单的贪吃蛇游戏,使用Python语言编写:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义屏幕大小和方块大小
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
BLOCK_SIZE = 10
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = RED
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:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, 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, WHITE, r, 1)
def handle_keys(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.turn(UP)
elif event.key == pygame.K_DOWN:
self.turn(DOWN)
elif event.key == pygame.K_LEFT:
self.turn(LEFT)
elif event.key == pygame.K_RIGHT:
self.turn(RIGHT)
# 定义食物类
class Food:
def __init__(self):
x = random.randrange(BLOCK_SIZE, SCREEN_WIDTH - BLOCK_SIZE, BLOCK_SIZE)
y = random.randrange(BLOCK_SIZE, SCREEN_HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
self.position = (x, y)
self.color = WHITE
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)
# 定义方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏主循环
while True:
screen.fill(BLACK)
snake.handle_keys()
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 判断是否结束游戏
if snake.get_head_position()[0] < 0 or snake.get_head_position()[0] > SCREEN_WIDTH - BLOCK_SIZE:
snake.reset()
elif snake.get_head_position()[1] < 0 or snake.get_head_position()[1] > SCREEN_HEIGHT - BLOCK_SIZE:
snake.reset()
# 控制游戏速度
pygame.time.delay(50)
```
这个贪吃蛇游戏使用 Pygame 模块实现,运行代码后可以在窗口中玩游戏。玩法和经典贪吃蛇游戏相同,通过方向键控制贪吃蛇的移动,吃到食物后贪吃蛇长度加一,撞到墙壁或自己的身体则游戏结束。
阅读全文