2015-06-05 3 views
1

Я новичок в Pygame и все еще изучаю Python. Я использую Python 3.4. Я следил за этим удивительным учебником по созданию игры: http://pythonprogramming.net/pygame-python-3-part-1-intro/ после завершения уроков я решил немного изменить игру и сумел добавить еще немного движения и исправил некоторые ошибки. однако теперь я пытаюсь выяснить, как изменить спрайт, когда я нажимаю клавишу со стрелкой, чтобы заставить его обращаться, как будто он наклоняется. У меня есть файл вызова racecar.png (который является плоскостью) и move_right (который выглядит как наклонный). Моя конечная цель - иметь его, когда я нажимаю стрелку вправо, отображается move_right.png до тех пор, пока я не отпущу ключ, и в этом случае он вернется к racecar.png. Я посмотрел, как использовать спрайт-листы, которые не удалось, как оживить, посмотрел на YouTube, искал мою проблему, но я не могу найти кого-либо еще, у кого есть эта проблема. большинство из того, что я нашел, говорили о перемещении спрайта вокруг экрана. вот код:Как сменить спрайт на экране после нажатия клавиши в pygame

import pygame 
import random 
import time 

pygame.init() 

car_width = 100 
car_height = 100 

display_width = 800 
display_height = 600 

gameDisplay = pygame.display.set_mode((display_width, display_height)) 
pygame.display.set_caption('A Macross Simumater') 

black = (0,0,0) 
white = (255, 255, 255) 
red = (255, 0,0) 
green = (0,255,0) 
greent = (0, 150, 0) 
blue = (0,0, 200) 
dark_blue = (0, 0, 50) 

clock = pygame.time.Clock() 

carImp = pygame.image.load('racecar.png') 

gameIcon = pygame.image.load('caricon.png') 

#background = pygame.image.load('background.png') 

pygame.display.set_icon(gameIcon) 

def quitgame(): 
    pygame.quit() 
    quit() 

def unpause(): 
    global pause 
    pause = False 

def paused(): 

    largeText = pygame.font.SysFont("comicsansms",115) 
    TextSurf, TextRect = text_objects("Paused", largeText) 
    TextRect.center = ((display_width/2),(display_height/2)) 
    gameDisplay.blit(TextSurf, TextRect) 


    while pause: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

     button("Continue",150,450,100,50,green,black,unpause) 
     button("Quit",550,450,100,50,red,black,quitgame) 

     pygame.display.update() 
     clock.tick(15) 


def things_dodged(count): 
    font = pygame.font.SysFont(None, 25) 
    text = font.render("Dodged: " + str(count), True, black) 
    gameDisplay.blit(text, (0,0)) 

def things(thingx, thingy, thingw, thingh, color): 
    pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) 

def car(x, y): 
    gameDisplay.blit(carImp, (x, y)) 

def text_objects(text, font): 
    textSurface = font.render(text, True, black) 
    return textSurface, textSurface.get_rect() 

def message_display(text): 
    largeText = pygame.font.Font('freesansbold.ttf', 115) 
    TextSurf, TextRect = text_objects(text, largeText) 
    TextRect.center = ((display_width/2), (display_height/2)) 
    gameDisplay.blit(TextSurf, TextRect) 

    pygame.display.update() 

    time.sleep(2) 

    game_loop() 

def crash(): 


    largeText = pygame.font.SysFont("comicsansms",115, (0, 0, 0)) 
    TextSurf, TextRect = text_objects("You Crashed", largeText) 
    TextRect.center = ((display_width/2),(display_height/2)) 
    gameDisplay.blit(TextSurf, TextRect) 


    while True: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

     button("Play Again",150,450,100,50,green,black,game_loop) 
     button("Quit",550,450,100,50,red,black,quitgame) 

     pygame.display.update() 
     clock.tick(15) 

def button(msg,x,y,w,h,ic,ac, action = None): 
    mouse = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed() 
    print(click) 

    if x+w > mouse[0] > x and y+h > mouse[1] > y: 
     pygame.draw.rect(gameDisplay, ac,(x, y, w, h)) 

     if click[0] == 1 and action != None: 
      action() 
    else: 
     pygame.draw.rect(gameDisplay, ic, (x, y, w, h)) 

    smallText = pygame.font.Font('freesansbold.ttf', 21) 
    textSurf, textRect = text_objects("GO!", smallText) 
    textRect.center = ((150+(100/2)), (450+(50/2))) 
    gameDisplay.blit(textSurf, textRect) 

    textSurf, textRect = text_objects("QUIT!", smallText) 
    textRect.center = ((550+(100/2)), (450+(50/2))) 
    gameDisplay.blit(textSurf, textRect) 

def game_intro(): 
    intro = True 
    while intro: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

     gameDisplay.fill(white) 
     largeText = pygame.font.Font('freesansbold.ttf', 115) 
     TextSurf, TextRect = text_objects('Macross',largeText) 
     TextRect.center = ((display_width/2), (display_height/2)) 
     gameDisplay.blit(TextSurf, TextRect) 

     mouse = pygame.mouse.get_pos() 

     button("GO!", 150, 450, 100, 50, green, black, game_loop) 
     button("Quit", 550,450,100,50, red, black, quitgame) 

     pygame.display.update() 
     clock.tick(15) 

def game_loop(): 
    global pause 

    pygame.mixer.music.load('Macross Plus - Voices HQ MV Karaoke Instrumental Japanese.mp3') 
    pygame.mixer.music.play(-1) 

    x = (display_width * 0.45) 
    y = (display_height * 0.8) 

    global x_change 
    global y_change 

    x_change = 0 
    y_change = 0 


    pause = False 

    dodged = 0 

    thing_startx = random.randrange(0, display_width) 
    thing_starty = -600 
    thing_speed = 4 
    thing_width = 50 
    thing_height = 50 

    thingt_startx = random.randrange(0, display_width) 
    thingt_starty = -600 
    thingt_speed = 7 
    thingt_width = 100 
    thingt_height = 100 


    gameExit = False 

    while not gameExit: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       gameExit = True 


      if event.type == pygame.KEYDOWN: 
       if event.key == pygame.K_RIGHT: 
        x_change = 8 
       elif event.key == pygame.K_LEFT: 
        x_change = -8 
       elif event.key == pygame.K_p: 
        pause = True 
        paused() 
       elif event.key == pygame.K_UP: 
        y_change = -8 
       elif event.key == pygame.K_DOWN: 
        y_change = 8 
      if event.type == pygame.KEYUP: 
       if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN: 
        x_change = 0 
        y_change = 0 

     x += x_change 
     y += y_change 

     gameDisplay.fill(dark_blue) 

     things(thing_startx, thing_starty, thing_width, thing_height, greent) 
     thing_starty += thing_speed 
     things(thingt_startx, thingt_starty, thingt_width, thingt_height, greent) 
     thingt_starty += thingt_speed 

     car(x, y) 


     if x > display_width - car_width or x < 0: 
      crash() 
     if y > display_width - car_width or y < 0: 
      y_change = 0 

     if thing_starty > display_height: 
      thing_starty = 0 - thing_height 
      thing_startx = random.randrange(0, display_width) 
      dodged += 1 
      thing_speed += 1 
      thing_width += (dodged * 1.2) 
      thing_height += (dodged * 2) 
      thingt_starty = 0 - thing_height 
      thingt_startx = random.randrange(0, display_width) 
      dodged += 1 
      thingt_speed += 1 
      thingt_width += (dodged * 1.2) 
      thingt_height += (dodged * 2) 

     if thing_starty < y: 
      if y < thing_starty+thing_height: 
       if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width: 
        crash() 
     elif thing_starty > y: 
      print('passed') 

     if thingt_starty < y: 
      if y < thingt_starty+thingt_height: 
       if x > thingt_startx and x < thingt_startx + thingt_width or x +  car_width > thingt_startx and x + car_width < thingt_startx + thingt_width: 
        crash() 
     elif thingt_starty > y: 
      print('PASSED') 





     things_dodged(dodged) 
     pygame.display.update() 
     clock.tick(60) 



game_intro() 
game_loop() 
pygame.quit() 
quit() 

код примеры, учебники, видео и т.д. приветствуются. спасибо.

ответ

1

В каждом кадре, отображать изображения в глобальной переменной называется carImp в этой функции:

def car(x, y): 
    gameDisplay.blit(carImp, (x, y)) 

SO, что вы должны сделать, это изменения содержимое этой переменной, чтобы указать на желаемое изображение перед дисплеем. Вы должны сначала прочитать все изображения для вашего автомобиля – вы можете прочитать их все в словарь, чтобы избежать загрязнения пространства имен (даже больше, чем это загрязненное) с именем переменным для каждого спрайта:

Итак, в начале , некоторый код, как:

car_image_names = ["racecar", "move_right", "move_left"] 
car_sprites = dict(((img_name, pygame.image.load(img_name + ".png")) 
         for img_name in car_image_names) 
carImp = car_sprites["racecar"] 

(Здесь я использовал ярлык под названием «выражение генератор», чтобы избежать необходимости писать «pygame.image.load» для каждого изображения автомобиля.)

а потом , в вашем основном цикле, после того, как вы прочитали клавиатуру и обнаружили , автомобиль движется вправо или влево (которые вы отражаете в x_change) – просто изменить carImp соответственно:

if x_change == 0: 
    carImp = car_sprites["racecar"] 
elif x_change > 0: 
    carImp = car_sprites["move_right"] 
elif x_change < 0: 
    carImp = car_sprites["move_left"] 
+0

спасибо, я дам этому попытку. – bubbahms

+0

да, это сработало, спасибо большое! – bubbahms

Смежные вопросы