赞
踩
在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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。