Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit.In this article we will see how we can make design in PyGame with help of keys such that design i.e marker moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key. We can do this by making a spot(marker) on the respective co-ordinates, which gets changes with the help of keys.
Change in Co-ordinates of marker for respective keys pressed :Left arrow key: Decrement in x co-ordinateRight arrow key: Increment in x co-ordinateUp arrow key: Decrement in y co-ordinateDown arrow key: Increment in y co-ordinate
Below is the implementation -
Python3 1==# import pygame module in this programimportpygame# activate the pygame library .# initiate pygame and give permission# to use pygame's functionality.pygame.init()# create the display surface object# of specific dimension..e(500, 500).win=pygame.display.set_mode((500,500))# set the pygame window namepygame.display.set_caption("Moving rectangle")# marker current co-ordinatesx=200y=200# dimensions of the markerwidth=10height=10# velocity / speed of movementvel=10# Indicates pygame is runningrun=True# infinite loopwhilerun:# creates time delay of 10mspygame.time.delay(10)# iterate over the list of Event objects# that was returned by pygame.event.get() method.foreventinpygame.event.get():# if event object type is QUIT# then quitting the pygame# and program both.ifevent.type==pygame.QUIT:# it will make exit the while looprun=False# stores keys pressedkeys=pygame.key.get_pressed()# if left arrow key is pressedifkeys[pygame.K_LEFT]andx>0:# decrement in x co-ordinatex-=vel# if left arrow key is pressedifkeys[pygame.K_RIGHT]andx<500-width:# increment in x co-ordinatex+=vel# if left arrow key is pressedifkeys[pygame.K_UP]andy>0:# decrement in y co-ordinatey-=vel# if left arrow key is pressedifkeys[pygame.K_DOWN]andy<500-height:# increment in y co-ordinatey+=vel# drawing spot on screen which is rectangle herepygame.draw.rect(win,(255,0,0),(x,y,width,height))# it refreshes the windowpygame.display.update()# closes the pygame windowpygame.quit()
Output :