Skip to content

Commit 403a503

Browse files
committed
add
1 parent 3817a44 commit 403a503

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

python/pygame/README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,5 @@ All images take from [craftpix](https://craftpix.net/).
1313
* [Bouncing Images](basic/bouncing-image.py): learn how to animate images
1414
* [Image Rotation](basic/image-rotation.py): learn how to rotate an image
1515
* [Sound](basic/bouncing-image-with-sound.py): learn how to play sound
16-
* [Key Events](basic/key-movement.py): learn how to listen for key events
16+
* [Key Events](basic/key-movement.py): learn how to listen for key events
17+
* [Mouse Movement](basic/mouse-movement.py): learn how to move a sprite with the mouse

python/pygame/basic/mouse-movement.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import os
2+
import sys
3+
4+
import pygame
5+
from pygame.locals import *
6+
7+
8+
class Satyr(pygame.sprite.Sprite):
9+
def __init__(self, position, scale=0.5):
10+
pygame.sprite.Sprite.__init__(self)
11+
12+
img = pygame.image.load('./images/Satyr_01_Idle_000.png')
13+
rect = img.get_rect(center=position)
14+
w, h = rect.size[0], rect.size[1]
15+
w, h = int(w * scale), int(h * scale)
16+
img = pygame.transform.scale(img, (w, h))
17+
18+
rect = img.get_rect(center=position)
19+
x = position[0] - int(rect.size[0] / 2.0)
20+
y = position[1] - int(rect.size[1] / 2.0)
21+
22+
self.image = img
23+
self.rect = rect
24+
self.position = x, y
25+
26+
def draw(self, surface, position):
27+
self.position = position[0] - self.rect.width / 2, position[1] - self.rect.height / 2
28+
surface.blit(self.image, self.position)
29+
30+
31+
def start():
32+
pygame.init()
33+
34+
FPS = 30
35+
width = 400
36+
height = 400
37+
DISPLAYSURF = pygame.display.set_mode((width, height))
38+
DISPLAYSURF.fill((255, 255, 255))
39+
pygame.display.set_caption('Key Events')
40+
fps_clock = pygame.time.Clock()
41+
42+
satyr = Satyr((200, 200), 0.25)
43+
44+
while True:
45+
for event in pygame.event.get():
46+
if event.type == QUIT:
47+
pygame.quit()
48+
sys.exit()
49+
50+
DISPLAYSURF.fill((255, 255, 255, 0))
51+
52+
satyr.draw(DISPLAYSURF, pygame.mouse.get_pos())
53+
54+
pygame.display.update()
55+
fps_clock.tick(FPS)
56+
57+
58+
if __name__ == '__main__':
59+
os.environ['SDL_VIDEO_CENTERED'] = '1'
60+
start()

0 commit comments

Comments
 (0)