I am following a tutorial into pygame. I spotted the instance code was written for the sake of being simple to grasp. I puzzled if I may ‘enhance’ the code, with a give attention to preserving the very same performance. I attempted, however I am not likely certain if that is an enchancment.
That is the unique code from the directions:
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()
# arrange the window
DISPLAYSURF = pygame.show.set_mode((400, 300), 0, 32)
pygame.show.set_caption('Animation')
WHITE = (255, 255, 255)
catImg = pygame.picture.load('cat.png') # hosted at https://inventwithpython.com/cat.png
catx = 10
caty = 10
path = 'proper'
whereas True: # the primary sport loop
DISPLAYSURF.fill(WHITE)
if path == 'proper':
catx += 5
if catx == 280:
path = 'down'
elif path == 'down':
caty += 5
if caty == 220:
path = 'left'
elif path == 'left':
catx -= 5
if catx == 10:
path = 'up'
elif path == 'up':
caty -= 5
if caty == 10:
path = 'proper'
DISPLAYSURF.blit(catImg, (catx, caty))
for occasion in pygame.occasion.get():
if occasion.sort == QUIT:
pygame.give up()
sys.exit()
pygame.show.replace()
fpsClock.tick(FPS)
That is my ‘improved’ code. Two questions. Basically, how can my model be improved and why is that enchancment higher then my code? And, how may the unique be improved?
import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30
fps_clock = pygame.time.Clock()
window_size = (400,300)
DISPLAYSURF = pygame.show.set_mode(window_size,0,32)
pygame.show.set_caption("Animation take a look at!")
WHITE = (255,255,255)
cat = pygame.picture.load('assests/cat.png') # hosted at https://inventwithpython.com/cat.png
path = 'proper'
x_,y_ = 10,10
def listenToQuit():
for occasion in pygame.occasion.get():
if occasion.sort == QUIT:
pygame.give up()
sys.exit()
def detectCollision(cat,x,y,window_size):
return cat.get_size()[0] + x >= window_size[0] or
cat.get_size()[1] + y >= window_size[1] or
x <= Zero or y <= 0
def getDirection(path):
instructions = ['right','down','left','up']
idx = instructions.index(path)
idx = Zero if idx + 1 == len(instructions) else idx + 1
return instructions[idx]
def getMovement(x,y,path):
if path == 'proper':
return x+5,y
elif path == 'down':
return x , y+5
elif path == 'left':
return x - 5 , y
elif path == 'up':
return x , y - 5
i = 0
whereas 1:
DISPLAYSURF.fill(WHITE)
x,y = getMovement(x_,y_,path)
whereas detectCollision(cat,x,y,window_size): # if there could be a collision, change path
path = getDirection(path)
x,y = getMovement(x_,y_,path) # re-calculate motion, now avoiding collision
x_,y_ = x,y
DISPLAYSURF.blit(cat,(x,y))
listenToQuit()
pygame.show.replace()
fps_clock.tick(FPS)
I particularly selected to not make the animated object a category. I’ll attempt to take action as my subsequent train in direction of myself.