Я не знаю, где вызвать функцию.Pygame - PullRequest
0 голосов
/ 27 февраля 2019

Я переделываю игру змея.И есть движущаяся функция и не знаю, где ее вызвать.Змея - это зеленый прямоугольник

, функция перед циклом while.это заставить другие сегменты змеи переместиться в позицию последнего сегмента.

вот код на данный момент:

import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
ax = 0
ay = 0
x = 0
y = 0
sa = 0
sizex = 500
sizey = 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
pygame.display.set_icon(pygame.image.load('images/tile.png'))
tile = pygame.image.load('images/tile.png')
tile = pygame.transform.scale(tile, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx = 0
sy = 0
vel_x = 0
vel_y = 0
ap = True

snake_parts = []   # /N/ Pygame rects 

def slither( new_head_coord ):
    # Move each body part to the location of the previous part
    # So we iterate over the tail-parts in reverse
    for i in range( len( snake_parts )-1, 0, -1 ):
        x, y = snake_parts[i-1].centerx, snake_parts[i-1].centery
        snake_parts[i].center = ( x, y )
    # Move the head
    snake_parts[0].centre = new_head_coord

while True:
    sx = x
    sy = y
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    for row in range(sizex):
        for column in range(sizey):
            screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_y = -25
                vel_x = 0
            elif event.key == K_DOWN:
                vel_y = 25
                vel_x = 0
            elif event.key == K_LEFT:
                vel_x = - 25
                vel_y = 0
            elif event.key == K_RIGHT:
                vel_x= 25
                vel_y = 0
            elif event.key == K_y:
                pag = 1
            elif event.key == K_n:
                pag = 2


    inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
    if inBounds:
        y += vel_y
        x += vel_x
    else:
        basicFont = pygame.font.SysFont(None, 48)
        text = basicFont.render('Game Over! Play again? y/n', True, GREEN, RED)
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery
        pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
        screen.blit(text, textRect)
        ay = -25
        ax = -25
        x = -25
        y = -25
        if pag == 1:
            pag = 0
            inBounds = True
            x = 0
            y = 0
            vel_x = 0
            vel_y = 0
            ax = random.choice(ran)
            ay = random.choice(ran)
            pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
        if pag == 2:
            pygame.quit()
            sys.exit()

    if ap:
        pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
    if x == ax and y == ay:
        pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
        ax = random.choice(ran)
        ay = random.choice(ran)
        sa += 1
    pygame.draw.rect(screen, GREEN, pygame.Rect(x,y,tilesize,tilesize))
    pygame.display.update()
    clock.tick(100)

Я не совсем уверен, как использовать функциитем не менее, так как я изучаю Python всего несколько недель.

1 Ответ

0 голосов
/ 27 февраля 2019

Добавить новую функцию, которая рисует змею:

def drawSnake():
    for p in snake_parts: 
        screen.blit(shake, p.topleft)

Конечно, вы можете нарисовать изображение вместо recatangl.snake - это изображение типа pygame.Surface:

def drawSnake():
    for p in snake_parts: 
        pygame.draw.rect(screen, RED, p)

Добавить голову в список snake_parts перед основным циклом (перед while True:):

snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)

Используйте drawSnake, чтобы нарисовать змею и обновить позиции частей прямо перед:

slither( (x, y) )
if ap:
    pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
    pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
    ax, ay = random.choice(ran), random.choice(ran)
    sa += 1
    snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))

drawSnake()
pygame.display.update()

В slither есть опечатка.Это должно быть snake_parts[0].center, а не snake_parts[0].centre.Но в любом случае, в вашем случае происхождение пар змеи составляет topleft, а не center.Измените функцию slither:

def slither( new_head_coord ):
    for i in range( len(snake_parts)-1, 0, -1 ):
        snake_parts[i] = snake_parts[i-1].copy()
    snake_parts[0].topleft = new_head_coord

Выполните только 1 цикл событий в основном цикле:

например

run = True
while run:
    sx, sy = x, y
    for row in range(sizex):
        for column in range(sizey):
            screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            run = False 
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_y = -25
                vel_x = 0
            # [...]

Демо

import pygame, sys, random
from pygame.locals import *

pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
sizex, sizey = 500, 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
tile = pygame.Surface((tilesize, tilesize))
tile.fill((0, 0, 64))
tile = pygame.transform.scale(tile, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx, sy = 0, 0
vel_x, vel_y = 0, 0
x, y = 0, 0
sa = 0
ap = True

snake_parts = []   # /N/ Pygame rects 

def slither( new_head_coord ):
    for i in range( len(snake_parts)-1, 0, -1 ):
        snake_parts[i] = snake_parts[i-1].copy()
    snake_parts[0].topleft = new_head_coord

def drawSnake():
    for p in snake_parts: 
        pygame.draw.rect(screen, GREEN, p)

snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
run = True
while run:
    sx, sy = x, y
    for row in range(sizex):
        for column in range(sizey):
            screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            run = False 
        if event.type == KEYDOWN:
            if event.key == K_UP:
                vel_x, vel_y = 0, -25
            elif event.key == K_DOWN:
                vel_x, vel_y = 0, 25
            elif event.key == K_LEFT:
                vel_x, vel_y = -25, 0
            elif event.key == K_RIGHT:
                vel_x, vel_y = 25, 0
            elif event.key == K_y:
                pag = 1
            elif event.key == K_n:
                pag = 2

    inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
    if inBounds:
        y += vel_y
        x += vel_x
    else:
        basicFont = pygame.font.SysFont(None, 48)
        text = basicFont.render('Game Over! Play again? y/n', True, GREEN, RED)
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery
        pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
        screen.blit(text, textRect)
        ax, ay = -25, -25
        x, y = -25, -25
        if pag == 1:
            pag = 0
            inBounds = True
            x, y = 0, 0
            vel_x, vel_y = 0, 0
            ax, ay = random.choice(ran), random.choice(ran)
            pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
        if pag == 2:
            pygame.quit()
            sys.exit()

    slither( (x, y) )
    if ap:
        pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
    if x == ax and y == ay:
        pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
        ax, ay = random.choice(ran), random.choice(ran)
        sa += 1
        snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))
    drawSnake()
    pygame.display.update()
    clock.tick(100)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...