接python跳跃平台类游戏开发实例(一)
- 增加移动角色和平台调用功能
import pygame as pg
import os
vec= pg.math.Vector2
WIDTH = 800
HEIGHT = 800
FPS = 60
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.06
PLAYER_GRAV= 0.8
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
game_folder = os.path.dirname('C:\\Users\\ZZJ\\img')
img_folder = os.path.join(game_folder, 'img')
TITLE = 'My game'
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = pg.image.load(os.path.join(img_folder, 'p1_jump.png')).convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def jump(self):
self.rect.x += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.x -= 1
if hits:
self.vel.y = -20
def update(self):
self.acc = vec(0, PLAYER_GRAV)
keys = pg.key.get_pressed()
if keys[pg.K_LEFT]:
self.acc.x = -PLAYER_ACC
if keys[pg.K_RIGHT]:
self.acc.x = PLAYER_ACC
self.acc.x += self.vel.x * PLAYER_FRICTION
<