pygame学習のオブジェクト移動
9754 ワード
pygameは強力なパッケージを多く提供しており、2 Dゲームの制作は非常に簡単です.
2 Dゲームの重要な側面は、オブジェクトを移動してからマップすることです.次は2つの方法を紹介し、最後に単独で編を書いて紹介します.(現在把握している):
1、pygameを使用する.rect:pygameのドキュメントは次のとおりです.
Pygame uses Rect objects to store and manipulate rectangular areas. A Rect can be created from a combination of left, top, width, and height values. Rects can also be created from python objects that are already a Rect or have an attribute named "rect".
Any Pygame function that requires a Rect argument also accepts any of these values to construct a Rect. This makes it easier to create Rects on the fly as arguments to functions.
The Rect functions that change the position or size of a Rect return a new copy of the Rect with the affected changes. The original Rect is not modified. Some methods have an alternate "in-place" version that returns None but effects the original Rect. These "in-place" methods are denoted with the "ip" suffix.
The Rect object has several virtual attributes which can be used to move and align the Rect:
All of these attributes can be assigned to:
Assigning to size, width or height changes the dimensions of the rectangle; all other assignments move the rectangle without resizing it. Notice that some attributes are integers and others are pairs of integers.
If a Rect has a nonzero width or height, it will return True for a nonzero test. Some methods return a Rect with 0 size to represent an invalid rectangle.
The coordinates for Rect objects are all integers. The size values can be programmed to have negative values, but these are considered illegal Rects for most operations.
There are several collision tests between other rectangles. Most python containers can be searched for collisions against a single Rect.
The area covered by a Rect does not include the right- and bottom-most edge of pixels. If one Rect's bottom border is another Rect's top border (i.e., rect1.bottom=rect2.top), the two meet exactly on the screen but do not overlap, and rect1.colliderect(rect2) returns false. --------------------------------------------------------------------------このセクションでは、rectには位置に関するいくつかの属性が含まれており、これらの属性を調整することで移動を実現することができます。これでもう便利だけど。。。 rectオブジェクトはまた2つの関数を提供し、移動の機能を非常に便利に実現した:rect.move
rect.move_ip
どちらの関数もrectオブジェクトを移動します.
Rect.move
moves the rectangleRect.move(x, y): return Rect
Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.
Rect.move_ip
moves the rectangle, in placeRect.move_ip(x, y): return None
Same as the Rect.move - moves the rectangle method, but operates in place.
違いはmove_ipは直接調整オブジェクトを変更し、moveは変更後のオブジェクトを返します.
爽やかでしょ?
セグメントサンプルコード:
1
#
!/usr/bin/env python
2
#
-*- coding: utf-8 -*-
3
4
__doc__
=
"""
pygameの矩形移動のデモ
"""
5
6
import
os
7
import
sys
8
import
pygame
9
import
time
10
import
random
11
from
sys
import
exit
12
from
pygame.locals
import
*
13
14
15
WIDTH
=
800
16
HEIGHT
=
600
17
18
#
ノンゼロランダム
19
def
random_none_zero(m1,m2):
20
n
=
random.randint(m1, m2)
21
22
while
n
==
0:
23
n
=
random.randint(m1, m2)
24
return
n
25
26
def
main():
27
pygame.init()
28
29
pygame.display.set_caption(
"
move rect
"
)
30
screen
=
pygame.display.set_mode((WIDTH,HEIGHT),0,
32
)
31
pygame.mouse.set_visible(0)
32
33
rect
=
pygame.Rect((
10
,
20
), (
200
,
300
))
34
35
done
=
False
36
while
not
done:
37
screen.fill((
255
,
255
,
255
))
38
for
event
in
pygame.event.get():
39
if
event.type
==
QUIT
or
\
40
(event.type
==
KEYDOWN
and
event.key
==
K_ESCAPE):
41
done
=
True
42
43
x
=
random.randint(
-
50
,
50
)
44
y
=
random.randint(
-
50
,
50
)
45
46
rect.move_ip(x,y)
47
pygame.draw.rect(screen,(
5
,
5
,
5
),rect)
48
pygame.display.update()
49
pygame.time.delay(
1000
)
50
return
0
51
52
if
__name__
==
'
__main__
'
:
53
main()
2、surfaceを使用する.surface
Surfaceはpygameのすべてのグラフィックリソースの基礎です.pygameにかかわらずRectかpygameかspriteはいずれもSurfaceを操作することによって実現される.Surfaceを直接通してオブジェクトを移動するのは、ちょっと面倒なので、いくつかのパッケージがあります.surfaceは1枚の画像と理解でき、親Surfaceに貼ると表示されます.移動が必要ならどうしますか?まず、親Surfaceを空にして座標を設定し、最後に親Surfaceに貼り付けるだけです.貼り付けpygameドキュメントに付いているmoveit.pyのコードは、画像リソースを提供しません.画像オブジェクト(surfaceでもあります)をカプセル化し、座標移動を設定します.コードは簡単です.
#
!/usr/bin/env python
"""
This is the full and final example from the Pygame Tutorial,"How Do I Make It Move". It creates 10 objects and animatesthem on the screen.Note it's a bit scant on error checking, but it's easy to read. :]Fortunately, this is python, and we needn't wrestle with a pile oferror codes.
"""
#
import everything
import
os, pygame
from
pygame.locals
import
*
#
our game object class
class
GameObject:
def
__init__
(self, image, height, speed): self.speed
=
speed self.image
=
image self.pos
=
image.get_rect().move(0, height)
def
move(self): self.pos
=
self.pos.move(self.speed, 0)
if
self.pos.right
>
600
: self.pos.left
=
0
#
quick function to load an image
def
load_image(name): path
=
os.path.join(
'
data
'
, name)
return
pygame.image.load(path).convert()
#
here's the full code
def
main(): pygame.init() screen
=
pygame.display.set_mode((
640
,
480
)) player
=
load_image(
'
player1.gif
'
) background
=
load_image(
'
liquid.bmp
'
)
#
scale the background image so that it fills the window and
#
successfully overwrites the old sprite position.
background
=
pygame.transform.scale2x(background) background
=
pygame.transform.scale2x(background) screen.blit(background, (0, 0)) objects
=
[]
for
x
in
range(
10
): o
=
GameObject(player, x
*
40
, x) objects.append(o)
while
1
:
for
event
in
pygame.event.get():
if
event.type
in
(QUIT, KEYDOWN):
return
for
o
in
objects: screen.blit(background, o.pos, o.pos)
for
o
in
objects: o.move() screen.blit(o.image, o.pos) pygame.display.update()
if
__name__
==
'
__main__
'
: main()
3、使用
pygame.spriteこれは次の編に残して書きます.
2 Dゲームの重要な側面は、オブジェクトを移動してからマップすることです.次は2つの方法を紹介し、最後に単独で編を書いて紹介します.(現在把握している):
1、pygameを使用する.rect:pygameのドキュメントは次のとおりです.
Pygame uses Rect objects to store and manipulate rectangular areas. A Rect can be created from a combination of left, top, width, and height values. Rects can also be created from python objects that are already a Rect or have an attribute named "rect".
Any Pygame function that requires a Rect argument also accepts any of these values to construct a Rect. This makes it easier to create Rects on the fly as arguments to functions.
The Rect functions that change the position or size of a Rect return a new copy of the Rect with the affected changes. The original Rect is not modified. Some methods have an alternate "in-place" version that returns None but effects the original Rect. These "in-place" methods are denoted with the "ip" suffix.
The Rect object has several virtual attributes which can be used to move and align the Rect:
#rectオブジェクトには、rectオブジェクトを および するためのプロパティがあります。
top, left, bottom, right topleft, bottomleft, topright, bottomright midtop, midleft, midbottom, midright center, centerx, centery size, width, height w,h
All of these attributes can be assigned to:
を り てるには
rect1.right = 10 rect2.center = (20,30)
Assigning to size, width or height changes the dimensions of the rectangle; all other assignments move the rectangle without resizing it. Notice that some attributes are integers and others are pairs of integers.
If a Rect has a nonzero width or height, it will return True for a nonzero test. Some methods return a Rect with 0 size to represent an invalid rectangle.
The coordinates for Rect objects are all integers. The size values can be programmed to have negative values, but these are considered illegal Rects for most operations.
There are several collision tests between other rectangles. Most python containers can be searched for collisions against a single Rect.
The area covered by a Rect does not include the right- and bottom-most edge of pixels. If one Rect's bottom border is another Rect's top border (i.e., rect1.bottom=rect2.top), the two meet exactly on the screen but do not overlap, and rect1.colliderect(rect2) returns false. --------------------------------------------------------------------------このセクションでは、rectには位置に関するいくつかの属性が含まれており、これらの属性を調整することで移動を実現することができます。これでもう便利だけど。。。 rectオブジェクトはまた2つの関数を提供し、移動の機能を非常に便利に実現した:rect.move
rect.move_ip
どちらの関数もrectオブジェクトを移動します.
Rect.move
moves the rectangleRect.move(x, y): return Rect
Returns a new rectangle that is moved by the given offset. The x and y arguments can be any integer value, positive or negative.
Rect.move_ip
moves the rectangle, in placeRect.move_ip(x, y): return None
Same as the Rect.move - moves the rectangle method, but operates in place.
違いはmove_ipは直接調整オブジェクトを変更し、moveは変更後のオブジェクトを返します.
爽やかでしょ?
セグメントサンプルコード:
1
#
!/usr/bin/env python
2
#
-*- coding: utf-8 -*-
3
4
__doc__
=
"""
pygameの矩形移動のデモ
"""
5
6
import
os
7
import
sys
8
import
pygame
9
import
time
10
import
random
11
from
sys
import
exit
12
from
pygame.locals
import
*
13
14
15
WIDTH
=
800
16
HEIGHT
=
600
17
18
#
ノンゼロランダム
19
def
random_none_zero(m1,m2):
20
n
=
random.randint(m1, m2)
21
22
while
n
==
0:
23
n
=
random.randint(m1, m2)
24
return
n
25
26
def
main():
27
pygame.init()
28
29
pygame.display.set_caption(
"
move rect
"
)
30
screen
=
pygame.display.set_mode((WIDTH,HEIGHT),0,
32
)
31
pygame.mouse.set_visible(0)
32
33
rect
=
pygame.Rect((
10
,
20
), (
200
,
300
))
34
35
done
=
False
36
while
not
done:
37
screen.fill((
255
,
255
,
255
))
38
for
event
in
pygame.event.get():
39
if
event.type
==
QUIT
or
\
40
(event.type
==
KEYDOWN
and
event.key
==
K_ESCAPE):
41
done
=
True
42
43
x
=
random.randint(
-
50
,
50
)
44
y
=
random.randint(
-
50
,
50
)
45
46
rect.move_ip(x,y)
47
pygame.draw.rect(screen,(
5
,
5
,
5
),rect)
48
pygame.display.update()
49
pygame.time.delay(
1000
)
50
return
0
51
52
if
__name__
==
'
__main__
'
:
53
main()
2、surfaceを使用する.surface
Surfaceはpygameのすべてのグラフィックリソースの基礎です.pygameにかかわらずRectかpygameかspriteはいずれもSurfaceを操作することによって実現される.Surfaceを直接通してオブジェクトを移動するのは、ちょっと面倒なので、いくつかのパッケージがあります.surfaceは1枚の画像と理解でき、親Surfaceに貼ると表示されます.移動が必要ならどうしますか?まず、親Surfaceを空にして座標を設定し、最後に親Surfaceに貼り付けるだけです.貼り付けpygameドキュメントに付いているmoveit.pyのコードは、画像リソースを提供しません.画像オブジェクト(surfaceでもあります)をカプセル化し、座標移動を設定します.コードは簡単です.
#
!/usr/bin/env python
"""
This is the full and final example from the Pygame Tutorial,"How Do I Make It Move". It creates 10 objects and animatesthem on the screen.Note it's a bit scant on error checking, but it's easy to read. :]Fortunately, this is python, and we needn't wrestle with a pile oferror codes.
"""
#
import everything
import
os, pygame
from
pygame.locals
import
*
#
our game object class
class
GameObject:
def
__init__
(self, image, height, speed): self.speed
=
speed self.image
=
image self.pos
=
image.get_rect().move(0, height)
def
move(self): self.pos
=
self.pos.move(self.speed, 0)
if
self.pos.right
>
600
: self.pos.left
=
0
#
quick function to load an image
def
load_image(name): path
=
os.path.join(
'
data
'
, name)
return
pygame.image.load(path).convert()
#
here's the full code
def
main(): pygame.init() screen
=
pygame.display.set_mode((
640
,
480
)) player
=
load_image(
'
player1.gif
'
) background
=
load_image(
'
liquid.bmp
'
)
#
scale the background image so that it fills the window and
#
successfully overwrites the old sprite position.
background
=
pygame.transform.scale2x(background) background
=
pygame.transform.scale2x(background) screen.blit(background, (0, 0)) objects
=
[]
for
x
in
range(
10
): o
=
GameObject(player, x
*
40
, x) objects.append(o)
while
1
:
for
event
in
pygame.event.get():
if
event.type
in
(QUIT, KEYDOWN):
return
for
o
in
objects: screen.blit(background, o.pos, o.pos)
for
o
in
objects: o.move() screen.blit(o.image, o.pos) pygame.display.update()
if
__name__
==
'
__main__
'
: main()
3、使用
pygame.spriteこれは次の編に残して書きます.