Code: Alles auswählen
import pygame
import random
import thread
import time
class RanWorm:
def __init__(self, surface, x, y, length):
self.surface = surface
self.x = x
self.y = y
self.length = length
self.dir_x = 0
self.dir_y = -1
self.body = []
self.crashed = False
for event in pygame.event.get():
self.key_event(event)
def key_event(self, event):
""" Tastatur-Ereignisse behandeln. """
zahl=random.randint(1,15)
if zahl == 1:
self.dir_x = 0
self.dir_y = -1
elif zahl == 2:
self.dir_x = 0
self.dir_y = 1
elif zahl == 3:
self.dir_x = -1
self.dir_y = 0
elif zahl == 4:
self.dir_x = 1
self.dir_y = 0
def move(self):
""" Wurm bewegen. """
self.x += self.dir_x
self.y += self.dir_y
if (self.x, self.y) in self.body:
self.crashed = True
self.body.insert(0, (self.x, self.y))
if len(self.body) > self.length:
self.body.pop()
def draw(self):
for x, y in self.body:
self.surface.set_at((x, y), (255, 255, 255))
class Worm:
""" Ein Wurm. """
def __init__(self, surface, x, y, length):
self.surface = surface
self.x = x
self.y = y
self.length = length
self.dir_x = 0
self.dir_y = -1
self.body = []
self.crashed = False
def key_event(self, event):
""" Tastatur-Ereignisse behandeln. """
if event.key == pygame.K_UP:
self.dir_x = 0
self.dir_y = -1
elif event.key == pygame.K_DOWN:
self.dir_x = 0
self.dir_y = 1
elif event.key == pygame.K_LEFT:
self.dir_x = -1
self.dir_y = 0
elif event.key == pygame.K_RIGHT:
self.dir_x = 1
self.dir_y = 0
def move(self):
""" Wurm bewegen. """
self.x += self.dir_x
self.y += self.dir_y
if (self.x, self.y) in self.body:
self.crashed = True
self.body.insert(0, (self.x, self.y))
if len(self.body) > self.length:
self.body.pop()
def draw(self):
for x, y in self.body:
self.surface.set_at((x, y), (255, 255, 255))
# Spielfeld-Abmessungen
width = 640
height = 400
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
running = True
# Unser Wurm ;-).
w = Worm(screen, width/2, height/2, 200)
r=RanWorm(screen, width/2, height/2, 200)
while running:
screen.fill((0, 0, 0))
w.move()
r.move()
w.draw()
def gegner():
while 1:
w.move()
w.draw()
time.sleep(0.1)
thread.start_new_thread(gegner,())
if w.crashed or w.x <= 0 or w.x >= width-1 or w.y <= 0 or w.y >= height-1:
print "Crash!"
running = False
if r.crashed or r.x <= 0 or r.x >= width-1 or r.y <= 0 or r.y >= height-1:
print "Win!"
running = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
w.key_event(event)
pygame.display.flip()
clock.tick(240)
Da kommt immer der Fehler raus, es startet nur die eine schlange und man kann einmal die richtung wechseln. Bei zweiten Mal steht dann immer Crash da.
Danke für Hilfe!