我用python写一个简易版的游戏(贪吃蛇)

直接上代码!

import sys
import random
import pygame

# 面向对象
# 全局定义
SCREEN_X = 600
SCREEN_Y = 600

# 蛇
class Snake(object):
    # 属性:1.初始化的长度
    #      2.头 方向
    def __init__(self):
        self.direction = pygame.K_RIGHT  # 头方向默认右
        self.body = []  # 蛇的身子

        for x in range(5):
            self.add_node()

    # 方法:1.吃
    #      2.死亡
    #      3.移动
    def add_node(self):
        left, top = (0, 0)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.direction == pygame.K_LEFT:
            node.left -= 25
        elif self.direction == pygame.K_RIGHT:
            node.left += 25
        elif self.direction == pygame.K_UP:
            node.top -= 25
        elif self.direction == pygame.K_DOWN:
            node.top += 25
        self.body.insert(0, node)

    # 删除
    def del_node(self):
        self.body.pop()

    # 死亡判断
    def is_dead(self):
        # 撞墙
        if not 0 <= self.body[0].x < SCREEN_X or not 0 <= self.body[0].y < SCREEN_Y:
            return True
        return False

    # 移动
    def move(self):
        self.add_node()
        self.del_node()

    # 改变方向
    def change_direction(self, cur_key):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if cur_key in LR + UD:
            if (cur_key in LR) and (self.direction in LR):
                return
            if (cur_key in UD) and (self.direction in UD):
                return
            self.direction = cur_key

# 食物(小方格)
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:
            all_pos = []
            for pos in range(25, SCREEN_X - 25, 25):
                all_pos.append(pos)
            self.rect.left = random.choice(all_pos)
            self.rect.top = random.choice(all_pos)

def show_text(screen, pos, text, color, font_bold=False, font_size=60, font_italic=False):
    cur_font = pygame.font.SysFont("宋体", font_size)
    cur_font.set_bold(font_bold)
    cur_font.set_italic(font_italic)
    text_fmt = cur_font.render(text, 1, color)
    screen.blit(text_fmt, pos)


def main():
    pygame.init()
    screen_size = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('贪吃蛇')
    clock = pygame.time.Clock()

    scores = 0
    is_dead = False
    game_started = False

    snake = Snake()
    food = Food()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if not game_started:
                    if event.key == pygame.K_SPACE:
                        game_started = True
                else:
                    snake.change_direction(event.key)

        screen.fill((255, 255, 255))

        if not game_started:
            show_text(screen, (150, 200), 'Press SPACE to start the game', (0, 0, 0), False, 30)

        if game_started:
            if not is_dead:
                snake.move()
            for rect in snake.body:
                pygame.draw.rect(screen, (20, 220, 39), rect, 0)

            is_dead = snake.is_dead()

            if is_dead:
                show_text(screen, (100, 200), 'YOU DEAD!', (227, 29, 18), False, 100)
                show_text(screen, (150, 260), 'press space to try again.....', (0, 0, 22), False, 30)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    is_dead = False
                    scores = 0
                    snake = Snake()
                    food = Food()
                    game_started = False  # Reset game_started to False

            if not is_dead:
                if food.rect == snake.body[0]:
                    scores += 50
                    food.remove()
                    snake.add_node()

                food.set()
                pygame.draw.rect(screen, (136, 0, 24), food.rect, 0)

                show_text(screen, (50, 500), 'Scores: ' + str(scores), (223, 223, 223))

        pygame.display.update()
        clock.tick(10)


main()

运行后的效果是这样的:

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值