So I need to create an interactive game map for other players. They could add some markers on it locally.
I imported the image of the map and saw a stackoverflow subject with someone having the same problem. I got the solution but it's zooming at the center of the picture.
It's a very large picture so i need to make the zoom possible on the cursor of the mouse.
Here's the code I've already made :
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.scatter import Scatter
from kivy.core.window import Window
from kivy.graphics.transformation import Matrix
from kivy.lang import Builder
Builder.load_file('map.kv')
class Zoom(ScatterLayout):
def on_touch_down(self, touch):
x, y = touch.x, touch.y
self.prev_x = touch.x
self.prev_y = touch.y
if touch.is_mouse_scrolling:
if touch.button == 'scrolldown':
print('down')
## zoom in
if self.scale < 10:
self.scale = self.scale * 1.1
elif touch.button == 'scrollup':
print('up') ## zoom out
if self.scale > 1:
self.scale = self.scale * 0.9
# if the touch isn't on the widget we do nothing
if not self.do_collide_after_children:
if not self.collide_point(x, y):
return False
if 'multitouch_sim' in touch.profile:
touch.multitouch_sim = True
# grab the touch so we get all it later move events for sure
self._bring_to_front(touch)
touch.grab(self)
self._touches.append(touch)
self._last_touch_pos[touch] = touch.pos
return True
class Main_app(BoxLayout):
pass
class Stacked(App):
def build(self):
Window.clearcolor = (1, 1, 1, 1)
Window.size = (1000, 700)
Seems like that should be an option for Scatter and ScatterPlane, but it isn't. Here is a hack I have used to accomplish what you asked about:
class MyScatterPlane(ScatterPlane):
def on_touch_up(self, touch):
if self.collide_point(*touch.pos):
if touch.is_mouse_scrolling:
if touch.button == 'scrolldown':
mat = Matrix().scale(.9, .9, .9)
self.apply_transform(mat, anchor=touch.pos)
elif touch.button == 'scrollup':
mat = Matrix().scale(1.1, 1.1, 1.1)
self.apply_transform(mat, anchor=touch.pos)
return super().on_touch_up(touch)
This is an extension of ScatterPlane, but it is not extensively tested. Use at your own risk.
Related
When the program runs, the ScreenManager shows the Main screen on which I added the white little square(Ball).
The widget Ball should be moving around but I cannot figure out why it is still static.
The update method is working but the position of the widget is not being updated. I tried to move things around and no effect.
If someone could help me to understand where I am wrong, would be great. Thx so much.
import kivy
kivy.require('1.10.1')
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.graphics import Rectangle
from kivy.uix.widget import Widget
from kivy.properties import ListProperty
from kivy.clock import Clock
# simple Screen on which the ball should move
class Main(Screen):
def __init__(self, **kwargs):
super(Main, self).__init__(**kwargs)
self.add_widget(Ball())
with self.canvas.before:
Rectangle(source = 'BG1.png',
size = Window.size,
pos = self.pos)
# the Ball should be bouncing around
class Ball(Widget):
velocity = ListProperty([10, 15])
def __init__(self, **kwargs):
super(Ball, self).__init__(**kwargs)
Clock.schedule_interval (self.update, 1 / 60)
with self.canvas:
Rectangle (color=[0, 0, 0, 1],
size=(10, 10),
pos = self.pos)
def update(self, *args):
print('wtf')
self.x += self.velocity[0]
self.y += self.velocity[1]
if self.x < 0 or (self.x + self.width) > Window.width:
self.velocity[0] *= -1
if self.y < 0 or (self.y + self.height) > Window.height:
self.velocity[1] *= -1
Window.size = (400, 300)
sm = ScreenManager()
sm.add_widget(Main(name = 'main'))
class Bubble(App):
def build(self):
return sm
if __name__ == '__main__':
Bubble().run()
Thank you Embryo and John, your answers led me to find the right answer. I found this code on this blog. Solved it all:Kivy blog
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle, Color
class CornerRectangleWidget(Widget)
def __init__(self, **kwargs):
super(CornerRectangleWidget, self).__init__(**kwargs)
with self.canvas:
Color(1, 0, 0, 1) # set the colour to red
self.rect = Rectangle(pos=self.center,
size=(self.width/2.,
self.height/2.))
self.bind(pos=self.update_rect,
size=self.update_rect)
def update_rect(self, *args):
self.rect.pos = self.pos
self.rect.size = self.size
The problem is that when you set up Canvas instructions in python (rather than in kv), you don't get the automatic bindings that kv does for you. So the Rectangle that you define in the Ball.__init__() method gets its pos defined as the pos of the Ball at its __init__() moment (which is [0,0]), and it does not change automatically. You can fix that by doing the update yourself. First, in your Ball.__init__() change your with self.canvas block to:
with self.canvas:
Color(0,0,0,1)
self.rect = Rectangle (size=(10, 10),
pos = self.pos)
One change is defining the Color, and the second is creating a reference to the Rectangle. Then in your update method add the line:
self.rect.pos = self.pos
This will move the rectangle with the Ball position.
Also, your update method has some problems because the size of the Ball is the same size as the Window. It is not the size you provide in the Rectangle.
Well, what is happening is this...
You are drawing the rectangle once, when you instantiate the Ball widget.
This is what you see in the bottom left corner.
After that you move the widget, but you don't draw it again.
If you print(self.pos) in the update function, you'll see it moving...
i have a simple ModalView and its size is (640,426).My window's size is (1366,732).My Screen Resolution is (1366,768).When i click at the top left corner of the ModalView,i get something like 363,690.Which is my touch coordinates taken from the window itself.i would however like to somehow convert this value to local widget space so that touching the top left corner i get the coordinate (0,0) instead of (363,690).Is this possible with kivy or any other way.What Im trying to do,for those interested is to crop an image using a box drawn by the user.Drawing the box isn't the problem,the problem is getting those bounds and transfering them to the image's coords.
NB: I read about the to_local(),to_parent(),to_window() and those functions are simply not working...for some reason,maybe i missed a thing there,would appreciate your help big time
Here is the code similar to my usecase but stripped
from kivy.app import App
from kivy.uix.modalview import ModalView
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
class CropBounds(ModalView):
def __init__(self, **kwargs):
super(CropBounds, self).__init__(**kwargs)
self.to_crop = True
self.size = (400,400)
print('Center: ',self.center)
print('Size: ',self.size)
print('Window Center: ',Window.center)
print('Window Size:(',Window.width,',',Window.height,')')
def on_touch_down(self, touch):
self.canvas.clear()
if self.collide_point(*touch.pos) and self.to_crop:
with self.canvas:
self.start_x = touch.x
self.start_y = touch.y
touch.ud['area'] = Line(points=(touch.x, touch.y, touch.x, 400,touch.x, touch.y,touch.x, touch.y, touch.x, touch.y))
print("Pos: ",touch.pos)
print(touch.x,touch.y)
return True
return MainWindow().on_touch_down(touch)
class GalleryWindow(BoxLayout):
def __init__(self, **kwargs):
super(GalleryWindow, self).__init__(**kwargs)
self.add_widget(Button(text='crop',size_hint=(1,None),size=(None,40),on_release=self.crop_img))
def crop_img(self):
bounds = CropBounds()
bounds.open()
class GalleryApp(App):
def build(self):
return GalleryWindow()
if __name__=='__main__':
GalleryApp().run()
Subtracting the ModalView position from the touch coordinates does work. I think your are getting confused about the size and position of your ModalView. The way your code is written, the ModalView is the same size and position as your GalleryWindow (recall that the default size_hint is (1.0, 1.0)). So, for there to be any difference between coordinates in the ModalView and GalleryWindow, you need to change the size_hint for the ModalView.
After correcting many errors in your code (to get it to run). I have made some changes to demonstrate the position of the ModalView and the location of the touch.
Here is the code:
from kivy.app import App
from kivy.core.window import Window
from kivy.graphics.vertex_instructions import Line
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.modalview import ModalView
from kivy.uix.button import Button
class CropBounds(ModalView):
def __init__(self, **kwargs):
super(CropBounds, self).__init__(**kwargs)
self.to_crop = True
self.size_hint = (None, None) # without this, the size below has no effect
self.size = (400,400)
print('Center: ',self.center)
print('Size: ',self.size)
print('Window Center: ',Window.center)
print('Window Size:(',Window.width,',',Window.height,')')
def on_touch_down(self, touch):
if self.collide_point(*touch.pos) and self.to_crop:
self.canvas.clear()
with self.canvas:
# plot the boundary of the ModalView
Line(points=[self.pos[0], self.pos[1],
self.pos[0], self.pos[1] + self.height,
self.pos[0] + self.width, self.pos[1] + self.height,
self.pos[0] + self.width, self.pos[1],
self.pos[0], self.pos[1]])
# plot a line from the touch point to the pos of the ModalView
Line(points=[self.pos[0], self.pos[1], touch.x, touch.y])
# calculate touch minus position of ModalView
touch_in_modal = (touch.x - self.pos[0], touch.y - self.pos[1])
print('touch : ' + str(touch.pos) + ', touch in modal: ' + str(touch_in_modal))
return True
#return MainWindow().on_touch_down(touch)
class GalleryWindow(BoxLayout):
def __init__(self, **kwargs):
super(GalleryWindow, self).__init__(**kwargs)
self.add_widget(Button(text='crop',size_hint=(1,None),size=(40,40),on_release=self.crop_img))
def crop_img(self, *args):
bounds = CropBounds()
bounds.open()
class GalleryApp(App):
def build(self):
return GalleryWindow()
if __name__=='__main__':
GalleryApp().run()
If you want to see what was happening in your code, just comment out the size_hint line.
Also, when we ask you to post a MCV example, please try running what you post. If we have to debug your example before we can see what you problem is, you won't get many responses.
What I tried to do:
I wanted my program to print a message when it collides with the sprite in the middle.
Problem:
It doesn't stop printing that it collided. I looked into it with pdb and it says that the Player Sprite is the size of the whole screen, which is weird because I set the image size to 32px by 32px.
What it looks like
Code and Sprites mentioned
Link to mentioned block
Link to mentioned sprite
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
import random
import time
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
#############################################################################
class Collider(Image):
pass
#############################################################################
root = FloatLayout()
class GameScreen(Screen):
def __init__(self, **kwargs):
super(GameScreen, self).__init__(**kwargs)
self.wimg = Basic(size = (32,32), source='sprite.png', pos=(270,-120))
self.block = Collider(size = (32,32), source = 'block.png')
def playy(self):
root.add_widget(self.wimg)
Clock.schedule_interval(self.wimg.update, 1.0 / 60.0)
def worldgen1(self):
self.add_widget(root)
root.add_widget(self.block)
def on_enter(self):
self.worldgen1()
self.playy()
#############################################################################
class Basic(Image):
pFrame = 0
def __init__(self, **kwargs):
super(Basic, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(None, self)
if not self._keyboard:
return
self._keyboard.bind(on_key_down=self.on_keyboard_down)
def on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'left':
self.x -= 10
elif keycode[1] == 'right':
self.x += 10
elif keycode[1] == 'up':
self.y += 10
elif keycode[1] == 'down':
self.y -= 10
else:
return False
return True
def update(self, dt):
self.pFrame += 1
if self.parent.parent.block.collide_widget(self.parent.parent.wimg):
print ("collide with", self.parent.parent.block)
#############################################################################
class MeinApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(GameScreen(name='gameplay'))
return sm
if __name__ == '__main__':
MeinApp().run()
In this case the problem is that FloatLayout uses the size_hint to set the size of the widget when it is added, since it does not set it, they take the value of (1, 1), that is, the size of the window.
The solution is to set size_hint to (None, None), in addition to using allow_stretch in True and keep_ratio in False. In the code I have set the block pos_hint to (0.5, 0.5) and it will anchor it to that position so it will not move, if you want it to be able to move you must set the pos, not the pos_hint.
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
import random
import time
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
#############################################################################
class Collider(Image):
pass
#############################################################################
root = FloatLayout()
class GameScreen(Screen):
def __init__(self, **kwargs):
super(GameScreen, self).__init__(**kwargs)
self.wimg = Basic(size = (32,32), pos=(200, 100), source='sprite.png', size_hint=(None, None), allow_stretch=True, keep_ratio=False)
self.block = Collider(size = (32,32), pos_hint={'x': 0.5, 'y':0.5}, source = 'block.png', size_hint=(None, None), allow_stretch=True, keep_ratio=False)
def playy(self):
root.add_widget(self.wimg)
Clock.schedule_interval(self.wimg.update, 1.0 / 60.0)
def worldgen1(self):
self.add_widget(root)
root.add_widget(self.block)
def on_enter(self):
self.worldgen1()
self.playy()
#############################################################################
class Basic(Image):
pFrame = 0
def __init__(self, **kwargs):
super(Basic, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(None, self)
if not self._keyboard:
return
self._keyboard.bind(on_key_down=self.on_keyboard_down)
def on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'left':
self.x -= 10
elif keycode[1] == 'right':
self.x += 10
elif keycode[1] == 'up':
self.y += 10
elif keycode[1] == 'down':
self.y -= 10
else:
return False
return True
def update(self, dt):
self.pFrame += 1
if self.parent.parent.block.collide_widget(self.parent.parent.wimg):
print ("collide with", self.parent.parent.block)
#############################################################################
class MeinApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(GameScreen(name='gameplay'))
return sm
if __name__ == '__main__':
MeinApp().run()
I am new to python and have messed around with Kivy a little. This is the first app of my own design I've been tying to make. The goal is for it to be a game where there is a character that moves in all directions around the screen. My problem right now is that I can't get the character widget to display and I don't know if it's a problem with the widget or the image in the widget. When I run the program all I get is a black screen and no errors. Can anyone see where I went wrong?
Also if you have any recommendations in a better way to structure anything it would be appreciated :)
import kivy
kivy.require('1.7.2')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import NumericProperty
from kivy.graphics import Rectangle, Color, Canvas
from kivy.uix.image import Image
class WidgetDrawer(Widget):
def __inti__(self, imageStr, **kwargs):
super(WidgetDrawer,self).__inti__(**kwargs)
with self.canvas:
self.size = (Window.width*.05, Window.width*.05)
self.x = self.center_x
self.y = self.center_y
self.pos = (self.x, self.y)
self.rect_pl = Rectangle(source= imageStr, pos=self.pos, size=self.size)
self.bind(pos=self.update_graphics_pos)
self.rect_pl.pos = self.pos
def update_graphic_pos(self, value):
self.rect_pl.pos = value
def setSize(self, width, height):
self.size = (width,height)
class Player(WidgetDrawer):
impulse_x = 3
impulse_y = 3
winre = -0.1
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
def move(self):
self.x = self.x + self.velocity_x
self.y = self.y + self.velocity_y
if self.x > Window.width*.95 or self.x < Window.width*.05:
velocity_x = 0
if self.y > Window.height*.95 or self.y < Window.height*.05:
velocity_y = 0
def determineVelocity(self):
self.velocity_x = self.impulse_x + self.winre
self.velocity_y = self.impulse_y + self.winre
def update(self):
self.determineVelocity()
self.move()
class GUI(Widget):
def __init___(self, **kwargs):
super(GUI, self).__init__(**kwargs)
self.character = Player(imageStr = './character.png')
self.character.x = Window.width/4
self.character.y = Window.height/2
self.add_widget(self.character)
class GameApp(App):
def build(self):
parent = Widget()
app = GUI()
parent.add_widget(app)
return parent
if __name__ == '__main__':
GameApp().run()
The problem is self.add_widget(self.character) i.e. adding widget in __init__ method. Try to run python main.py -m inspector, Ctrl+E and get to GUI(). No children, nothing. Add children after __init__.
About the structure:
use kv language
use one naming style
fix typos(__inti__ != __init__)
if you have 1.7.2 version, you definitely need to update asap
I am wondering why my 'collide_with_hero' method does not seem to be working? Is there something wrong with my Npcs class?
I am just trying to detect when widgets collide (the hero and the tree widget), I stripped out all the additional code in the method, and I am at the point now where I am just simply trying to detect collision and print something if True. When I run the game and walk my hero character into the tree, nothing prints, nothing happens.
I call self.tree.collide_with_widget in the build. Any advice on what I am doing wrong here?
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.core.audio import SoundLoader
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import FallOutTransition
gamelayout = RelativeLayout(size=(300, 300))
bglayout = RelativeLayout()
class Game(Screen):
pass
class Bg(Image):
def __init__(self, **kwargs):
super(Bg, self).__init__(**kwargs)
self.allow_stretch = True
self.size_hint = (None, None)
self.size = (1440, 1440)
class Npcs(Image):
def __init__(self, **kwargs):
super(Npcs, self).__init__(**kwargs)
def collide_with_hero(self, hero):
if self.collide_widget(hero):
print "you ran into a tree"
#dir1 = self.hero.x - self.x
#if self.x < self.hero.x:
# self.hero.x = self.x + dir1
class MoveableImage(Image):
def __init__(self, **kwargs):
super(MoveableImage, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(None, self)
if not self._keyboard:
return
self._keyboard.bind(on_key_down=self.on_keyboard_down)
self._keyboard.bind(on_key_up=self.on_keyboard_up)
self.size_hint = (.11, .11)
self.y = (Window.height/2.1)
self.app = App.get_running_app()
def on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'left':
self.source = 'selectionscreen/left.zip'
self.anim_delay=.20
if self.x < (Window.width * .25):
bglayout.x += 4
else:
self.x -= 6
elif keycode[1] == 'right':
self.source ='selectionscreen/right.zip'
self.anim_delay=.20
if self.x > (Window.width * .70):
bglayout.x -= 4
else:
self.x += 6
elif keycode[1] == 'down':
self.source ='selectionscreen/right.zip'
self.anim_delay=.20
if self.y < (Window.height * .25):
bglayout.y += 4
else:
self.y -= 6
elif keycode[1] == 'up':
self.source = 'selectionscreen/back.zip'
self.anim_delay=.1
if self.y > (Window.height * .70):
bglayout.y -= 4
else:
self.y += 6
else:
return False
return True
def on_keyboard_up(self, keyboard, keycode):
if keycode[1] == 'left':
self.source = 'selectionscreen/left1.png'
elif keycode[1] == 'right':
self.source ='selectionscreen/right1.png'
elif keycode[1] == 'down':
self.source ='selectionscreen/right1.png'
elif keycode[1] == 'up':
self.source ='selectionscreen/back2.png'
else:
return False
return True
class gameApp(App):
def build(self):
global sm
sm = ScreenManager()
game = Game(name='game')
sm.add_widget(game)
hero = MoveableImage(source='selectionscreen/right1.png', pos=(75, 40))
self.tree = Npcs(source='selectionscreen/tree.zip', pos=(100, 200))
self.tree.collide_with_hero(hero)
self.background=Bg(source='selectionscreen/background9.png')
#add widgets to bglayout
bglayout.add_widget(self.background)
bglayout.add_widget(self.tree)
#add bglayout and moveable hero to gamelayout
gamelayout.add_widget(bglayout)
gamelayout.add_widget(hero)
game.add_widget(gamelayout)
return sm
if __name__ == '__main__':
gameApp().run()
You need a main game loop to check for collision after some interval in time or on a keypress event. You can take a look at the Pong example here: http://kivy.org/docs/tutorials/pong.html to get an idea about how to achieve that.
More specifically start reading from this section: http://kivy.org/docs/tutorials/pong.html#adding-ball-animation.
Clock.schedule_interval(game.update, 1.0/60.0)
It uses Clock.schedule_interval to schedule a main loop function called "update".
def update(self, dt):
self.ball.move()
#bounce off top and bottom
if (self.ball.y < 0) or (self.ball.top > self.height):
self.ball.velocity_y *= -1
#bounce off left and right
if (self.ball.x < 0) or (self.ball.right > self.width):
self.ball.velocity_x *= -1
You will need to write the collision detection code in a function like that. If your game involves more complex Physics simulation then you may consider using a library like http://box2d.org/. It will manage all the collisions and stuff for you.
First, you made self.tree an Image, but this doesn't have a collide_with_hero method. You need to make it an instance of the new class you defined, Npcs.
Second, you didn't call the collide_with_hero method. You need to do self.tree.collide_with_hero(hero) to actually call it including passing your hero as an argument to the function.