E
E
Eugene2018-09-21 11:29:39
Python
Eugene, 2018-09-21 11:29:39

How to adjust the smooth movement of the model?

Colleagues,
I study OOP according to the textbook by Eric Matiz "Learning Python". I am writing a game based on it using pygame. And there was a problem - it is not possible to set up a smooth movement of the model. Help, please, to solve a problem.

import  sys, pygame


def check_events(ship):
    for event in pygame.event.get():
        if event.type   ==    pygame.QUIT:
            sys.exit()

        #проверка нажатия клавиши
        elif event.type ==    pygame.KEYDOWN:
            if event.key==    pygame.K_RIGHT:
            #Переместить корабль вправо.
                ship.moving_rignt   =   True
        elif event.type ==    pygame.KEYUP:
            if event.key==    pygame.K_RIGHT:
                ship.moving_rignt   =   False


def update_screen(ai_settings, screen, ship):
    '''обновляет изображение на экране и отображает новый экран
при каждом проходе цикла перерисовывается экран'''
    screen.fill(ai_settings.bg_color)
    ship.blitme()

    #отображание последнего прорисованного экрана

The idea is that by default the ship's movement (only to the right so far) is set to False. And when the key is pressed, the movement becomes True and the position of the model begins to move until the key is released.
import pygame

class Ship():
    def __init__(self, screen):
        self.screen         =   screen
        self.image          =   pygame.image.load('images/ship.png')
        self.rect           =   self.image.get_rect()
        self.screen_rect    =   screen.get_rect()
        self.rect.centerx   =   self.screen_rect.centerx
        self.rect.bottom    =   self.screen_rect.bottom

       <b> self.moving_right   =   False # Flag moving</b>

    def update(self):
        '''update ship`s posicition with flag'''

        if self.moving_right:
            self.rect.centerx   +=  1

    def blitme(self):

As I understand it, the problem is in the check_events (ship) module

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-09-21
@Eujene

I did not understand why, but if you rewrite the code in this form, then everything will work.

def check_events(ship):
    for event in pygame.event.get():
        if event.type   ==    pygame.QUIT:
            sys.exit()
        #проверка нажатия клавиш


        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = True

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question