python代码贪吃蛇

在Python中实现贪吃蛇游戏,你可以使用pygame库。以下是一个简单的贪吃蛇游戏的实现示例:

import pygame

import sys

import random

# 初始化pygame

pygame.init()

# 设置屏幕大小和标题

screen_width = 600

screen_height = 480

screen = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption('贪吃蛇')

# 定义颜色常量

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

# 定义蛇的节点类

class Snake:

def __init__(self):

self.body = [pygame.Rect(250, 240, 20, 20)] # 蛇的初始位置

self.direction = 'right' # 蛇的初始方向

self.change_x = 20

self.change_y = 0

def move(self):

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_LEFT or event.key == pygame.K_a) and self.direction != 'right':

self.direction = 'left'

self.change_x = -20

self.change_y = 0

elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and self.direction != 'left':

self.direction = 'right'

self.change_x = 20

self.change_y = 0

elif (event.key == pygame.K_UP or event.key == pygame.K_w) and self.direction != 'down':

self.direction = 'up'

self.change_x = 0

self.change_y = -20

elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and self.direction != 'up':

self.direction = 'down'

self.change_x = 0

self.change_y = 20

head = self.body[0].copy()

head.move_ip(self.change_x, self.change_y)

self.body.insert(0, head)

def draw(self):

for rect in self.body:

pygame.draw.rect(screen, GREEN, rect)

pygame.draw.rect(screen, BLACK, rect, 1)

# 定义食物类

class Food:

def __init__(self):

self.rect = pygame.Rect(random.randint(0, screen_width - 20), random.randint(0, screen_height - 20), 20, 20)

def draw(self):

pygame.draw.rect(screen, RED, self.rect)

pygame.draw.rect(screen, BLACK, self.rect, 1)

# 游戏主循环

def main():

snake = Snake()

food = Food()

clock = pygame.time.Clock()

while True:

screen.fill(BLACK)

snake.move()

# 蛇吃食物

if snake.body[0].colliderect(food.rect):

snake.body.append(snake.body[-1].copy())

food.rect = pygame.Rect(random.randint(0, screen_width - 20), random.randint(0, screen_height - 20), 20, 20)

# 画蛇和食物

snake.draw()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值