Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with game
#21
(Nov-14-2017, 09:23 PM)metulburr Wrote: if you remove the elif, to have all if, you can do two angles at the same time making it more "natural" feeling
(Nov-14-2017, 08:40 PM)Windspar Wrote: here a pygame example
import pygame
pygame.init()

SCREEN = 600, 400

class Bullet:
    def __init__(self, x, y, color, movement):
        self.position = [x - movement[0], y - movement[1]]
        self.color = color
        self.movement = movement

    def blit(self, surface):
        self.position[0] += self.movement[0]
        self.position[1] += self.movement[1]
        position = int(self.position[0]), int(self.position[1])
        pygame.draw.circle(surface, self.color, position, 3)

class Ship:
    def __init__(self, x, y, color, pointlist):
        self.position = [x, y]
        self.pointlist = pointlist
        self.color = color

    def move(self, x, y):
        self.position[0] += x
        self.position[1] += y

    def blit(self, surface):
        points = []
        for point in self.pointlist:
            points.append((self.position[0] + point[0], self.position[1]  + point[1]))

        pygame.draw.polygon(surface, self.color, points)

class Pauser:
    def __init__(self, length):
        self.length = length
        self.last_tick = 0

    def elaspe(self, ticks):
        if ticks > self.last_tick + self.length:
            self.last_tick = ticks
            return True
        return False

class App:
    def __init__(self):
        pygame.display.set_caption("Invaders")
        # create are screen. Your main surface
        self.screen = pygame.display.set_mode(SCREEN)
        # create a clock for framerate control
        self.clock = pygame.time.Clock()
        self.bullets = []
        self.bullets_pauser = Pauser(300)
        self.ship = Ship(300, 370, (0,0,200), ((0,0), (-20,30), (20,30)))

    def loop(self):
        running = True
        self.ticks = 0
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False

            last_ticks = self.ticks
            self.ticks = pygame.time.get_ticks()
            speed = (self.ticks - last_ticks) * 0.05
            # grab all keys return True if pressed
            key_press = pygame.key.get_pressed()
            # creaate bullets
            if key_press[pygame.K_SPACE]:
                # shoot bullets in intervals
                if self.bullets_pauser.elaspe(self.ticks):
                    x, y = self.ship.position
                    self.bullets.append(Bullet(x, y, (0,0,200), (0,-10)))

            # ship movement
            ship_speed = speed * 3
            if key_press[pygame.K_LEFT]:
                self.ship.move(-ship_speed, 0)
            if key_press[pygame.K_RIGHT]:
                self.ship.move(ship_speed, 0)
            if key_press[pygame.K_UP]:
                self.ship.move(0, -ship_speed)
            if key_press[pygame.K_DOWN]:
                self.ship.move(0, ship_speed)

            # clear screen
            self.screen.fill((0,0,0))
            # blits bullets
            remove_list = []
            for enum, bullet in enumerate(self.bullets):
                if bullet.position[1] < 0:
                    remove_list.append(enum)
                else:
                    bullet.blit(self.screen)

            for enum, index in enumerate(remove_list):
                self.bullets.pop(index - enum)

            self.ship.blit(self.screen)

            pygame.display.flip()
            # frame per seconds
            self.clock.tick(30)

def main():
    app = App()
    app.loop()
    pygame.quit()

if __name__ == '__main__':
    main()

Thank very much metulburr

But I'm looking for a code with the less libraries


Thanks for your concern
Quote
#22
Don't use threading. Every widget has after method. You can have more then one if needed.
Take a look here . You might see another way of doing things.
hammza likes this post
99 percent of computer problems exists between chair and keyboard.
Quote
#23
Windspar

Can I communicate with you in other Facebook or telegram

Iam a self learning like you, I need your advice in how I learn and improve my self.

Thank you again :)
Quote
#24
One thing i classified myself as a Novice. Right now I am trying to learn concept of programming like (message bus / event bus) ways to prevent spaghetti code.

Just to let you know. I never use tkinter for anything. Just my preference to use wxpython , pygame, pysfml.
To help you i just read the docs and google some info.

Best way of learning write the code until it works. Then rewrite using a different way.
Write a small program using function. Then rewrite using classes. The rewrite using dict.

You always can contact me here. Even personal message me here. But the community as a whole can help you more.

If you need to understand classes
a = 1 # variable instance
class MyClass(object):
    a = 2 # class instance. only created once even if you create 50 objects.
    # reason it created once because if a class instance not a object instance.

    # just a builtin constructor for objects. Create a new object each time it called
    def __init__(self, a): # self = object
        self.a = a # object instance, does not overwrite class instance

    # object method simlar to a function
    def double(self): # self bring in object
        self.a *= 2

b = MyClass(3) # MyClass.__init__(object, 3) , b = points to object. b is not the object
print(a)
print(MyClass.a) # only difference from (a) is a namespace
print(b.a) # prints object a
print()
c = b # c now points to same object. class are pass by reference
c.double()  # b and c, a = 6. MyClass.double(object)
print(b.a)
print(c.a)
hammza likes this post
99 percent of computer problems exists between chair and keyboard.
Quote
#25
Windspar

Thank you for everything

You're the best helper ever met


Maybe I need more time to learn, because I know the basics, but making programs is hard thing.

I need to review your code step by step to understand every line, and why you use it.
Quote
#26
example using function and dict
import tkinter as tk

game = {}

def create_pauser(length):
    return { 'length':length,
             'last tick':0 }

def pauser_elaspe(pauser, ticks):
    if ticks > pauser['last tick'] + pauser['length']:
        pauser['last tick'] = ticks
        return True
    return False

def create_bullet(canvas, x, y, color, mx, my):
    return {'id': canvas.create_oval(x -3 , y - 3, x + 3, y + 3, fill=color),
            'movement': {'x':mx, 'y':my} }

def bullet_move(canvas, bullet):
    canvas.move(bullet['id'], bullet['movement']['x'], bullet['movement']['y'])

def create_ship(canvas,x, y, color):
    return canvas.create_polygon(x, y, x - 20, y + 30, x + 20, y + 30, fill=color)

def go_press(event):
    global game
    game['keys press'][event.keysym] = True

def go_release(event):
    global game
    game['keys press'][event.keysym] = False

def shoot():
    global game
    x, y = game['canvas'].coords(game['ship'])[:2]
    game['bullets'].append(create_bullet(game['canvas'], x, y, 'blue', 0, -10))

def game_loop():
    global game
    remove_bullets = []
    for enum, bullet in enumerate(game['bullets']):
        coords = game['canvas'].coords(bullet['id'])
        if coords[0] < 0 or coords[1] < 0 or coords[2] > game['SCREEN SIZE']['w']:
            remove_bullets.append(enum)
            game['canvas'].delete(bullet['id'])
        else:
            bullet_move(game['canvas'], bullet)

    for enum, index in enumerate(remove_bullets):
        game['bullets'].pop(index - enum)

    # moving ship
    if game['keys press'].get('Left', False):
        game['canvas'].move(game['ship'], -game['ship speed'], 0)
    if game['keys press'].get('Right', False):
        game['canvas'].move(game['ship'], game['ship speed'], 0)
    if game['keys press'].get('Up', False):
        game['canvas'].move(game['ship'], 0, -game['ship speed'])
    if game['keys press'].get('Down', False):
        game['canvas'].move(game['ship'], 0, game['ship speed'])
    if game['keys press'].get('space', False):
        if pauser_elaspe(game['shoot pauser'], game['ticks']):
            shoot()

    game['ticks'] += 1
    game['root'].after(int(1000 / 30), game_loop)

def main():
    global game
    game['SCREEN SIZE'] = {'w':600, 'h':400}
    game['root'] = tk.Tk()
    game['canvas'] = tk.Canvas(game['root'], width=game['SCREEN SIZE']['w'], height=game['SCREEN SIZE']['h'])
    game['canvas'].pack()
    game['bullets'] = []
    game['ticks'] = 0
    game['shoot pauser'] = create_pauser(12)
    game['keys press'] = {}
    game['ship'] = create_ship(game['canvas'], 300, 370, 'blue')
    game['ship speed'] = 5

    # you can use root or canvas here it all goes to the same place
    game['root'].bind_all('<KeyPress>', go_press)
    game['root'].bind_all('<KeyRelease>', go_release)
    game_loop()
    game['root'].mainloop()

if __name__ == '__main__':
    main()

example using a class as a global container
import tkinter as tk

# store variable here
class Game:
    pass

def create_pauser(length):
    return { 'length':length,
             'last tick':0 }

def pauser_elaspe(pauser, ticks):
    if ticks > pauser['last tick'] + pauser['length']:
        pauser['last tick'] = ticks
        return True
    return False

def create_bullet(canvas, x, y, color, mx, my):
    return {'id': canvas.create_oval(x -3 , y - 3, x + 3, y + 3, fill=color),
            'movement': {'x':mx, 'y':my} }

def bullet_move(canvas, bullet):
    canvas.move(bullet['id'], bullet['movement']['x'], bullet['movement']['y'])

def create_ship(canvas,x, y, color):
    return canvas.create_polygon(x, y, x - 20, y + 30, x + 20, y + 30, fill=color)

def go_press(event):
    Game.keys_press[event.keysym] = True

def go_release(event):
    Game.keys_press[event.keysym] = False

def shoot():
    x, y = Game.canvas.coords(Game.ship)[:2]
    Game.bullets.append(create_bullet(Game.canvas, x, y, 'blue', 0, -10))

def game_loop():
    remove_bullets = []
    for enum, bullet in enumerate(Game.bullets):
        coords = Game.canvas.coords(bullet['id'])
        if coords[0] < 0 or coords[1] < 0 or coords[2] > Game.SCREEN_SIZE['w']:
            remove_bullets.append(enum)
            Game.canvas.delete(bullet['id'])
        else:
            bullet_move(Game.canvas, bullet)

    for enum, index in enumerate(remove_bullets):
        Game.bullets.pop(index - enum)

    # moving ship
    if Game.keys_press.get('Left', False):
        Game.canvas.move(Game.ship, -Game.ship_speed, 0)
    if Game.keys_press.get('Right', False):
        Game.canvas.move(Game.ship, Game.ship_speed, 0)
    if Game.keys_press.get('Up', False):
        Game.canvas.move(Game.ship, 0, -Game.ship_speed)
    if Game.keys_press.get('Down', False):
        Game.canvas.move(Game.ship, 0, Game.ship_speed)
    if Game.keys_press.get('space', False):
        if pauser_elaspe(Game.shoot_pauser, Game.ticks):
            shoot()

    Game.ticks += 1
    Game.root.after(int(1000 / 30), game_loop)

def main():
    Game.SCREEN_SIZE = {'w':600, 'h':400}
    Game.root = tk.Tk()
    Game.canvas = tk.Canvas(Game.root, width=Game.SCREEN_SIZE['w'], height=Game.SCREEN_SIZE['h'])
    Game.canvas.pack()
    Game.bullets = []
    Game.ticks = 0
    Game.shoot_pauser = create_pauser(12)
    Game.keys_press = {}
    Game.ship = create_ship(Game.canvas, 300, 370, 'blue')
    Game.ship_speed = 5

    # you can use root or canvas here it all goes to the same place
    Game.root.bind_all('<KeyPress>', go_press)
    Game.root.bind_all('<KeyRelease>', go_release)
    game_loop()
    Game.root.mainloop()

if __name__ == '__main__':
    main()
hammza likes this post
99 percent of computer problems exists between chair and keyboard.
Quote
#27
Every time you impress Me with your skills

I was nearly to give up, and leave the python programming to study assembly and c Lang.


That way proves that there is another solutions without using mush libraries,

You need just an open mind and basic skills to make whatever you want.

Thank you very much man.


And by the way, I remarked some thing

When I push space bar, and keep shooting, that ship can move in all the ways, accept (up+left), it stops until i stop pushing space bar.

Why is this happening??
Quote
#28
Quote:And by the way, I remarked some thing

When I push space bar, and keep shooting, that ship can move in all the ways, accept (up+left), it stops until i stop pushing space bar.

Why is this happening??
My examples run find on my computer. I'm using Linux. What is your os ?

You can still take a look at C, but they have no builtin or package GUI.
Hardly anyone uses Assembly. Unless you developing device driver or trying to optimize small piece of code.

Cython is nice when you need to optimize code for python. It C and python together with some restriction.
It build wrapper around c code. Then you import into python. It give you a library to pass with python code.

PyPy that uses a jit(just in time) compiler to make code run faster. There are some restriction.

D a general-purpose programming language. It like C++ and python together in general-purpose programming language.
It has memory safety like python. dmd is good cross platform compiler. dub is great for package building.

Hello World Examples. Bare minium code. Linux compile code.
99 percent of computer problems exists between chair and keyboard.
Quote
#29
Iam using win7 x32,x86

I know about using c codes with python. But I didn't learned those things yet, I'm just with the basics.


And I know about d language, I like it, but there isn't enough information and libraries using it

I found those games years ago, it's really fantastic

https://www.uvlist.net/groups/info/dlanguage
Quote
#30
Curious thou why up + left doesn't work. If every other way is working. Maybe try a different keyboard.
Did you change any code ?

I really like D. It has so many features. I still trying to learn them. D can use all of c libraries but you have to wrap them in.
Derelict is a good source for making games.

You can check some of my code on Github.
99 percent of computer problems exists between chair and keyboard.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)