Pygame蛇游戏-移动蛇



我正试图在pygame中构建蛇游戏。我用一个二维矢量来表示蛇
我写了这段代码来移动蛇,但由于某种原因,它不起作用。蛇非但没有移动,反而变大了。我想让这条蛇移动并保持它原来的大小。

def move_snake(self):
body_copy = self.body[:-1]
body_copy.insert(0, body_copy[0] + self.direction)
self.body = body_copy[:]

self-direction只是另一个向量,self-body是我刚才说的二维向量。

我不知道错误是否在move_snake方法中,所以我也在这里发布了我的完整代码。

import pygame
import sys
import random
from pygame.math import Vector2

pygame.init()
pygame.display.set_caption("Snake")
DARK_GREEN = (126, 166, 114)
STEEL_BLUE = (70, 130, 180)

CELL_SIZE = 40
CELL_NUMBER = 20
WIDTH, HEIGTH = CELL_SIZE * CELL_NUMBER, CELL_SIZE * CELL_NUMBER
FPS = 60
SCREEN = pygame.display.set_mode((WIDTH, HEIGTH))
SCREEN.fill((175, 215, 70))

class Snake:
def __init__(self):
self.body = [Vector2(5, 10), Vector2(6, 10), Vector2(7, 10)]
self.direction = Vector2(1, 0)
def draw_snake(self):
for block in self.body:
x_pos = int(block.x * CELL_SIZE)
y_pos = int(block.y * CELL_SIZE)
block_rect = pygame.Rect(x_pos, y_pos, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(SCREEN, STEEL_BLUE, block_rect)
def move_snake(self):
body_copy = self.body[:-1]
body_copy.insert(0, body_copy[0] + self.direction)
self.body = body_copy[:]

class Fruit:
def __init__(self):
self.x = random.randint(0, CELL_NUMBER - 1)
self.y = random.randint(0, CELL_NUMBER - 1)
self.pos = Vector2(self.x, self.y)
def draw_fruit(self):
fruit_rect = pygame.Rect(
int(self.pos.x * CELL_SIZE), int(self.pos.y * CELL_SIZE), CELL_SIZE, CELL_SIZE)
pygame.draw.rect(SCREEN, DARK_GREEN, fruit_rect)

def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
sys.exit()
if event.type == SCREEN_UPDATE:
snake.move_snake()
fruit.draw_fruit()
snake.draw_snake()
pygame.display.update()

fruit = Fruit()
snake = Snake()
SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE, 150)

main()

在绘制任何内容之前,您需要在循环中的某个位置设置screen.fill(color)(一个参数是游戏的背景色(,否则它将无法清除屏幕(换句话说,它将保留上次在屏幕上绘制的内容(。

最新更新