python跳跃平台类游戏开发实例(二)

接python跳跃平台类游戏开发实例(一)

  1. 增加移动角色和平台调用功能
    在这里插入图片描述
# pygame template - skeleton for  a  new python project
import pygame as pg
import os
vec= pg.math.Vector2

WIDTH = 800 # 360
HEIGHT = 800 # 480
# FRAME PER SECOND
FPS = 60 

# define colors
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.06
PLAYER_GRAV= 0.8

# starting platforms
# PLATFORM_LIST = [(0, HEIGHT - 40, WIDTH, 40), 
#                  (WIDTH / 2 - 50, HEIGHT * 3 / 4, 100, 20), 
#                  (125, HEIGHT - 350, 100, 20),
#                  (175, 100, 50, 20)]

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# set up assets folders
# windows : 'C:\Users\ZZJ\img'
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):
    # sprite for the player
    def __init__(self, game):
        pg.sprite.Sprite.__init__(self)
        self.game = game
#         self.image = pg.Surface((50, 50))  # still don't know why works immediately
#         self.image.fill(RED)
        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):
        # jump only if on platforms
        self.rect.x += 1
        hits = pg.sprite.spritecollide(self, self.game.platforms, False)
        self.rect.x -= 1
        if hits:
            self.vel.y = -20  # this can jump many times
        
    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
         
        # apply friction
        self.acc.x += self.vel
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值