使用python,85行代码实现贪吃蛇和关卡升级
你觉得你能坚持到第10关吗?
一、实现效果
二、环境要求
1.python 3+ 2.pygame包 安装命令:打开cmd 输入: pip install pygame
三、源码分享
import pygame
import sys
import random
SCREEN = {'x': 600, 'y': 600}
class Snake(object):
def __init__(self):
self.dirction, self.body = pygame.K_RIGHT, []
[self.add_node() for x 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))
if self.dirction == pygame.K_LEFT:
node.left -= 25
elif self.dirction == pygame.K_RIGHT:
node.left += 25
elif self.dirction == pygame.K_UP:
node.top -= 25
elif self.dirction == pygame.K_DOWN:
node.top += 25
self.body.insert(0, node)
def del_node(self):
self.body.pop()
def is_dead(self):
body_h = self.body[0]
if body_h.x not in range(SCREEN['x']) or body_h.y not in range(SCREEN['y']) or body_h in self.body[1:]:
return True
def move(self):
self.add_node()
self.del_node()
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 (curkey in LR) and (self.dirction in LR) or (curkey in UD) and (self.dirction in UD):
return
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['x'] - 75, 25)]
self.rect.left, self.rect.top = random.choice(allpos), random.choice(allpos)
def show_text(screen, pos, text, color, font_bold=False, font_size=30, font_italic=False):
cur_font = pygame.font.SysFont("SimHei", font_size, True)
cur_font.set_bold(font_bold)
cur_font.set_italic(font_italic)
text_fmt = cur_font.render(text, True, color)
screen.blit(text_fmt, pos)
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN['x'], SCREEN['y']))
pygame.display.set_caption('贪吃蛇:是男人就坚持到第10关!')
clock, scores, isdead = pygame.time.Clock(), 0, False
snake, food = Snake(), Food()
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), '翻车了!', (227, 29, 18), False, 80)
show_text(screen, (50, 320), '是男人就超过60KM/h,按空格键重试...', (0, 0, 22))
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 * 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()
在尽可能的保证代码易用性的情况下,减少代码行数!
这只是随便弄的一个小玩意,如果真要做游戏还是建议使用游戏引擎。
市面上常见的cocos、unity都是不错的游戏引擎,能够让你开发游戏的效率达到事半功倍的效果!
|