利用python的pygame实现贪吃蛇

创建界面

print("创建游戏窗口")
    # 导入GUI
    pygame.init()
    # 设置窗口尺寸
    screen = pygame.display.set_mode((800, 600))
    # 设置窗口标题
    pygame.display.set_caption("贪吃蛇")
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.quit():
                running = False

参数初始化

class Point:
    row = 0
    clo = 0

    def __init__(self, row, clo):
        self.row = row
        self.clo = clo

    def copy(self):
        return Point(row=self.row, clo=self.clo)
pygame.init()
# 初始化图形界面大小
GUI_width = 800
GUI_height = 400

ROW = 30
CLO = 40
# 初始化分数
game_score = 0

direct = 'left'
GUI_screen = pygame.display.set_mode((GUI_width, GUI_height))
pygame.display.set_caption('贪吃蛇游戏')

# 蛇头
head = Point(row=int(ROW / 2), clo=int(CLO / 2))
# 蛇身
snake = [
    Point(row=head.row, clo=head.clo + 1),
    Point(row=head.row, clo=head.clo + 2),
    Point(row=head.row, clo=head.clo + 3)
]

运行

running = True
# 设置帧频率
clock = pygame.time.Clock()
display_score_text = '得分:' + str(game_score)
try:
    score_font = pygame.font.SysFont('bahnschrift', 30)  # 创建一个font对象,显示结果
except FileNotFoundError:
    print("没有这个字体,下面是已安装的字体")
    print(pygame.font.get_fonts())
    score_font = pygame.font.Font(None, 30)
WhiteFont = (255, 255, 255)
while running:
    # 处理帧频 锁帧
    clock.tick(30)
    # pygame.event.get()获取当前事件的队列 可以同时发生很多事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            GUI_screen.blit(score_surface, (10, 5))  # 将结果绘制出来
            # 这里小细节蛇不可以直接左右上下 要判断当前是在什么状态下前行
            if event.key == 273 or event.key == 119:
                if direct == 'left' or direct == 'right':
                    direct = 'top'
            if event.key == 274 or event.key == 115:
                if direct == 'left' or direct == 'right':
                    direct = 'bottom'
            if event.key == 276 or event.key == 97:
                if direct == 'top' or direct == 'bottom':
                    direct = 'left'
            if event.key == 275 or event.key == 100:
                if direct == 'top' or direct == 'bottom':
                    direct = 'right'
    # 吃东西
    eat = (head.row == snake_food_location.row and head.clo == snake_food_location.clo)

    if eat:
        snake_food_location = Point(row=random.randint(0, ROW - 1), clo=random.randint(0, CLO - 1))
        game_score = game_score + 1
    snake.insert(0, head.copy())
    if not eat:
        snake.pop()

    # 移动一下
    if direct == 'left':
        head.clo -= 1
    if direct == 'right':
        head.clo += 1
    if direct == 'top':
        head.row -= 1
    if direct == 'bottom':
        head.row += 1
    dead = False
    if head.clo < 0 or head.row < 0 or head.clo >= CLO or head.row >= ROW:
        dead = True
    for body in snake:
        if head.clo == body.clo and head.row == body.row:
            dead = True
            break
    game_over = False
    if dead:
        print('Game Over')
        game_over = True
    # 背景画图
    pygame.draw.rect(GUI_screen, (245, 135, 155), (0, 0, GUI_width, GUI_height))
    score_surface = score_font.render("Score : %s" % str(game_score), True, WhiteFont)
    # 图像,绘制的位置,绘制的截面框
    GUI_screen.blit(score_surface, (0, 0), score_surface.get_rect())
    # 蛇头
    rect(head, head_color)
    # 绘制食物
    rect(snake_food_location, snake_food_color)
    # 绘制蛇的身子
    for body in snake:
        rect(body, snake_color)
    if game_over:
        running = False
        # pygame.quit()
        # break
        # quit()

    pygame.display.flip()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以为你提供一个简单的贪吃蛇小游戏实现。使用Pygame库,我们可以轻松地实现这个游戏。 首先,让我们导入需要的库: ```python import pygame import time import random ``` 接下来,我们需要定义一些常量,如窗口大小、蛇和食物大小、游戏速度等: ```python # 定义常量 SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 SNAKE_SIZE = 10 FOOD_SIZE = 10 SNAKE_SPEED = 15 ``` 然后,我们需要定义蛇和食物的类: ```python # 定义蛇类 class Snake: def __init__(self): self.position = [100, 50] self.body = [[100, 50], [90, 50], [80, 50]] self.direction = "RIGHT" self.changeDirectionTo = self.direction def changeDirTo(self, dir): if dir=="RIGHT" and not self.direction=="LEFT": self.direction = "RIGHT" if dir=="LEFT" and not self.direction=="RIGHT": self.direction = "LEFT" if dir=="UP" and not self.direction=="DOWN": self.direction = "UP" if dir=="DOWN" and not self.direction=="UP": self.direction = "DOWN" def move(self, foodPos): if self.direction == "RIGHT": self.position[0] += SNAKE_SIZE if self.direction == "LEFT": self.position[0] -= SNAKE_SIZE if self.direction == "UP": self.position[1] -= SNAKE_SIZE if self.direction == "DOWN": self.position[1] += SNAKE_SIZE self.body.insert(0, list(self.position)) if self.position == foodPos: return 1 else: self.body.pop() return 0 def checkCollision(self): if self.position[0] > SCREEN_WIDTH-SNAKE_SIZE or self.position[0] < 0: return 1 elif self.position[1] > SCREEN_HEIGHT-SNAKE_SIZE or self.position[1] < 0: return 1 for bodyPart in self.body[1:]: if self.position == bodyPart: return 1 return 0 def getHeadPos(self): return self.position def getBody(self): return self.body # 定义食物类 class Food: def __init__(self): self.position = [random.randrange(1,SCREEN_WIDTH/10)*10,random.randrange(1,SCREEN_HEIGHT/10)*10] self.color = (223,163,49) def spawnFood(self): self.position = [random.randrange(1,SCREEN_WIDTH/10)*10,random.randrange(1,SCREEN_HEIGHT/10)*10] def drawFood(self, surface): pygame.draw.rect(surface, self.color, pygame.Rect(self.position[0], self.position[1], FOOD_SIZE, FOOD_SIZE)) ``` 现在,我们可以在主函数中实例化蛇和食物,并在游戏循环中实现蛇的移动和碰撞检测,以及食物的生成和绘制: ```python # 定义主函数 def main(): pygame.init() pygame.display.set_caption("贪吃蛇") # 设置窗口 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # 实例化蛇和食物 snake = Snake() food = Food() # 游戏循环 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_RIGHT: snake.changeDirTo('RIGHT') if event.key == pygame.K_LEFT: snake.changeDirTo('LEFT') if event.key == pygame.K_UP: snake.changeDirTo('UP') if event.key == pygame.K_DOWN: snake.changeDirTo('DOWN') # 移动蛇 foodPos = food.position if snake.move(foodPos) == 1: food.spawnFood() # 检查碰撞 if snake.checkCollision() == 1: pygame.quit() quit() # 绘制游戏界面 screen.fill((0,0,0)) for pos in snake.getBody(): pygame.draw.rect(screen, (0,255,0), pygame.Rect(pos[0], pos[1], SNAKE_SIZE, SNAKE_SIZE)) food.drawFood(screen) pygame.display.update() # 控制游戏速度 clock = pygame.time.Clock() clock.tick(SNAKE_SPEED) ``` 现在,我们可以运行这个程序,尝试一下自己的贪吃蛇小游戏了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麦滋堡的摸鱼芝士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值