В настоящее время я пытаюсь выполнить домашнее задание для своего класса программной инженерии.Мы создаем объектно-ориентированную пушечную игру.Нам просто нужно создать пушку и выстрелить из пушечного ядра.
В настоящее время я могу получить свой код для создания пушечного ядра в дульной точке пушки, но, к сожалению, функция перемещения не перемещает пушечное ядро под углом вверх (попытка сделать это перед запуском фактического пушечного огня)В настоящее время вместо этого пушечное ядро (которое я сделал красным, чтобы было легче увидеть, создано ли оно в точке дульного среза пушки), остается там, где оно есть, и я заметил, что само орудие движется в правом нижнем углу.Я озадачен тем, что я мог сделать неправильно.Или почему я не могу заставить мяч двигаться как следует.
import pygame
from colors import color
class Cannonball(object):
'''
classdocs
'''
_x = 135
_y = 310
def __init__(self):
'''
Constructor for cannonball. Initiates x and y at initial values
of x == 135 and y == 310. at 30 FPS
'''
self._x = Cannonball._x
self._y = Cannonball._y
clock = pygame.time.Clock()
time_passed = clock.tick(30)
time_passed_seconds = time_passed / 1000.0
def draw(self, screen):
'''
Draws the cannonball
'''
sprite = pygame.draw.circle(screen, color["red"], (self._x,self._y), 5)
return sprite
def move(self, screen, time_passed):
'''
initiates the cannonball to move until its past the screen
'''
speed = 50
self._x += speed+time_passed
self._y -= speed+time_passed
pygame.display.flip()
Вот мой класс по пушечному ядру
import pygame
import sys
from cannon import Cannon
from cannonball import Cannonball
from colors import color
pygame.init()
'''create the GUI window'''
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption("Cannon Game")
background = screen.fill(color["white"])
clock = pygame.time.Clock()
'''draw the Cannon onto the window'''
aCannon = Cannon
aCannon.draw(aCannon, screen)
pygame.display.flip()
while True:
'''handle keydown and quit events for Cannon Game. Space bar
fires the cannonball
'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
aCannonball = aCannon.fire(screen)
cannon_ball = True
if cannon_ball == True:
aCannonball.draw(screen)
aCannonball.move(screen, time_passed)
pygame.display.flip()
Это мой водитель.Попытка сохранить это простым в настоящее время, поскольку это помогло мне создать вещи до сих пор.
import pygame
from colors import color
from cannonball import Cannonball
class Cannon (object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
def draw(self, screen):
pygame.draw.circle(screen, color["black"], (40,400), 20)
pygame.draw.polygon(screen, color["black"], ([30,400], [135, 300], [150, 320], [50,400]), 0)
def fire (self, screen):
print("Fire") //used this as a tester to make sure the fire call worked before attempting to have a cannonball created and move.
aCannonball = Cannonball()
aCannonball.draw(screen)
aCannonball.move(screen)
И, наконец, мой класс пушек, который содержит функцию огня, которая создает пушечное ядро, тянет его к графическому интерфейсу и инициирует его движение.
Я все еще пытаюсь выяснить, что я мог сделать неправильно, но любая помощь будет с благодарностью оценена.
РЕДАКТИРОВАТЬ: Я обнаружил проблему с кодом, в котором мое пушечное ядро не будет двигаться.Я умножал скорость на прошедшее время, а не прибавлял.Он сорвался бы с экрана почти сразу, прежде чем его можно было увидеть.
Спасибо за помощь!Может быть, я смогу пройти мимо этого в огонь дуги.