Reputation: 113
I have written a code which aims to move a horse when pressing the right arrow key, but when I press it, it doesnt move. I can't seem notice where the problem is. I have typed print(a.locx)
in def char()
to see a.locx
is increasing or not but its not and also in class Horse()
's method def location()
when I press right arrow key self.locx
is increasing and then instantly decreasing.
import pygame
from pygame import locals
def main():
global window,width,height
pygame.init()
width ,height = 500,500
window = pygame.display.set_mode((width,height))
while True:
window.fill((0,0,0))
for event in pygame.event.get():
if pygame.event == pygame.QUIT:
pygame.quit()
char()
pygame.display.update()
def char():
a = Horse()
window.blit(a.horse1,(a.locx,a.locy))
print(a.locx)
a.location()
class Horse():
def __init__(self):
self.horse1 = pygame.image.load("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk3.png")
self.horse2 = []
for horse in range(0,8):
self.horse2.append(pygame.image.load(("C:/Users/niimet/Desktop/pygeym/blitz/Horse_Walk{}.png").format(horse+1)))
self.horse3 = []
for horse in self.horse2:
self.horse3.append(pygame.transform.flip(horse,True,False))
self.locx = 0
self.locy = width - self.horse1.get_size()[1]
def location(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
print(self.locx,"1")
self.locx += 200
print(self.locx,"2")
main()
Upvotes: 2
Views: 63
Reputation: 211077
The issue is that you crate a new Horse
object in every frame and so the horse continuously "starts" at its initial position.
def char(): a = Horse() # <--- creates new Hors object with "self.locx = 0" # [...]
Create a Horse
in global name space and use this object:
def main():
global window, width, height, a
pygame.init()
width, height = 500,500
window = pygame.display.set_mode((width,height))
a = Horse()
while True:
window.fill((0,0,0))
for event in pygame.event.get():
if pygame.event == pygame.QUIT:
pygame.quit()
char()
pygame.display.update()
def char():
window.blit(a.horse1,(a.locx,a.locy))
print(a.locx)
a.location()
Upvotes: 2