帮我用python编一个弹窗贪吃蛇游戏
当然可以帮您编写一个弹窗贪吃蛇游戏。以下是一个简单的示例代码:
import pygame
import random
# 初始化游戏
pygame.init()
# 定义常量
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
SNAKE_SIZE = 20
SNAKE_SPEED = 10
APPLE_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 创建窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [((WINDOW_WIDTH // 2), (WINDOW_HEIGHT // 2))]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
self.color = RED
def get_head_position(self):
return self.positions[0]
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x * SNAKE_SIZE)) % WINDOW_WIDTH), (cur[1] + (y * SNAKE_SIZE)) % WINDOW_HEIGHT)
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [((WINDOW_WIDTH // 2), (WINDOW_HEIGHT // 2))]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
def draw(self, surface):
for p in self.positions:
pygame.draw.rect(surface, self.color, (p[0], p[1], SNAKE_SIZE, SNAKE_SIZE))
# 定义苹果类
class Apple:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, (WINDOW_WIDTH - APPLE_SIZE) // APPLE_SIZE) * APPLE_SIZE,
random.randint(0, (WINDOW_HEIGHT - APPLE_SIZE) // APPLE_SIZE) * APPLE_SIZE)
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], APPLE_SIZE, APPLE_SIZE))
# 初始化贪吃蛇和苹果
snake = Snake()
apple = Apple()
# 游戏主循环
running = True
clock = pygame.time.Clock()
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_UP and snake.direction != (0, 1):
snake.direction = (0, -1)
elif event.key == pygame.K_DOWN and snake.direction != (0, -1):
snake.direction = (0, 1)
elif event.key == pygame.K_LEFT and snake.direction != (1, 0):
snake.direction = (-1, 0)
elif event.key == pygame.K_RIGHT and snake.direction != (-1, 0):
snake.direction = (1, 0)
snake.move()
if snake.get_head_position() == apple.position:
snake.length += 1
apple.randomize_position()
window.fill(BLACK)
snake.draw(window)
apple.draw(window)
pygame.display.update()
clock.tick(SNAKE_SPEED)
# 退出游戏
pygame.quit()
运行这段代码,将会弹出一个窗口,您可以使用上下左右箭头控制贪吃蛇的移动,目标是吃掉苹果,每吃一个苹果贪吃蛇的长度会增加
原文地址: https://www.cveoy.top/t/topic/iyjh 著作权归作者所有。请勿转载和采集!