Combining two functions in one - python

How can I combine functions mark_block and mark_cell into single function?
import numpy as np
class Board:
def __init__(self):
self.cells = np.zeros((3, 3, 3, 3))
self.block = np.zeros((3, 3))
def mark_block(self, main_row, main_col, player):
self.block[main_row][main_col] = player
def mark_cell(self, main_row, main_col, row, col, player):
self.cells[main_row][main_col][row][col] = player
EDIT: Would it also be possible to do it without if statement?

import numpy as np
class Board:
def __init__(self):
self.cells = np.zeros((3, 3, 3, 3))
self.block = np.zeros((3, 3))
def mark(self, main_row, main_col, player, row=None, col=None):
if row is None and col is None:
self.block[main_row][main_col] = player
else:
self.cells[main_row][main_col][row][col] = player

Related

superwires meltdown cant get animation to work

hey i am not using livewires or pygame but superwires and i have little to no information on how to animate characters and sprites with sprite sheet, i get a weird error when i try to use this code
import os, math
from superwires import games
from spriteUtils import *
class Stone(games.Sprite):
def __init__(self, x, y, tag):
self.spliced_x = 60
self.spliced_y = 92
self.filename = f"explosed-Big-sprite.png"
self.anim_list = load_sliced_sprites(self.spliced_x, self.spliced_y, self.filename)
self.tag = tag
self.obj_image = games.load_image(f"stone.png", transparent = True)
super(Stone, self).__init__(image = self.obj_image,
x = x,
y = y,
is_collideable=True)
def check_collision(self):
for Character in self.overlapping_sprites:
if(Character == None):
explode = games.Animation(images= [f"explosed-Big-sprite.png"],
x= self.x,
y = self.y,
n_repeats = 0,
repeat_interval = 5)
explode,images = self.anim_list
else:
''' explode = games.Animation(images= self.anim_list,
x= self.x,
y = self.y,
n_repeats = -10,
repeat_interval = 10)
games.screen.add(explode) '''
return
def update(self):
explode = games.Animation(images = [f"explosed-Big-sprite.png"],
x = self.spliced_x,
y = self.spliced_y,
n_repeats = 10,
repeat_interval = 10,
is_collideable = True)
explode.images = self.anim_list
games.screen.add(explode)
self.check_collision()
i can get a image of frame but not the frames by frame animation. The independent frames wont animate right either. Superwire is really giving me a headache, Help?!

Create an inventory for a python game

So I try to create an inventory for the python game Dodger. In the inventory I want to be able to select different players to play the game. But when I run the game, only the option images/player.png is chosen. How can I fix that? thanks
This is what I have tried so far:
//Inventory.py
import pygame
import pygwidgets
import pyghelpers
import random
from Player import Player
import Constants
from Constants import *
class Inventory(pyghelpers.Scene):
def __init__(self, window):
self.window = window
self.player = Player(window)
self.player0 = pygwidgets.CustomButton(self.window, (30, 250), 'images/player_inv.png')
self.player1 = pygwidgets.CustomButton(self.window, (280, 250), 'images/player1_inv.jpg')
self.player2 = pygwidgets.CustomButton(self.window, (30, 450), 'images/char1_inv.png')
self.inventory = []
self.image = pygwidgets.Image(self.window,(0, 0),'images/inventory.png')
self.quitButton = pygwidgets.CustomButton(self.window,
(30, 650),
up='images/quitNormal.png',
down='images/quitDown.png',
over='images/quitOver.png',
disabled='images/quitDisabled.png')
self.backButton = pygwidgets.CustomButton(self.window,
(240, 650),
up='images/backNormal.png',
down='images/backDown.png',
over='images/backOver.png',
disabled='images/backDisabled.png')
def getSceneKey(self):
return SCENE_INVENTORY
def enter(self, data):
pass
def handleInputs(self, eventsList, keyPressedList):
for event in eventsList:
if self.quitButton.handleEvent(event):
self.quit()
elif self.backButton.handleEvent(event):
self.goToScene(Constants.SCENE_PLAY)
if self.player0.handleEvent(event):
self.player.imagelink = 'images/player.png'
self.goToScene(Constants.SCENE_PLAY)
elif self.player1.handleEvent(event):
self.player.imagelink = 'images/player1.jpg'
self.goToScene(Constants.SCENE_PLAY)
elif self.player2.handleEvent(event):
self.player.imagelink = 'images/player2.png'
self.goToScene(Constants.SCENE_PLAY)
def update(self):
pass
def draw(self):
self.image.draw()
self.quitButton.draw()
self.backButton.draw()
self.player0.draw()
self.player1.draw()
self.player2.draw()
//Player.py
import pygame
import pygwidgets
from Constants import *
class Player():
def __init__(self, window):
self.window = window
self.imagelink = 'images/player.png'
self.image = pygwidgets.Image(window,
(-100, -100), self.imagelink)
playerRect = self.image.getRect()
self.maxX = WINDOW_WIDTH - playerRect.width
self.maxY = GAME_HEIGHT - playerRect.height
# Every frame, move the Player icon to the mouse position
# Limits the x- and y-coordinates to the game area of the window
def update(self, x, y):
if x < 0:
x = 0
elif x > self.maxX:
x = self.maxX
if y < 0:
y = 0
elif y > self.maxY:
y = self.maxY
self.image.setLoc((x, y))
return self.image.getRect()
def draw(self):
self.image.draw()
enter image description here
With your code Player.imagelink = 'images/player1.jpg', you are modifying a class attribute and not a class instance attribute. You can fix this by changing self.player.imagelink = 'images/player1.jpg'. You will need to make similar changes for each line that includes Player.imagelink = ...

Checking for last entity position to move the entity randomly to somewhere else

I am trying to make a game like grindshot in aimlab using ursina engine. I need to move the targets each time you click on them. They should move somewhere where already isn´t any target. This part works but they ocassionally don´t change the position because they are randomly moved to the same position as they were before I think. (It sometimes takes 2 clicks to move the target)
I tried to create a new variable (previousposition) in which I stored the previous position but it didn´t work and the program froze. I think its because the variable changes with the new position and then it goes to an endless loop. Please help.
import random
from ursina.prefabs.first_person_controller import FirstPersonController
class Cube(Entity):
def __init__(self, position = (0,0,0)):
super().__init__(
position = position,
model = "cube",
origin_y = 0.5,
texture = "white_cube",
color = color.white,
collider= 'box')
class Target(Button):
def __init__(self, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
super().__init__(
parent = scene,
position = position,
model = "cube",
origin_y = 0.5,
texture = "white_cube",
color = color.red,
highlight_color = rgb(255, 88, 74),
scale = scale)
def input(self, key):
if self.hovered:
if key == "left mouse down":
mouse.hovered_entity.x = random.randint(-2,2)
mouse.hovered_entity.y = random.randint(1, 4)
while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
mouse.hovered_entity.x = random.randint(-2, 2)
mouse.hovered_entity.y = random.randint(1, 4)
app = Ursina()
target1 = Target(position = (0,3, 5))
target2 = Target(position = (1,4, 5))
target3 = Target(position = (2,2, 5))
for x in range(9):
for z in range(9):
floor = Cube(position = (x-4,0,z-4))
player = FirstPersonController()
app.run()
__________________________________________________________________________________________________
#Not Working
from ursina import *
import random
from ursina.prefabs.first_person_controller import FirstPersonController
class Cube(Entity):
def __init__(self, position = (0,0,0)):
super().__init__(
position = position,
model = "cube",
origin_y = 0.5,
texture = "white_cube",
color = color.white,
highlight_color = color.red,
collider= 'box')
class Target(Button):
def __init__(self, previousposition, position = (0,0,0), scale = (0.7, 0.7, 0.7)):
super().__init__(
parent = scene,
position = position,
model = "cube",
origin_y = 0.5,
texture = "white_cube",
color = color.red,
highlight_color = color.red,
scale = scale)
self.previousposition = previousposition
def input(self, key):
if self.hovered:
if key == "left mouse down":
mouse.hovered_entity.position = self.previousposition
mouse.hovered_entity.x = random.randint(-2,2)
mouse.hovered_entity.y = random.randint(1, 4)
while target1.position == target2.position or target1.position == target3.position or target2.position == target3.position:
mouse.hovered_entity.x = random.randint(-2, 2)
mouse.hovered_entity.y = random.randint(1, 4)
while self.previousposition == target1.position or target2.position or target3.position:
mouse.hovered_entity.x = random.randint(-2, 2)
mouse.hovered_entity.y = random.randint(1, 4)
app = Ursina()
target1 = Target((0,0,0), position = (0,3, 5))
target2 = Target((0,0,0), position = (1,4, 5))
target3 = Target((0,0,0), position = (2,2, 5))
for x in range(9):
for z in range(9):
floor = Cube(position = (x-4,0,z-4))
player = FirstPersonController()
app.run()
Instead of generating a position and checking it it's not the same, avoid that position in the first place:
Generate a list of possible positions. You can change the range for different values. This will make a list like this: [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
import itertools
possible_positions = [[(x,y) for y in range(4)] for x in range(3)]
possible_positions = list(itertools.chain(*possible_positions)) # flatten list
Use list comprehension to remove the current position from possible positions and choose a random element from the new list:
entity.position = random.choice([coordinate for coordinate in possible_positions if coordinate != (int(entity.x), int(entity.y))])

tkinter not letting 2 threads run at once

I have a game and I have the world moving towards you, and you can jump at the same time. both functions work separately, but they don't work when used together. sometimes it gives me an error(ValueError: could not convert string to float: expected) couldnt convert, sometimes the character does a weird jittery motion, sometimes it does both, and sometimes it just crashes. this is my code
import Tkinter as tkinter
import thread
from time import sleep
def is_even(n):
if n % 2 == 0:
retVal = True
else:
retVal = False
return retVal
class gameScreen:
def move(self, event):
d = self.getdir(event.keysym)
self.canvas.move(self.char, d[0], d[1])
self.canvas.update()
if self.collision():
self.canvas.move(self.char, -d[0], -d[1])
def fall(self):
speed = .01
x = 0
while not self.collision():
self.canvas.move(self.char, 0, 1)
self.canvas.update()
sleep(speed)
if x == 2:
speed -= speed *.04
x = 0
else:
x += 1
self.canvas.move(self.char, 0, -1)
def jump(self):
j = 0
from time import sleep
jump = [6, 6, 6, 6, 4, 4, 2, 1, 0]
for i in range(0, (len(jump)*2)):
x = jump[j]
self.canvas.move(self.char, 0, -x)
if not is_even(i):
j +=1
self.canvas.update()
sleep(.05)
self.fall()
def getLast(self, lvl):
x = 0
for i in lvl:
coords = self.canvas.coords(i)
if x < coords[3]:
x = coords[3]
last = i
return last
def gameThread(self, event):
thread.start_new_thread(self.gameStart, ())
def gameStart(self, event=None):
from time import sleep
last = self.getLast(self.lvl1)
coords = self.canvas.coords(last)
while coords[2] > 0:
print coords[2]
for i in self.lvl1:
self.canvas.move(i, -1, 0)
coords = self.canvas.coords(last)
self.canvas.update()
sleep(.002)
if not self.touchingGround(event):
self.fall()
def touchingGround(self, event = None):
self.canvas.move(self.char, 0, 5)
if self.collision():
retVal = True
else:
retVal = False
self.canvas.move(self.char, 0, -5)
return retVal
def onKey(self, event):
if self.touchingGround(event):
thread.start_new_thread(self.jump, ())
def collision(self):
coords = self.canvas.coords(self.char)
collision = len(self.canvas.find_overlapping(coords[0]-1,
coords[1]-1,
coords[2]-1,
coords[3]-1)) >=2
return collision
def getdir(self, s):
direction = {"Left":[-5, 0], "Right":[5, 0]}
try:
retVal = direction[s]
except KeyError:
retVal =False
return retVal
def __init__(self, master):
self.lvl1 = []
self.objects = []
self.master = master
master.attributes("-fullscreen", True)
master.title("Game")
self.width=master.winfo_screenwidth()
self.height=master.winfo_screenheight()
self.canvas = tkinter.Canvas(master, width=self.width,
height=self.height)
self.canvas.pack(expand="YES",fill="both")
self.objects.append(self.canvas.create_rectangle(0, self.height,
self.width,
self.height-100,
fill="grey"))
self.lvl1.append(self.canvas.create_rectangle(self.width,
self.height-100,
self.width + 100,
self.height-150,
fill="grey"))
self.objects.extend(self.lvl1)
self.char = self.canvas.create_rectangle((self.width/2)-25,
self.height- 100,
(self.width/2)+25,
self.height-150,
fill="red")
self.x = 0
self.y = 0
master.bind("<Key-Up>", self.onKey)
master.bind("<Return>", self.onKey)
def destroy(event):
root.destroy()
root = tkinter.Tk()
my_gui = gameScreen(root)
root.bind("<Escape>", destroy)
root.mainloop()
i tried adding the afters like tadhg said, but it still only jumps sometimes, and most of the time it dosent do a full jump, or just goes up one or two pixels, then goes back down, then repeats for the amount of time it should be jumping.

Animating Sprites in Python

I am pretty new at coding, and am wondering how I would animate my sprite to look like it is actually moving. I think I have a general idea, but honestly I do not know where to start in my code to insert the different images and make it look like it's moving. This is my code, any tips are greatly appreciated.
SCREEN_SIZE = (1024, 768)
import sys
import pygame
from pygame.locals import *
from random import randint, choice
from Vector2 import Vector2
NEST_POSITION = (SCREEN_SIZE[0]/2, SCREEN_SIZE[1]/2)
NEST_POSITION_VECTOR2 = Vector2(NEST_POSITION)
ANT_COUNT = 20
NEST_SIZE = 100.
class State(object):
def __init__(self, name):
self.name = name
def do_actions(self):
pass
def check_conditions(self):
pass
def entry_actions(self):
pass
def exit_actions(self):
pass
class StateMachine(object):
def __init__(self):
self.states = {}
self.active_state = None
def add_state(self, state):
self.states[state.name] = state
def think(self):
if self.active_state is None: return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if new_state_name is not None:
self.set_state(new_state_name)
def set_state(self, new_state_name):
if self.active_state is not None:
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions()
class World(object):
def __init__(self):
self.entities = {}
self.entity_id = 0
self.background = pygame.surface.Surface(SCREEN_SIZE).convert()
self.background.fill((255, 255, 255))
pygame.draw.circle(self.background, (200, 255, 200), NEST_POSITION, int(NEST_SIZE))
def add_entity(self, entity):
self.entities[self.entity_id] = entity
entity.id = self.entity_id
self.entity_id += 1
def remove_entity(self, entity):
del self.entities[entity.id]
def get(self, entity_id):
if entity_id in self.entities:
return self.entities[entity_id]
else:
return None
def process(self, time_passed):
time_passed_seconds = time_passed / 1000.0
for entity in self.entities.values():
entity.process(time_passed_seconds)
def render(self, surface):
surface.blit(self.background, (0, 0))
for entity in self.entities.itervalues():
entity.render(surface)
def get_close_entity(self, name, location, range=100.):
for entity in self.entities.itervalues():
if (entity.name == name):
distance = location.get_distance_to(entity.location)
if (distance < range):
return entity
return None
############################# GameEntity ####################################
## This is a "template" object - that is, we never actually create one of
## these objects in the game.
## This object is used as a base templet for other game objects that "extend"
## or "inherit from" this object.
## The leaf, Spider and And objects all extend the GameEntity object
class GameEntity(object):
def __init__(self, world, name, image):
self.world = world
self.name = name
self.image = image
self.location = Vector2(0, 0)
self.destination = Vector2(0, 0)
self.speed = 0.
self.brain = StateMachine()
self.id = 0
def render(self, surface):
w, h = self.image.get_size()
surface.blit(self.image, (self.location.x-w/2, self.location.y-h/2))
def process(self, time_passed):
self.brain.think()
if ((self.speed > 0.) and (self.location != self.destination)):
vec_to_destination = self.destination - self.location
distance_to_destination = vec_to_destination.get_magnitude()
heading = vec_to_destination.get_normalized()
travel_distance = min(distance_to_destination, time_passed * self.speed)
self.location += heading * travel_distance
############################# Leaf ##########################################
class Leaf(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "leaf", image)
############################# Ant ##########################################
class Spider(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "spider", image)
self.dead_image = pygame.transform.flip(image, 0, 1)
self.health = 25
self.speed = 50. + randint(-20, 20)
def bitten(self):
self.health -= 1
if (self.health <= 0):
self.speed = 0.
self.image = self.dead_image
self.speed = 140.
def render(self, surface):
GameEntity.render(self, surface)
w, h = self.image.get_size()
bar_x = self.location.x - 12
bar_y = self.location.y + h/2
surface.fill( (255, 0, 0), (bar_x, bar_y, 25, 4))
surface.fill( (0, 255, 0), (bar_x, bar_y, self.health, 4))
def process(self, time_passed):
if (self.location.x > SCREEN_SIZE[0] + 2):
self.world.remove_entity(self)
return
GameEntity.process(self, time_passed)
############################# Ant ##########################################
class Ant(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "ant", image)
exploring_state = AntStateExploring(self)
seeking_state = AntStateSeeking(self)
delivering_state = AntStateDelivering(self)
hunting_state = AntStateHunting(self)
self.brain.add_state(exploring_state)
self.brain.add_state(seeking_state)
self.brain.add_state(delivering_state)
self.brain.add_state(hunting_state)
self.carry_image = None
def carry(self, image):
self.carry_image = image
def drop(self, surface):
if self.carry_image:
x = self.location.x
y = self.location.y
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2))
self.carry_image = None
def render(self, surface):
GameEntity.render(self, surface)
if (self.carry_image):
x = self.location.x
y = self.location.y
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2))
############################# AntStateExploring #############################
class AntStateExploring(State):
def __init__(self, ant):
State.__init__(self, "exploring")
self.ant = ant
def random_destination(self):
w, h = SCREEN_SIZE
self.ant.destination = Vector2(randint(0, w), randint(0, h))
def do_actions(self):
if (randint(1, 20) == 1):
self.random_destination()
def check_conditions(self):
leaf = self.ant.world.get_close_entity("leaf", self.ant.location)
if (leaf is not None):
self.ant.leaf_id = leaf.id
return "seeking"
spider = self.ant.world.get_close_entity("spider", NEST_POSITION_VECTOR2, NEST_SIZE)
if (spider is not None):
if (self.ant.location.get_distance_to(spider.location) < 100.):
self.ant.spider_id = spider.id
return "hunting"
return None
def entry_actions(self):
self.ant.speed = 120. + randint(-30, 30)
self.random_destination()
############################# AntStateSeeking ###############################
class AntStateSeeking(State):
def __init__(self, ant):
State.__init__(self, "seeking")
self.ant = ant
self.leaf_id = None
def check_conditions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if (leaf is None): return "exploring"
if (self.ant.location.get_distance_to(leaf.location) < 5.0):
self.ant.carry(leaf.image)
self.ant.world.remove_entity(leaf)
return "delivering"
return None
def entry_actions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if (leaf is not None):
self.ant.destination = leaf.location
self.ant.speed = 160. + randint(-20, 20)
############################# AntStateDelivering ############################
class AntStateDelivering(State):
def __init__(self, ant):
State.__init__(self, "delivering")
self.ant = ant
def check_conditions(self):
if (self.ant.location.get_distance_to(NEST_POSITION) < NEST_SIZE):
if (randint(1, 10) == 1):
self.ant.drop(self.ant.world.background)
return "exploring"
return None
def entry_actions(self):
self.ant.speed = 60.
random_offset = Vector2(randint(-20, 20), randint(-20, 20))
self.ant.destination = random_offset + NEST_POSITION
############################# AntStateHunting ###############################
class AntStateHunting(State):
def __init__(self, ant):
State.__init__(self, "hunting")
self.ant = ant
self.got_kill = False
def do_actions(self):
spider = self.ant.world.get(self.ant.spider_id)
if (spider is None): return
self.ant.destination = spider.location
if (self.ant.location.get_distance_to(spider.location) < 15.):
if (randint(1, 5) == 1):
spider.bitten()
if (spider.health <= 0):
self.ant.carry(spider.image)
self.ant.world.remove_entity(spider)
self.got_kill = True
def check_conditions(self):
if (self.got_kill): return "delivering"
spider = self.ant.world.get(self.ant.spider_id)
if (spider is None): return "exploring"
if (spider.location.get_distance_to(NEST_POSITION) > NEST_SIZE * 3):
return "exploring"
return None
def entry_actions(self):
self.speed = 160. + randint(0, 50)
def exit_actions(self):
self.got_kill = False
############################# Set up Game ###############################
def run():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("The Super Amazing Ant Simulation")
world = World()
w, h = SCREEN_SIZE
clock = pygame.time.Clock()
ant_image = pygame.image.load("ant.png").convert_alpha()
ant2_image = pygame.image.load("ant6.gif").convert_alpha()
ant3_image = pygame.image.load("ant7.gif").convert_alpha()
leaf_image = pygame.image.load("leaf.png").convert_alpha()
spider_image = pygame.image.load("spider.png").convert_alpha()
############# Place ants in starting locations #########################
for ant_no in xrange(ANT_COUNT):
ant = Ant(world, ant_image)
ant.location = Vector2(randint(0, w), randint(0, h))
ant.brain.set_state("exploring")
world.add_entity(ant)
############################# Game Loop ###############################
while (True):
for event in pygame.event.get():
if (event.type == QUIT):
pygame.quit()
return
time_passed = clock.tick(30)
if (randint(1, 50) == 1):
leafX = randint(0, w)
leafY = randint(0, h)
numberOfLeafs = randint(5,25)
for leafNumber in range(numberOfLeafs):
leaf = Leaf(world, leaf_image)
leaf.location = Vector2(leafX, leafY)
world.add_entity(leaf)
if (randint(1, 100) == 1):
spider = Spider(world, spider_image)
spider.location = Vector2(-50, randint(0, h))
spider.destination = Vector2(w+50, randint(0, h))
world.add_entity(spider)
world.process(time_passed)
world.render(screen)
pygame.display.update()
############################# Call run to start game #########################
try:
if (Vector2.version() != "Version 2014-04-09"):
raise()
except:
print "****ERROR**** Vector2 version mis-matched with AntSimulation.py"
sys.exit()
run()
In pygame, an animation is just multiple images played in a sequence. I'm assuming that because you are wanting to animate a sprite you already have an image sequence in mind to use.
Here is a basic example of an animation class (you will probably want to add quite a bit of functionality to this):
class Animation(object):
def __init__(self, image_list):
self.image_list = image_list #a list of pygame images
self.total_frames = len(image_list)
self.index = 0
def next(self):
image = self.image_list[self.index]
self.index = (self.index+1) % self.total_frames #loops back around
return image
Now, in your sprite class, when you are ready to switch to the next frame of your animation:
self.image = my_animation.next()

Categories

Resources