arcade 库做游戏真的非常合适懒人,套套模板就可以了,结构非常清晰。
配合地图编辑器,做个下面这种游戏还是比较简单的。
今天主要分享一个定时生成金币功能。
import arcade
import random
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Starting Template"
# 玩家
class Player(arcade.Sprite):
def __init__(self,image):
super().__init__(image)
self.center_x = SCREEN_WIDTH//2
self.center_y = self.height//2
def move(self,direction):
# 左移
if direction == "left" and self.center_x >0:
self.center_x = self.center_x - 20
# 右移
elif direction == "right" and self.center_x < SCREEN_WIDTH:
self.center_x = self.center_x + 20
# 金币
class Coin(arcade.Sprite):
def __init__(self,image):
super().__init__(image)
self.center_x = SCREEN_WIDTH//2
self.center_y = SCREEN_HEIGHT-self.height//2
# 创建游戏类
class MyGame(arcade.Window):
def __init__(self, width, height, title):
super().__init__(width, height, title)
self.setup()
def setup(self):
arcade.set_background_color(arcade.color.SKY_BLUE)
self.player = Player('robot.png')
self.coins = arcade.SpriteList()
# 程序运行总时间
self.total_time = 0
# 按键控制变量
self.direction = None
def on_draw(self):
arcade.start_render()
self.player.draw()
if self.coins:
for coin in self.coins:
coin.draw()
def on_update(self, delta_time):
# 记录程序经过的时间
self.total_time = self.total_time + delta_time
if self.total_time >= 0.5:
c = Coin('gold.png')
x = random.randint(50,750)
c.center_x = x
self.coins.append(c)
self.total_time = 0
for coin in self.coins:
# 金币落下
coin.center_y -= 5
# 判断是否超出底边界
if coin.center_y < 0:
self.coins.remove(coin)
# 与金币列表碰撞检测,返回所有碰到的金币
coin_list = self.player.collides_with_list(self.coins)
# 循环删除所有碰到的金币
for c in coin_list:
self.coins.remove(c)
if self.direction =='left':
self.player.move("left")
elif self.direction =='right':
self.player.move("right")
def on_key_press(self, key, key_modifiers):
if key == arcade.key.A:
self.direction = 'left'
elif key == arcade.key.D:
self.direction = 'right'
def on_key_release(self, key, key_modifiers):
if key == arcade.key.A or key == arcade.key.D:
self.direction = None
if __name__ == '__main__':
# 实例对象
game = MyGame(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_TITLE)
arcade.run()