import pygame
import random
import sys
SCREEN, dirction_node = 600, {
pygame.K_LEFT: ['left', -25], pygame.K_RIGHT: ['right', 25], pygame.K_UP: ['top', -25],
pygame.K_DOWN: ['top', 25]}
class Snake:
def __init__(self):
self.dirction, self.body = pygame.K_RIGHT, []
[self.add_node() for _ in range(5)]
def add_node(self):
node = pygame.Rect(((self.body[0].left, self.body[0].top) if self.body else (0, 0)) + (25, 25))
setattr(node, dirction_node[self.dirction][0],
getattr(node, dirction_node[self.dirction][0]) + dirction_node[self.dirction][1])
self.body.insert(0, node)
def is_dead(self):
body_h = self.body[0]
if body_h.x not in range(SCREEN) or body_h.y not in range(SCREEN) or body_h in self.body[1:]:
return True
def move(self):
self.add_node()
self.body.pop()
def change_direction(self, curkey):
LR, UD = [pygame.K_LEFT, pygame.K_RIGHT], [pygame.K_UP, pygame.K_DOWN]
if curkey in LR + UD:
if not ((curkey in LR) and (self.dirction in LR) or (curkey in UD) and (self.dirction in UD)):
self.dirction = curkey
class Food:
def __init__(self):
self.rect = pygame.Rect(-25, 0, 25, 25)
def remove(self):
self.rect.x = -25
def set(self):
if self.rect.x == -25:
allpos = [pos for pos in range(75, SCREEN - 75, 25)]
self.rect.left, self.rect.top = random.choice(allpos), random.choice(allpos)
def show_text(screen, pos, text, color, font_size=30):
cur_font = pygame.font.SysFont("SimHei", font_size)
text_fmt = cur_font.render(text, True, color)
screen.blit(text_fmt, pos)
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN, SCREEN))
pygame.display.set_caption('贪吃蛇')
snake, food, clock, scores, isdead = Snake(), Food(), pygame.time.Clock(), 0, False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
snake.change_direction(event.key)
if event.key == pygame.K_SPACE and isdead:
return main()
screen.fill((255, 255, 255))
if not isdead:
snake.move()
for rect in snake.body:
pygame.draw.rect(screen, (144, 238, 144), rect)
isdead = snake.is_dead()
if isdead:
show_text(screen, (150, 200), '翻车了!', (255, 29, 188), 80)
show_text(screen, (50, 320), ' ...按空格键重试...', (78, 78, 242))
if food.rect == snake.body[0]:
scores += 1
food.remove()
snake.add_node()
food.set()
pygame.draw.rect(screen, (233, 150, 122), food.rect)
speed = 10 + scores * 3.5 if scores else 10
show_text(screen, (20, 550), '关卡:' + str(scores) + ' 速度:' + str(speed) + 'KM/h', (0, 0, 205))
pygame.display.update()
clock.tick(speed)
main()
蛮有意思的哦!
原文地址贪吃蛇源代码出处