python及pygame雷霆战机游戏项目实战01 控制飞机
时间:2021-12-03 作者:songboriceboy
入门
在这个系列中,将制作一个雷霆战机游戏。
首先,将游戏设置修改一下:
WIDTH = 480
HEIGHT = 600
FPS = 60
玩家精灵
要添加的第一件事是代表玩家的精灵。最终,这将是一艘雷霆战机。但是当你第一次开始时,忽略图形会更简单,只需对所有精灵使用普通矩形。
class Player(域名te):
def __init__(self):
域名域名it__(self)
域名e = 域名ace((50, 40))
域名(GREEN)
域名 = 域名rect()
域名erx = WIDTH / 2
域名om = HEIGHT - 10
域名dx = 0
为Player选择了50x40像素的大小,将其定位矩形rect
放在屏幕的底部中心。还定义了一个speedx
属性,可以跟踪玩家在x方向上移动的速度(从一侧到另一侧)。
对于update()
方法,这是将在游戏的每一次循环调用的函数,x坐标向右移动speedx个像素:
def update(self):
域名.x += 域名dx
创建精灵,加入精灵组:
all_sprites = 域名p()
player = Player()
域名(player)
运动/控制
这是一个键盘控制的游戏,所以希望玩家在按下Left
或Right
箭头键时移动精灵。
def update(self):
域名dx = 0
keystate = 域名pressed()
if keystate[域名FT]:
域名dx = -8
if keystate[域名GHT]:
域名dx = 8
域名.x += 域名dx
上面代码会将speedx
每帧设置为0,然后检查键是否已被按下。在域名pressed()
返回一个字典keystate,如果某个键被按下,那么字典中该键对应的值是True。
边界检查
最后,需要确保精灵不会离开屏幕。将向Player类的update()
方法添加以下内容:
if 域名t > WIDTH:
域名t = WIDTH
if 域名 < 0:
域名 = 0
现在,如果Player试图移动到超过屏幕左边缘或右边缘的位置,它将停止。
整合到一起
以下是此步骤的完整代码:
# Shmup game - part 1
# Video link: https://域名/watch?v=nGufy7weyGY
# Player sprite and movement
import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
域名()
域名()
screen = 域名mode((WIDTH, HEIGHT))
域名caption("Shmup!")
clock = 域名k()
class Player(域名te):
def __init__(self):
域名域名it__(self)
域名e = 域名ace((50, 40))
域名(GREEN)
域名 = 域名rect()
域名erx = WIDTH / 2
域名om = HEIGHT - 10
域名dx = 0
def update(self):
域名dx = 0
keystate = 域名pressed()
if keystate[域名FT]:
域名dx = -8
if keystate[域名GHT]:
域名dx = 8
域名.x += 域名dx
if 域名t > WIDTH:
域名t = WIDTH
if 域名 < 0:
域名 = 0
all_sprites = 域名p()
player = Player()
域名(player)
# Game loop
running = True
while running:
# keep loop running at the right speed
域名(FPS)
# Process input (events)
for event in 域名():
# check for closing window
if 域名 == 域名:
running = False
# Update
域名te()
# Draw / render
域名(BLACK)
域名(screen)
# *after* drawing everything, flip the display
域名()
域名()