import pygame
import random
# 游戏窗口大小
width = 640
height = 480
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [((width // 2), (height // 2))]
self.direction = random.choice([up, down, left, right])
self.color = (0, 255, 0) # 绿色
def get_head_position(self):
return self.positions[0]
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x*gridsize)) % width), (cur[1] + (y*gridsize)) % height)
if len(self.positions) > 2 and 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 = [((width // 2), (height // 2))]
self.direction = random.choice([up, down, left, right])
def draw(self, surface):
for p in self.positions:
pygame.draw.rect(surface, self.color, (p[0], p[1], gridsize, gridsize))
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.color = (255, 0, 0) # 红色
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, width//gridsize-1)*gridsize,
random.randint(0, height//gridsize-1)*gridsize)
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], gridsize, gridsize))
# 游戏初始化
pygame.init()
window = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
clock = pygame.time.Clock()
snake = Snake()
food = Food()
# 定义方向
up = (0, -1)
down = (0, 1)
left = (-1, 0)
right = (1, 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_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
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
food.randomize_position()
window.fill((0, 0, 0)) # 清空窗口
snake.draw(window)
food.draw(window)
pygame.display.update()
clock.tick(10) # 控制帧率
利用ChatGPT生成的简单Python 贪吃蛇
于 2023-05-24 18:56:22 首次发布