本文整理汇总了Python中background.Background.draw方法的典型用法代码示例。如果您正苦于以下问题:Python Background.draw方法的具体用法?Python Background.draw怎么用?Python Background.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类background.Background
的用法示例。
在下文中一共展示了Background.draw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Rules
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class Rules(object):
"""menu of the game"""
def __init__(self, width, height):
self.initAttr(width, height);
def loadResource(self):
self.headMark = pygame.image.load(getFilePath("separators.png"))
def initAttr(self, width, height):
self.width, self.height = width, height
self.loadResource()
self.background = Background((width, height))
# 规则文字开始的位置
offLine = 100
offSet = 50
self.content = []
for content in RULES_CONTENT[0 : -1]:
offLine += offSet
self.content.append(Label(RULES_CONTENT_FONTS, content, (50, offLine), headMark = self.headMark))
self.returnButton = TextButton(RULES_EXIT_FONTS, RULES_CONTENT[-1], (offSet, self.height - offSet), (255, 255, 255))
def draw(self, screen):
self.background.draw(screen)
[content.draw(screen) for content in self.content]
self.returnButton.draw(screen)
pygame.display.flip()
def clickListener(self):
if (pygame.mouse.get_pressed()[0]):
mousePos = pygame.mouse.get_pos()
if self.returnButton.rect.collidepoint(mousePos):
return STATE.menu
return STATE.rules
示例2: TheApp
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class TheApp(cocos.layer.Layer):
# If you want that your layer receives events
# you must set this variable to 'True',
# otherwise it won't receive any event.
is_event_handler = True
def __init__(self):
super(TheApp, self).__init__()
self.image = pyglet.resource.image('terrain_4.png')
self._background = Background()
self._objects = []
enemy = Enemy()
self._objects.append(enemy)
self._player = Player()
self._objects.append(self._player)
# call the "step" method every frame when the layer is active
self.schedule(self.step)
def on_enter(self):
super(TheApp, self).on_enter()
self._background.init()
for ob in self._objects:
ob.init()
def draw(self):
super(TheApp, self).draw()
self._background.draw()
for ob in self._objects:
ob.draw()
def step(self, dt):
for ob in self._objects:
ob.update(dt)
def on_key_press(self, symbol, modifiers):
if symbol == key.RIGHT:
self._player.setXVelocity(10)
if symbol == key.LEFT:
self._player.setXVelocity(-10)
def on_key_release(self, key, modifiers):
self._player.setXVelocity(0)
示例3: main
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
def main():
open_canvas()
global background, score, timer, burger, character_list
global running
global current_time, frame_time
background = Background()
score = Score()
timer = Timer()
character_list = [Character() for i in range(nCharacter)]
burger.draw()
running = True
current_time = get_time()
while running:
frame_time = get_frame_time()
handle_events()
for character in character_list:
character.update(frame_time)
clear_canvas()
background.draw()
score.draw()
score.update(value)
timer.draw()
timer.update(time_value)
for character in character_list:
character.draw()
character.draw_bb()
burger.draw()
update_canvas()
close_canvas()
示例4: __init__
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class Game:
def __init__(self):
self.cfg = config.Config(file('config.ini'))
self.game_start_time = time.time()
self.game_speed = self.cfg.init_game_speed
self.play_time = 0
self.game_score = 0
self.player_name = ''
self.fps = self.cfg.fps
pygame.init()
try:
if sys.argv[1] == 'fullscreen':
info = pygame.display.Info()
self.window_size = (info.current_w, info.current_h)
pygame.display.set_mode(self.window_size, pygame.FULLSCREEN)
except:
self.window_size = (640, 480)
self.screen = pygame.display.set_mode(self.window_size)
self.clock = pygame.time.Clock()
self.obstacles = Obstacles(self.screen, self.window_size)
self.obstacles.gen_obstacles(1)
self.player = Player(self.screen, self.window_size)
self.bg = Background(self.screen)
def display_text(self, text, x=None, y=None, font_size=40):
myfont = pygame.font.SysFont("Arial Bold", font_size)
label = myfont.render(text, 1, (255, 255, 255))
if not x:
x = self.window_size[0] / 2 - label.get_width() / 2
if not y:
y = self.window_size[1] / 3
self.screen.blit(label, (x, y))
return label
def game_over(self):
self.display_text('GAME OVER', None, 50)
self.display_text("your score is %s" % self.game_score, None, 80)
def game_score_display(self):
self.play_time = time.time() - self.game_start_time
self.display_text("Score: %s" % str(self.game_score), 10, 10)
def game_score_save(self, key_index=None):
if len(self.player_name) < 3:
if key_index != None and key_index > 96 and key_index < 123:
self.player_name += chr(key_index)
self.display_text('Type your initials: %s' % self.player_name, None, 120, 30)
elif len(self.player_name) == 3:
writer = csv.writer(open('scores.txt', 'ab'))
writer.writerow([self.player_name, self.game_score])
self.player_name += '-1'
elif int(self.player_name[-1:]) == 1:
self.player_name = 'abc2'
reader = csv.reader(open('scores.txt', 'rb'))
scores = []
for row in reader:
scores.append((row[0], row[1]))
scores.sort(None, operator.itemgetter(1), True)
writer = csv.writer(open('scores.txt', 'wb'))
writer.writerows(scores[:5])
else:
self.game_score_board()
def game_score_board(self):
reader = csv.reader(open('scores.txt', 'rb'))
y = 120
self.display_text("Top scores", None, y, 30)
y = 150
for row in reader:
self.display_text('%s %s' % (row[0].upper(), row[1]), None, y, 30)
y += 30
def game_speedup(self, speedup=1):
self.game_speed += speedup
def draw(self, hide_scores=False):
self.bg.draw()
self.obstacles.draw()
self.player.draw()
if not hide_scores:
self.game_score_display()
def main(self):
done = False
stop = False
gameover = False
speedup_counter = self.fps
while done == False:
if not gameover:
if self.player.hit_obstacle(self.obstacles.collection):
gameover = True
key_index = None
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
#.........这里部分代码省略.........
示例5: SetLevel
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class SetLevel(Div, object):
"""set level frame"""
def __init__(self, width, height):
# super(SetLevel, self).__init__()
Div.__init__(self, (width, height))
self.initAttr(width, height)
def initAttr(self, width, height):
self.justClicked = SETLEVEL["JUST_CLICKED"]
# 默认 level
self.loadResouce()
self.setArrow()
self.setLevel()
self.background = Background((self.width, self.height))
titleOffTop = 150
self.titleText = CenteredText(SETLEVEL["TITLE_FONTS"], SETLEVEL["TITLE_CONTENT"], (self.width / 2, titleOffTop))
offSet = 50
self.beginButton = TextButton(SETLEVEL["BEGIN_FONTS"], SETLEVEL["BEGIN_CONTENT"], (self.width - offSet, self.height - offSet), (255, 255, 255))
self.returnButton = TextButton(SETLEVEL["EXIT_FONTS"], SETLEVEL["EXIT_CONTENT"], (offSet, self.height - offSet), (255, 255, 255))
def loadResouce(self):
self.arrowImgRight = pygame.image.load(getFilePath("arrow.png"))
def setArrow(self):
arrowSize = SETLEVEL["ARROW_SIZE"]
levelImageOffTop = 300
coordX, coordY = self.width / 2, levelImageOffTop
self.rArrow = ImageButton(self.arrowImgRight, (arrowSize, arrowSize), (coordX + 80, coordY - 10))
self.lArrow = ImageButton(pygame.transform.flip(self.arrowImgRight, True, True), (arrowSize, arrowSize), (coordX - 80, coordY - 10))
def setLevel(self, level = SETLEVEL["DEFAULT_LEVEL"]):
if not isinstance(level, int):
level = level[0]
if (level > SETLEVEL["MAX_LEVEL"]):
level = SETLEVEL["MAX_LEVEL"]
if (level < SETLEVEL["MIN_LEVEL"]):
level = SETLEVEL["MIN_LEVEL"]
self.level = level
levelTextOffTop = 300
coordX, coordY = self.width / 2, levelTextOffTop
self.levelText = CenteredText(SETLEVEL["LEVEL_FONTS"], str(self.level), (coordX, coordY))
def drawLevelSet(self, screen):
self.rArrow.draw(screen)
self.levelText.draw(screen)
self.lArrow.draw(screen)
def draw(self, screen):
self.background.draw(screen)
self.titleText.draw(screen)
self.drawLevelSet(screen)
self.beginButton.draw(screen)
self.returnButton.draw(screen)
ret = self.beginButton.click(lambda *args : self.level)
if ret != None:
return ret
ret = self.returnButton.click(lambda *args : STATE.menu)
if ret != None:
return ret
self.rArrow.click(self.setLevel, self.level + 1)
self.lArrow.click(self.setLevel, self.level - 1)
return STATE.setLevel
示例6: __init__
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
#.........这里部分代码省略.........
self.background.addLayer(layer)
def setupShip(self,filename):
domLevel = parse(filename)
shipNodes = domLevel.getElementsByTagName("ship")
shipNode = shipNodes[0]
self.mainbody = Body()
for node in shipNode.childNodes:
if node.localName == "position":
position = node.getAttribute('value')
values = position.split(',')
self.mainbody.setPosition(float(values[0]),float(values[1]))
if node.localName == "mobile":
m = Mobile()
for childnode in node.childNodes:
if childnode.localName == "position":
values = childnode.getAttribute('value').split(',')
m.setPosition(float(values[0]),float(values[1]))
if childnode.localName == "velocity":
values = childnode.getAttribute('value').split(',')
m.setVelocity(float(values[0]),float(values[1]))
if childnode.localName == "thrust":
values = childnode.getAttribute('value').split(',')
m.setThrustVector(float(values[0]),float(values[1]))
m.setInitialThrustVector(float(values[0]),float(values[1]))
if childnode.localName == "mass":
value = childnode.getAttribute('value')
m.setMass(float(value))
if childnode.localName == "radius":
value = childnode.getAttribute('value')
m.setRadius(float(value))
if childnode.localName == "texture":
value = childnode.getAttribute('value')
m.setTexture(TextureHelper.loadTextureFromFile(value))
#if childnode.localName == "physicalPoints":
# for ppointnode in childnode.childNodes:
# if ppointnode.localName == "point":
# values = ppointnode.getAttribute('value').split(',')
# m.addPhysicalPoint(Vector2d(float(values[0]),float(values[1])))
m.setupPhysicalPoint()
self.mainbody.addMobile(m)
self.mainbody.init()
focus_position = self.mainbody.getPosition()
self.world.addMobile(self.mainbody)
def setupWorld(self,filename):
self.world.reset()
domLevel = parse(filename)
worldNodes = domLevel.getElementsByTagName("world")
for node in worldNodes[0].childNodes:
if node.localName == "gravity":
values = node.getAttribute('value').split(',')
self.world.setGravity(float(values[0]),float(values[1]))
if node.localName == "landingzone":
values = node.getAttribute('value').split(',')
self.world.setLandingzone(Landingzone(float(values[0]),float(values[1]),float(values[2]),float(values[3]),TextureHelper.loadTextureFromFile('checker.png')))
h = Config.getint('graphics', 'height')
w = Config.getint('graphics', 'width')
p0 = Plane(1,0,-10)
p1 = Plane(0,-1,h-10)
p2 = Plane(-1,0,w-10)
p3 = Plane(0,1,-64)
self.world.addPlane(p0)
self.world.addPlane(p1)
self.world.addPlane(p2)
self.world.addPlane(p3)
#self.world.setGravity(0.0,-1.8)
def setupGame(self):
self.setupMenu()
def updateGame(self,canvas):
if self.mainbody != 0:
self.camera.follow(self.mainbody)
self.camera.setup(canvas)
self.background.draw(canvas)
self.world.draw(canvas)
self.gui.draw(canvas)
self.world.step(1/60.)
if self.gameIsRunning():
res = self.checkVictoryCondition()
if res != 0:
if res == -1:
self.gui.messaging.displayText('FAIL ! !',200)
self.gameResult = -1
Clock.schedule_once(self.setupLevel, 5)
if res == 1:
self.gui.messaging.displayText('SUCCESS ! !',200)
self.gameResult = 1
self.currentLevel += 1
Clock.schedule_once(self.setupLevel, 5)
def on_touch_down(self, touch):
worldpos = self.camera.screenToWorld(touch.pos[0],touch.pos[1])
self.world.on_touch_down(worldpos)
self.gui.on_touch_down(touch)
示例7: __init__
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
#.........这里部分代码省略.........
buttons.reverse()
for button in buttons:
if button.isMouseOver():
self.entity.target = button
break
def chooseAction(self):
'''Escape, heal or attack the selected target.'''
if not self.entity.isThinking(): return
elif self.entity in self.NPCs: return
elif self.entity.target == self.escape: self.entity.fear()
elif self.entity.target in self.PCs and self.entity.isHealer():
if self.entity.target.isInjured() or self.entity.target.isIncapacitated():
if self.entity.target == self.entity: self.entity.healSelf()
else: self.entity.headToHeal()
elif self.entity.target in self.NPCs:
if not self.entity.target.isGone():
if not self.entity.target.isIncapacitated():
self.entity.headToAttack()
def input(self):
'''Respond to user interface events'''
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: self.quit = True
elif event.key == pygame.K_F11: self.toggleFullscreen()
elif event.key == pygame.K_LEFT: self.selectLeft()
elif event.key == pygame.K_RIGHT: self.selectRight()
elif event.key == pygame.K_UP: self.selectUp()
elif event.key == pygame.K_DOWN: self.selectDown()
elif event.key == pygame.K_RETURN: self.chooseAction()
elif event.type == pygame.MOUSEMOTION: self.selectMouse()
elif event.type == pygame.MOUSEBUTTONDOWN:
self.selectMouse()
self.chooseAction()
pygame.event.pump()
def think(self):
'''Entities move and make decisions'''
if self.entity.isThinking() and self.entity in self.NPCs:
self.entity.randomAction(self.NPCs, self.PCs)
for entity in self.PCs: entity.move()
for entity in self.NPCs: entity.move()
def drawSelector(self):
'''Draw a selector under the target if it is a PC or NPC'''
if self.entity.target == None: return
if self.entity.target == self.escape: return
entity_team = self.entity in self.PCs
target_team = self.entity.target in self.PCs
if not (entity_team or target_team): selector = self.heal
elif entity_team and target_team: selector = self.heal
else: selector = self.attack
rectangle = selector.get_rect()
rectangle.midbottom = self.entity.target.position
rectangle.bottom = rectangle.bottom + 15
pygame.display.get_surface().blit(selector, rectangle)
def drawEntities(self):
'''Draw the entities representing each character'''
entities = self.PCs + self.NPCs
entities.sort(lambda a, b: int(a.position[1] - b.position[1]))
for entity in entities: entity.draw()
def draw(self):
'''Draw the fight scene'''
self.background.draw()
self.drawSelector()
self.drawEntities()
self.escape.draw(self.entity.target == self.escape)
pygame.display.flip()
def turn(self):
'''One character's turn'''
if self.entity.isIncapacitated() or self.entity.isGone(): return
self.entity.startTurn()
self.selectMouse()
while True:
time = pygame.time.get_ticks()
if self.quit or self.entity.isTurnOver(): break
self.input()
self.think()
self.draw()
elapsed = pygame.time.get_ticks() - time;
pygame.time.wait(self.delay - elapsed)
def loop(self):
'''Take turns until the PCs or NPCs are defeated'''
entities = self.sortedEntities()
turn = 0
while not self.quit:
if isDefeated(self.PCs): return
if isDefeated(self.NPCs): return
self.entity = entities[turn]
self.turn()
turn = turn + 1
if turn == len(entities): turn = 0
示例8: __init__
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class LevelEditor:
# * Contains a background.
# * Handles Camera controls.
#################################
# PUBLIC
def __init__(self, window):
self.Background = Background(window)
self.ToolBox = ToolBox(*window.size)
def camera_controls(self, Key, Mouse, Camera):
Camera.smooth.speed = 3
if Key.L_CTRL.held(): return
#Move (per Room)
if Key.LEFT.pressed(): Camera.smooth.room_x -= 1
if Key.RIGHT.pressed(): Camera.smooth.room_x += 1
if Key.UP.pressed(): Camera.smooth.room_y -= 1
if Key.DOWN.pressed(): Camera.smooth.room_y += 1
#Move (per Tile)
amt = 25
if Key.A.held(): Camera.smooth.x -= amt
if Key.D.held(): Camera.smooth.x += amt
if Key.W.held(): Camera.smooth.y -= amt
if Key.S.held(): Camera.smooth.y += amt
#Zoom (Toggle)
if Key.E.pressed():
if Camera.smooth.zoom == 1: Camera.smooth.zoom = 2
elif Camera.smooth.zoom == 2: Camera.smooth.zoom = 1
def controls(self, Key, Mouse, Camera, WorldMap):
#toolbox
self.ToolBox.controls(Key, Mouse, Camera, WorldMap)
if Key.TAB.pressed(): self.ToolBox.toggle()
# Toggle grid.
if Key.Q.pressed():
WorldMap.enable_grid = not WorldMap.enable_grid
# Saving/Loading
if Key.L_CTRL.held():
if Key.S.pressed():
self._save(WorldMap)
if Key.O.pressed():
self._load(WorldMap)
#
def draw_background(self, Window, Camera):
self.Background.draw(Window, Camera)
def draw_objects(self, Window, Camera):
Window.view = Window.default_view
self.ToolBox.static_draw(Window, None)
Window.view = Camera
self.ToolBox.normal_draw(Window, None)
#################################
# PRIVATE
# * WorldMap saving/loading.
_map_name = "map1"
def _save(self, WorldMap):
WorldMap.save(self._map_name)
def _load(self, WorldMap):
WorldMap.load(self._map_name)
示例9: __init__
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
#.........这里部分代码省略.........
self.incorrectEffect = pygame.mixer.Sound('assets/incorrect.wav')
# Start the first level
self.nextLevel()
while self.running:
# Pump GTK messages.
while Gtk.events_pending():
Gtk.main_iteration()
pos = pygame.mouse.get_pos()
# Pump PyGame messages.
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.VIDEORESIZE:
pygame.display.set_mode(event.size, pygame.RESIZABLE)
elif event.type == pygame.MOUSEMOTION and self.state == 'GAME':
x, y = pos
# Center the bucket
x -= self.bucket.sprite.get_width() / 2
self.bucket.setPos(x, screen.get_height() * 0.8)
elif event.type == pygame.KEYDOWN: # Shortcut to next level
if self.debug and event.key == pygame.K_n:
self.nextLevel()
elif event.key == pygame.K_p: # Toggle pause status
self.set_paused(not self.paused)
elif event.type == pygame.MOUSEBUTTONDOWN and self.state == 'START':
x, y = pos
width, height = self.titleFont.size("Begin")
if x > self.startButtonX and x < self.startButtonX + self.startButtonWidth and y > self.startButtonY and y < self.startButtonY + self.startButtonHeight:
self.state = 'GAME'
if self.state == 'START':
self.background.draw(1, screen, False);
titleText = "Grapes of Math"
(titleWidth, titleHeight) = self.titleFont.size(titleText)
title = self.titleFont.render(titleText, 1, (200, 200, 200))
screen.blit(title, (screen.get_width() / 2 - (titleWidth / 2), 50))
startText = "Begin"
(self.startButtonWidth, self.startButtonHeight) = self.titleFont.size(startText)
# Only generate this the first draw
if self.startButtonX == 0:
overlayColor = (0, 0, 0, 127)
overlayRect = pygame.Rect(0, 0, self.startButtonWidth, self.startButtonHeight)
overlaySurface = pygame.Surface((300, 160), pygame.SRCALPHA)
overlaySurface.fill(overlayColor, overlayRect)
self.startButtonX = (screen.get_width() / 2 - (self.startButtonWidth / 2))
self.startButtonY = 200
screen.blit(overlaySurface, (self.startButtonX, self.startButtonY))
startButton = self.titleFont.render(startText, 1, (200, 200, 200))
screen.blit(startButton, (self.startButtonX, self.startButtonY))
elif self.state == 'GAME':
if not self.paused:
# Spawn Grapes
if self.spawnCount > random.randrange(self.spawnTime - 5, self.spawnTime):
for i in range(0, random.randint(1, self.maxGrapesPerTick)):
self.spawnGrape(screen.get_width(), i)
示例10: range
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
#.........这里部分代码省略.........
self.DropSpeed = 10
self.MoveState = self.JUMP
elif self.JumpTime == 0:
# self.JumpTime = -1
self.MoveState = self.JUMP
elif self.JumpTime == -1:
self.MoveState = self.CLEAR
if self.MoveState == self.CLEAR or self.MoveState == self.JUMP:
if self.GetCharCrash(self.HeroX, (self.HeroY + (self.DropSpeed / 10) * 2 + 48), 0) == 0:
self.HeroY += self.DropSpeed / 10 * 2
self.DropSpeed += 1
self.isjump = True
else: #######################
self.DropSpeed = 10
self.MoveState = self.CLEAR
self.JumpTime = -1
self.isjump = False
if self.SwitchDetection(self.HeroX, self.HeroY + 52) == 1:
self.SetSwitch(self.SwitchNo)
if self.HeroY > 768:
self.LoadStage(self.map.Stage_number)
if self.collide(self.HeroX, self.HeroY, self.EndX, self.EndY):
if self.clearWin == False:
self.clear_sound.play()
self.clearWin = True
pass
def tutorial_draw(self):
self.tutorial_image1.draw(252, 500)
self.tutorial_image2.draw(400, 400)
self.tutorial_image3.draw(300, 300)
if self.map.object[8][8] != 14:
self.tutorial_image4.draw(700, 370)
pass
def clear_draw(self):
self.clearbg.draw(200, 154)
self.Stageclear_image[self.clear_frames].draw(225, 250)
pass
def draw(self):
self.background.draw()
self.map.draw()
if self.map.Stage_number == 0:
self.tutorial_draw()
if self.Charview == False:
self.laser.clip_draw(self.laser_frames * 64, 0, 64, 768, self.HeroX - 17, self.HeroY - 720)
else:
if self.CharState == self.LEFT_RUN:
self.left_run.clip_draw(self.run_frames * 25, 0, 25, 50, self.HeroX, self.HeroY)
elif self.CharState == self.RIGHT_RUN:
self.right_run.clip_draw(self.run_frames * 25, 0, 25, 50, self.HeroX, self.HeroY)
elif self.CharState == self.LEFT_STAND:
self.left_stand.draw(self.HeroX, self.HeroY)
elif self.CharState == self.RIGHT_STAND:
self.right_stand.draw(self.HeroX, self.HeroY)
示例11:
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
sys.exit()
elif event.key == pygame.K_z:
trooper.action()
elif event.key == pygame.K_UP:
cursor.update('up')
elif event.key == pygame.K_DOWN:
cursor.update('down')
elif event.key == pygame.K_LEFT:
cursor.update('left')
elif event.key == pygame.K_RIGHT:
cursor.update('right')
cursor_x, cursor_y = cursor.get_location()
trooper.update( cursor_x, cursor_y )
background.draw()
trooper.draw()
cursor.draw()
pygame.display.flip()
moveflag = 0
clock.tick(FPS)
示例12: AllDayTasks
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class AllDayTasks(Gtk.DrawingArea):
def __init__(self, parent, rows=1, cols=7):
super(Gtk.DrawingArea, self).__init__()
self.par = parent
self.num_rows = rows
self.num_columns = cols
self.background = Background(rows, cols)
self.padding = 1.5
self.font = "Courier"
self.font_size = 12
self.font_color = (0.35, 0.31, 0.24)
self.link_color = (0, 0, 255, 0.5) # default blue link color
self.today_cell = (None, None)
self.selected_task = None
self.faded_cells = []
self.cells = []
self.labels = None
self.label_height = self.font_size
self.overflow_links = []
self.connect("draw", self.draw)
# drag-and-drop signals and events
self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK
| Gdk.EventMask.BUTTON_RELEASE_MASK
| Gdk.EventMask.BUTTON1_MOTION_MASK
| Gdk.EventMask.POINTER_MOTION_MASK)
def get_label_height(self):
if self.labels:
return self.label_height
return 0
def set_labels(self, labels):
self.labels = labels
def set_num_rows(self, rows):
self.num_rows = rows
self.background.set_num_rows(rows)
def set_font(self, font):
self.font = font
def set_font_size(self, size):
self.font_size = size
def set_font_color(self, color):
self.font_color = color
def set_line_color(self, color):
self.background.set_line_color(color)
def set_background_color(self, color):
self.background.set_background_color(color)
def get_day_width(self):
return self.get_allocation().width / float(self.num_columns)
def get_week_height(self):
return self.get_allocation().height / float(self.num_rows)
def set_tasks_to_draw(self, drawtasks):
self.drawtasks = drawtasks
def highlight_cells(self, ctx, cells, color, alpha=0.5):
alloc = self.get_allocation()
for cell in cells:
row, col = cell
if 0 <= row < self.num_rows and 0 <= col < self.num_columns:
ctx.save()
self.background.highlight_cell(ctx, row, col, alloc,
color, alpha)
ctx.restore()
def set_today_cell(self, row, col):
if 0 <= row < self.num_rows and 0 <= col < self.num_columns:
self.today_cell = (row, col)
else:
self.today_cell = (None, None)
def draw(self, widget, ctx):
ctx.set_line_width(0.8)
ctx.set_font_size(self.font_size)
ctx.select_font_face(self.font, cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
# first draw background
ctx.save()
alloc = self.get_allocation()
self.set_line_color(color=(0.35, 0.31, 0.24, 0.15))
row, col = self.today_cell
if row is not None and col is not None and row >= 0 and col >= 0:
self.background.highlight_cell(ctx, row, col, alloc)
self.background.draw(ctx, alloc, vgrid=True, hgrid=True)
ctx.restore()
# then draw labels, if any (used only on month_view)
if self.labels:
#.........这里部分代码省略.........
示例13: GameWindow
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
#.........这里部分代码省略.........
## MOUSE SCROLL ##
def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
if scroll_y > 0:
print "scrolled forward"
if scroll_y < 0:
print "scrolled backward"
## MOUSE DRAG ##
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if buttons and mouse.LEFT:
#print 'Dragging Left Mouse'
pass
""" END EVENT HANDLING MUMBO JUMBO """
def check_player(self):
if self.player.inspace == 0:
self.player.velocity = 0
if self.player_rot[0] == 1:
self.player.rotate(self.player_rot[1])
if self.player_accel == 1:
self.player.accelerate(self.mapsize)
if self.player_accel == 0 and self.player.velocity > 0:
self.player.glide(self.mapsize)
if self.player_about == 1:
self.player.about()
def on_draw(self):
global Name
glClear(GL_COLOR_BUFFER_BIT)
if self.mainmenu.open == 0:
self.check_player()
if self.player.inspace == 1:
netinfo = self.net_client.netUpdate(self.player)
if self.bgcheck == 1 or self.bgcheck == -1:
self.background.draw(self.player.pos, self.bgcheck)
self.bgcheck *= -1
addplayer = 0
if netinfo[0] == "update":
crucial = pickle.loads(netinfo[1])
print "crucial data 3", crucial
for x in crucial:
if x != self.idnum:
if x in self.otherlist:
self.otherlist.get(x).setCrucial(crucial.get(x))
else:
self.playercount += 1
self.otherlist[x] = others.Other((self.width,self.height),self.panel.size)
self.otherlist.get(x).setCrucial(crucial.get(x))
if len(self.otherlist) > len(crucial):
for x in self.otherlist:
if self.otherlist.get(x).name not in plist:
self.otherlist.pop(x)
break
othersprites = []
for x in self.otherlist:
sprite = self.otherlist.get(x).draw(self.player.pos,self.visible_size,self.net_client.average_ping,self.player.name)
if sprite != None:
示例14: MoveTank
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
inputs.key_state("KEY_UP"),
inputs.key_state("KEY_DOWN"),
inputs.key_state("KEY_SPACE"),
bullet0)
MoveTank(tank1, False, True, True, False, True, bullet1)
MoveBullet(bullet0, tank0)
MoveBullet(bullet1, tank1)
camera.reset(lens1)
camera.rotateY(tself.a)
camera.rotateX(90)
camera.position((tself.x(), tself.y(), -60.0))
pi3d.opengles.glLineWidth(ctypes.c_float(2.0))
bkgd.positionX(tself.x())
bkgd.positionY(tself.y())
bkgd.tick(dt)
bkgd.draw()
pi3d.opengles.glLineWidth(ctypes.c_float(3.0))
for o in objects:
o.tick(dt)
for i in range(0, 4): # draw moving objects
if objects[i] != tself:
objects[i].draw(False) # wireframe
mwo.draw() # draw stationary wireframe objects
for i in range(4, len(objects)):
objects[i].drawIfHit(False)
camera.reset(lens0)
camera.rotateY(tself.a)
camera.rotateX(90)
camera.position((tself.x(), tself.y(), -60.0))
for i in range(0, 4): # draw moving objects
示例15: Header
# 需要导入模块: from background import Background [as 别名]
# 或者: from background.Background import draw [as 别名]
class Header(Gtk.DrawingArea):
def __init__(self, cols=7):
super(Header, self).__init__()
self.labels = []
self.background = Background(1, cols)
self.sidebar = 0
self.font = "Courier"
self.font_size = 12
self.font_color = (0.35, 0.31, 0.24)
self.highlight_cell = (None, None)
self.connect("draw", self.draw)
def set_sidebar_size(self, size):
self.sidebar = size
def set_labels(self, labels):
self.labels = labels
def set_font(self, font):
self.font = font
def set_font_size(self, size):
self.font_size = size
def set_font_color(self, color):
self.font_color = color
def set_line_color(self, color):
self.background.set_line_color(color)
def set_background_color(self, color):
self.background.set_background_color(color)
def get_height(self):
try:
line_height = self.get_allocation().height / len(self.labels[0])
except ZeroDivisionError:
print("List of labels in object Header not initialized!")
raise
else:
return line_height
def get_col_width(self):
try:
col_width = (self.get_allocation().width - self.sidebar) \
/ float(len(self.labels))
except ZeroDivisionError:
print("List of labels in object Header not initialized!")
raise
else:
return col_width
def set_highlight_cell(self, row, col):
if row == 0 and 0 <= col < len(self.labels):
self.highlight_cell = (row, col)
else:
self.highlight_cell = (None, None)
def draw(self, widget, ctx):
"""
Draws the header according to the labels.
@param ctx: a Cairo context
"""
alloc = self.get_allocation()
alloc.width -= self.sidebar
# FIXME: look deeper into why x=5 and y=35 - both should start at 0
# Whathever is happening has to do with spacing in vbox (glade file)
# temporary fix:
alloc.x = 0
alloc.y = 0
ctx.set_line_width(0.8)
row, col = self.highlight_cell
if row is not None and col is not None:
# print "header", alloc.x, alloc.y, alloc.width, alloc.height
self.background.highlight_cell(ctx, row, col, alloc)
self.background.draw(ctx, alloc, vgrid=False, hgrid=True)
color = self.font_color
ctx.set_source_rgb(color[0], color[1], color[2])
ctx.set_font_size(self.font_size)
ctx.select_font_face(self.font, cairo.FONT_SLANT_NORMAL,
cairo.FONT_WEIGHT_NORMAL)
# print labels: use multiple lines if necessary
col_width = self.get_col_width()
line_height = self.get_height()
for i in range(0, len(self.labels)):
for j in range(0, len(self.labels[i])):
label, base_x, base_y = utils.center_text_on_rect(
ctx, self.labels[i][j],
(i * col_width), (j * line_height),
col_width, line_height)
ctx.move_to(base_x, base_y)
ctx.text_path(label)
ctx.stroke()