Python 简易版贪食蛇(源代码)

Python 简易版贪食蛇

简易版贪食蛇代码如下,直接运行即可。

1. 效果图

在这里插入图片描述

2.源代码

源代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygame as pygame
import random
import sys

from pygame.rect import Rect


class Snake(object):
    def __init__(self):
        self.black = pygame.Color(0, 0, 0)
        self.green = pygame.Color(0, 255, 0)
        self.white = pygame.Color(255, 255, 255)

    def gameover(self):
        pygame.quit()
        sys.exit()

    def initialize(self):
        pygame.init()
        clock = pygame.time.Clock()

        playSurface = pygame.display.set_mode((800, 600))

        pygame.display.set_caption('tanshishe')

        snakePosition = [80, 80]

        snakebody = [[80, 80], [60, 80], [40, 80]]

        targetPosition = [200, 400]
        targetflag = 1
        direction = 'right'

        changeDirection = direction
        self.main(snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface, clock)

    def main(self, snakebody, targetPosition, targetflag, direction, changeDirection, snakePosition, playSurface,
             clock):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        changeDirection = 'right'
                        print("向右转")
                    if event.key == pygame.K_LEFT:
                        changeDirection = 'left'
                        print("向左转")
                    if event.key == pygame.K_DOWN:
                        changeDirection = 'down'
                        print("向上走")
                    if event.key == pygame.K_UP:
                        changeDirection = 'up'
                        print("向下走")
                    if event.key == pygame.K_ESCAPE:
                        pygame.event.post(pygame.event.Event(pygame.QUIT))

            if (changeDirection == 'left' and not direction == 'right'):
                direction = changeDirection
            if (changeDirection == 'right' and not direction == 'left'):
                direction = changeDirection
            if (changeDirection == 'down' and not direction == 'up'):
                direction = changeDirection
            if (changeDirection == 'up' and not direction == 'down'):
                direction = changeDirection

            if direction == 'right':
                snakePosition[0] += 20
            if direction == 'left':
                snakePosition[0] -= 20
            if direction == 'down':
                snakePosition[1] += 20
            if direction == 'up':
                snakePosition[1] -= 20

            snakebody.insert(0, list(snakePosition))
            if (snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]):
                targetflag = 0
            else:
                snakebody.pop()
            if targetflag == 0:
                x = random.randrange(1, 40)
                y = random.randrange(1, 30)
                targetPosition = [int(x * 20), int(y * 20)]
                targetflag = 1

            playSurface.fill(self.black)
            for position in snakebody:
                pygame.draw.rect(playSurface, self.white, Rect(position[0], position[1], 20, 20))
                pygame.draw.rect(playSurface, self.green, Rect(targetPosition[0], targetPosition[1], 20, 20))

            pygame.display.flip()
            if (snakePosition[0] > 900 or snakePosition[0] < 0):
                snake.gameover()
            elif (snakePosition[1] > 800 or snakePosition[0] < 0):
                snake.gameover()
            for i in snakebody[1:]:
                if (snakePosition[0] == i[0] and snakePosition[1] == i[1]):
                    snake.gameover()
            clock.tick(5)


snake = Snake()
snake.initialize()
  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
贪食蛇(Snake)是一种经典的游戏,玩家通过控制蛇的移动来吃食物,蛇的长度会不断增长。下面是一个由Python编写的贪食蛇源代码示例: ```python import pygame import random WIDTH, HEIGHT = 640, 480 GRID_SIZE = 20 GRID_WIDTH = WIDTH // GRID_SIZE GRID_HEIGHT = HEIGHT // GRID_SIZE UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def draw_snake(snake): for block in snake: rect = pygame.Rect(block[0] * GRID_SIZE, block[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE) pygame.draw.rect(screen, (0, 255, 0), rect) def move_snake(snake, direction): head = (snake[0][0] + direction[0], snake[0][1] + direction[1]) snake.insert(0, head) snake.pop() def generate_food(): while True: x = random.randint(0, GRID_WIDTH - 1) y = random.randint(0, GRID_HEIGHT - 1) if (x, y) not in snake: return (x, y) pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() snake = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)] direction = RIGHT food = generate_food() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_w and direction != DOWN: direction = UP elif event.key == pygame.K_s and direction != UP: direction = DOWN elif event.key == pygame.K_a and direction != RIGHT: direction = LEFT elif event.key == pygame.K_d and direction != LEFT: direction = RIGHT move_snake(snake, direction) if snake[0] == food: food = generate_food() else: snake.pop() screen.fill((0, 0, 0)) draw_snake(snake) pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(food[0] * GRID_SIZE, food[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)) pygame.display.flip() clock.tick(10) pygame.quit() ``` 这段代码使用了pygame库来实现游戏的绘图与事件处理部分,snake列表存储贪食蛇的身体块的坐标,direction表示蛇的移动方向。通过键盘事件来控制蛇的移动方向,每帧更新蛇的位置并绘制在屏幕上,同时检测蛇是否吃到食物并更新食物的位置。游戏结束后调用`pygame.quit()`来退出pygame

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

这么神奇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值